blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5a7355c7a5879c14d8627a0a9f6b2c291a29953c
20,246,475,896,614
de3c2d89f623527b35cc5dd936773f32946025d2
/src/main/java/com/bytedance/sdk/openadsdk/multipro/p205d/SPMultiHelper.java
e580e83730f60a2182e335f8f023285a355802d7
[]
no_license
ren19890419/lvxing
https://github.com/ren19890419/lvxing
5f89f7b118df59fd1da06aaba43bd9b41b5da1e6
239875461cb39e58183ac54e93565ec5f7f28ddb
refs/heads/master
2023-04-15T08:56:25.048000
2020-06-05T10:46:05
2020-06-05T10:46:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bytedance.sdk.openadsdk.multipro.p205d; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.bytedance.sdk.openadsdk.core.InternalContainer; import com.bytedance.sdk.openadsdk.multipro.TTPathConst; import com.bytedance.sdk.openadsdk.utils.C2564t; import com.tencent.android.tpush.SettingsContentProvider; import com.tencent.mid.sotrage.StorageInterface; import com.tencent.p605ep.common.adapt.iservice.account.AccountConst.ArgKey; import java.util.HashSet; import java.util.Set; /* renamed from: com.bytedance.sdk.openadsdk.multipro.d.a */ public class SPMultiHelper { /* renamed from: a */ private static Context f9095a; /* renamed from: a */ public static boolean m11876a() { if (f9095a != null && InternalContainer.m10059a() != null) { return true; } C2564t.m12219b("The context of SPHelper is null, please initialize sdk in main process"); return false; } /* renamed from: b */ private static ContentResolver m11878b() { try { if (m11876a()) { return m11882c().getContentResolver(); } } catch (Throwable unused) { } return null; } /* renamed from: a */ public static void m11867a(Context context) { f9095a = context == null ? InternalContainer.m10059a() : context.getApplicationContext(); } /* renamed from: c */ private static Context m11882c() { Context context = f9095a; return context == null ? InternalContainer.m10059a() : context; } /* renamed from: d */ private static String m11883d() { StringBuilder sb = new StringBuilder(); sb.append(TTPathConst.f9099b); String str = "/"; sb.append(str); sb.append("t_sp"); sb.append(str); return sb.toString(); } /* renamed from: b */ private static String m11879b(String str) { if (TextUtils.isEmpty(str)) { return ""; } StringBuilder sb = new StringBuilder(); sb.append("?sp_file_name="); sb.append(str); return sb.toString(); } /* renamed from: a */ public static synchronized void m11870a(String str, String str2, Boolean bool) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.BOOLEAN_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, bool); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11874a(String str, String str2, String str3) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.STRING_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, str3); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11872a(String str, String str2, Integer num) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("int"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, num); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11873a(String str, String str2, Long l) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, l); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11871a(String str, String str2, Float f) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.FLOAT_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, f); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11875a(String str, String str2, Set<String> set) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("string_set"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); HashSet hashSet = new HashSet(); for (String replace : set) { hashSet.add(replace.replace(StorageInterface.KEY_SPLITER, "__COMMA__")); } contentValues.put(ArgKey.KEY_VALUE, hashSet.toString()); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: b */ public static String m11880b(String str, String str2, String str3) { if (!m11876a()) { return str3; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.STRING_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); return (type == null || type.equals("null")) ? str3 : type; } } catch (Throwable unused) { } } /* renamed from: a */ public static int m11865a(String str, String str2, int i) { if (!m11876a()) { return i; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("int"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Integer.parseInt(type); } } } } catch (Throwable unused) { } return i; } /* renamed from: a */ public static float m11864a(String str, String str2, float f) { if (!m11876a()) { return f; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.FLOAT_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Float.parseFloat(type); } } } } catch (Throwable unused) { } return f; } /* renamed from: a */ public static boolean m11877a(String str, String str2, boolean z) { if (!m11876a()) { return z; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.BOOLEAN_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Boolean.parseBoolean(type); } } } } catch (Throwable unused) { } return z; } /* renamed from: a */ public static long m11866a(String str, String str2, long j) { if (!m11876a()) { return j; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Long.parseLong(type); } } } } catch (Throwable unused) { } return j; } /* renamed from: b */ public static Set<String> m11881b(String str, String str2, Set<String> set) { String str3 = ", "; if (!m11876a()) { return set; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("string_set"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { if (!type.matches("\\[.*\\]")) { return set; } String[] split = type.substring(1, type.length() - 1).split(str3); HashSet hashSet = new HashSet(); for (String replace : split) { hashSet.add(replace.replace("__COMMA__", str3)); } return hashSet; } } } } catch (Throwable unused) { } return set; } /* renamed from: a */ public static void m11869a(String str, String str2) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); b.delete(Uri.parse(sb.toString()), null, null); } } catch (Throwable unused) { } } } /* renamed from: a */ public static void m11868a(String str) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("clean"); sb.append(m11879b(str)); b.delete(Uri.parse(sb.toString()), null, null); } } catch (Throwable unused) { } } } }
UTF-8
Java
14,898
java
SPMultiHelper.java
Java
[]
null
[]
package com.bytedance.sdk.openadsdk.multipro.p205d; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.text.TextUtils; import com.bytedance.sdk.openadsdk.core.InternalContainer; import com.bytedance.sdk.openadsdk.multipro.TTPathConst; import com.bytedance.sdk.openadsdk.utils.C2564t; import com.tencent.android.tpush.SettingsContentProvider; import com.tencent.mid.sotrage.StorageInterface; import com.tencent.p605ep.common.adapt.iservice.account.AccountConst.ArgKey; import java.util.HashSet; import java.util.Set; /* renamed from: com.bytedance.sdk.openadsdk.multipro.d.a */ public class SPMultiHelper { /* renamed from: a */ private static Context f9095a; /* renamed from: a */ public static boolean m11876a() { if (f9095a != null && InternalContainer.m10059a() != null) { return true; } C2564t.m12219b("The context of SPHelper is null, please initialize sdk in main process"); return false; } /* renamed from: b */ private static ContentResolver m11878b() { try { if (m11876a()) { return m11882c().getContentResolver(); } } catch (Throwable unused) { } return null; } /* renamed from: a */ public static void m11867a(Context context) { f9095a = context == null ? InternalContainer.m10059a() : context.getApplicationContext(); } /* renamed from: c */ private static Context m11882c() { Context context = f9095a; return context == null ? InternalContainer.m10059a() : context; } /* renamed from: d */ private static String m11883d() { StringBuilder sb = new StringBuilder(); sb.append(TTPathConst.f9099b); String str = "/"; sb.append(str); sb.append("t_sp"); sb.append(str); return sb.toString(); } /* renamed from: b */ private static String m11879b(String str) { if (TextUtils.isEmpty(str)) { return ""; } StringBuilder sb = new StringBuilder(); sb.append("?sp_file_name="); sb.append(str); return sb.toString(); } /* renamed from: a */ public static synchronized void m11870a(String str, String str2, Boolean bool) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.BOOLEAN_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, bool); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11874a(String str, String str2, String str3) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.STRING_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, str3); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11872a(String str, String str2, Integer num) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("int"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, num); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11873a(String str, String str2, Long l) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, l); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11871a(String str, String str2, Float f) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.FLOAT_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); contentValues.put(ArgKey.KEY_VALUE, f); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: a */ public static synchronized void m11875a(String str, String str2, Set<String> set) { synchronized (SPMultiHelper.class) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("string_set"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); Uri parse = Uri.parse(sb.toString()); ContentValues contentValues = new ContentValues(); HashSet hashSet = new HashSet(); for (String replace : set) { hashSet.add(replace.replace(StorageInterface.KEY_SPLITER, "__COMMA__")); } contentValues.put(ArgKey.KEY_VALUE, hashSet.toString()); b.update(parse, contentValues, null, null); } } catch (Throwable unused) { } } } } /* renamed from: b */ public static String m11880b(String str, String str2, String str3) { if (!m11876a()) { return str3; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.STRING_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); return (type == null || type.equals("null")) ? str3 : type; } } catch (Throwable unused) { } } /* renamed from: a */ public static int m11865a(String str, String str2, int i) { if (!m11876a()) { return i; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("int"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Integer.parseInt(type); } } } } catch (Throwable unused) { } return i; } /* renamed from: a */ public static float m11864a(String str, String str2, float f) { if (!m11876a()) { return f; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.FLOAT_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Float.parseFloat(type); } } } } catch (Throwable unused) { } return f; } /* renamed from: a */ public static boolean m11877a(String str, String str2, boolean z) { if (!m11876a()) { return z; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.BOOLEAN_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Boolean.parseBoolean(type); } } } } catch (Throwable unused) { } return z; } /* renamed from: a */ public static long m11866a(String str, String str2, long j) { if (!m11876a()) { return j; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { return Long.parseLong(type); } } } } catch (Throwable unused) { } return j; } /* renamed from: b */ public static Set<String> m11881b(String str, String str2, Set<String> set) { String str3 = ", "; if (!m11876a()) { return set; } try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("string_set"); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); String type = b.getType(Uri.parse(sb.toString())); if (type != null) { if (!type.equals("null")) { if (!type.matches("\\[.*\\]")) { return set; } String[] split = type.substring(1, type.length() - 1).split(str3); HashSet hashSet = new HashSet(); for (String replace : split) { hashSet.add(replace.replace("__COMMA__", str3)); } return hashSet; } } } } catch (Throwable unused) { } return set; } /* renamed from: a */ public static void m11869a(String str, String str2) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append(SettingsContentProvider.LONG_TYPE); sb.append("/"); sb.append(str2); sb.append(m11879b(str)); b.delete(Uri.parse(sb.toString()), null, null); } } catch (Throwable unused) { } } } /* renamed from: a */ public static void m11868a(String str) { if (m11876a()) { try { ContentResolver b = m11878b(); if (b != null) { StringBuilder sb = new StringBuilder(); sb.append(m11883d()); sb.append("clean"); sb.append(m11879b(str)); b.delete(Uri.parse(sb.toString()), null, null); } } catch (Throwable unused) { } } } }
14,898
0.451269
0.41905
418
34.641148
21.722816
100
false
false
0
0
0
0
0
0
0.590909
false
false
4
2b282be757d8a75970ac0659a34ceec621645974
36,790,689,896,320
687bb23798c5ced1d42d7f5cd06685e4c6c716ee
/vitals/BMSTester.java
961bfdbf1ee835295f9af288f1b7292136ff0460
[ "MIT" ]
permissive
clean-code-craft-tcq-1/functional-java-PronabM
https://github.com/clean-code-craft-tcq-1/functional-java-PronabM
2977b052b97f21ced2147cfd6956d1ac09401490
d4fd365f1e0615b23bf88a844ef6285fb8104bac
refs/heads/master
2023-03-08T21:59:27.450000
2021-03-02T16:43:21
2021-03-02T16:43:21
343,180,684
0
0
MIT
false
2021-02-28T18:23:33
2021-02-28T18:23:29
2021-02-28T18:23:32
2021-02-28T18:23:32
0
0
0
1
Java
false
false
package vitals; import java.util.Random; public class BMSTester { private BMS bms; private float maxTemp; private float minTemp; private float maxSoc; private float minSoc; private float maxCR; private Random random = new Random(); public BMSTester(BMS bms) { this.bms = bms; this.maxTemp = bms.getTempUpperLimit(); this.minTemp = bms.getTempLowerLimit(); this.maxSoc = bms.getSocUpperLimit(); this.minSoc = bms.getSocLowerLimit(); this.maxCR = bms.getChargeRateUpperLimit(); } public void tempAboveLimit_Failure() { assert(bms.checkBattery(maxTemp + 1, maxSoc, maxCR)==false); } public void tempBelowLimit_Failure() { assert(bms.checkBattery(minTemp - 1, maxSoc, maxCR)==false); } public void tempWithinLimit_Success() { float randomTempWithinRange = minTemp + random.nextFloat() * (maxTemp - minTemp); assert(bms.checkBattery(randomTempWithinRange, maxSoc, maxCR)==true); } public void socAboveLimit_Failure() { assert(bms.checkBattery(maxTemp, maxSoc + 1, maxCR)==false); } public void socBelowLimit_Failure() { assert(bms.checkBattery(maxTemp, minSoc - 1, maxCR)==false); } public void socWithinLimit_Success() { float randomSocWithinRange = minSoc + random.nextFloat() * (maxSoc - minSoc); assert(bms.checkBattery(maxTemp, randomSocWithinRange, maxCR)==true); } public void crAboveLimit_Failure() { assert(bms.checkBattery(maxTemp, maxSoc, maxCR + 1)==false); } public void crWithinLimit_Success() { float randomCRWithinRange = random.nextFloat() * (maxCR); assert(bms.checkBattery(maxTemp, maxSoc, randomCRWithinRange)==true); } public void allParamOutsideLimit_Failure() { assert(bms.checkBattery(maxTemp + 1, minSoc - 1, maxCR + 1)==false); } }
UTF-8
Java
1,742
java
BMSTester.java
Java
[]
null
[]
package vitals; import java.util.Random; public class BMSTester { private BMS bms; private float maxTemp; private float minTemp; private float maxSoc; private float minSoc; private float maxCR; private Random random = new Random(); public BMSTester(BMS bms) { this.bms = bms; this.maxTemp = bms.getTempUpperLimit(); this.minTemp = bms.getTempLowerLimit(); this.maxSoc = bms.getSocUpperLimit(); this.minSoc = bms.getSocLowerLimit(); this.maxCR = bms.getChargeRateUpperLimit(); } public void tempAboveLimit_Failure() { assert(bms.checkBattery(maxTemp + 1, maxSoc, maxCR)==false); } public void tempBelowLimit_Failure() { assert(bms.checkBattery(minTemp - 1, maxSoc, maxCR)==false); } public void tempWithinLimit_Success() { float randomTempWithinRange = minTemp + random.nextFloat() * (maxTemp - minTemp); assert(bms.checkBattery(randomTempWithinRange, maxSoc, maxCR)==true); } public void socAboveLimit_Failure() { assert(bms.checkBattery(maxTemp, maxSoc + 1, maxCR)==false); } public void socBelowLimit_Failure() { assert(bms.checkBattery(maxTemp, minSoc - 1, maxCR)==false); } public void socWithinLimit_Success() { float randomSocWithinRange = minSoc + random.nextFloat() * (maxSoc - minSoc); assert(bms.checkBattery(maxTemp, randomSocWithinRange, maxCR)==true); } public void crAboveLimit_Failure() { assert(bms.checkBattery(maxTemp, maxSoc, maxCR + 1)==false); } public void crWithinLimit_Success() { float randomCRWithinRange = random.nextFloat() * (maxCR); assert(bms.checkBattery(maxTemp, maxSoc, randomCRWithinRange)==true); } public void allParamOutsideLimit_Failure() { assert(bms.checkBattery(maxTemp + 1, minSoc - 1, maxCR + 1)==false); } }
1,742
0.722732
0.71814
62
27.112904
25.284897
83
false
false
0
0
0
0
0
0
1.903226
false
false
4
29c4182af27c294b3d998207ec52308e1627e4f8
35,476,429,914,213
67bd7481b6712b33902448929d1956e6ee5c2116
/TheSecondOne.java
2b1220e0859968f1683b6232ae1efec7bcb8c377
[]
no_license
FrostyBaggins/LearningJava
https://github.com/FrostyBaggins/LearningJava
46e46b8a3cc4444f78f9de95d31ae3e2674f9933
d4f962ab8729fd717a3e8e6ce391112ac4367dde
refs/heads/master
2021-01-12T00:17:23.719000
2020-04-09T07:11:20
2020-04-09T07:11:20
78,701,841
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class TheSecondOne { }
UTF-8
Java
32
java
TheSecondOne.java
Java
[]
null
[]
public class TheSecondOne { }
32
0.71875
0.71875
3
9.333333
12.498889
27
false
false
0
0
0
0
0
0
0
false
false
4
a7d66ae3a6433fc29f0418deb1582a94c88e2bbb
35,442,070,178,641
595c46a749db2e336e184699cfa0259c05546e71
/chapter_102/src/main/java/ru/job4j/jobparser/exception/ParserException.java
b25bbef911cfb4edc9d6e625b21d8144ba8d8f8f
[]
no_license
vavilovns/nvavilov
https://github.com/vavilovns/nvavilov
23f716b79b942e0ed6ad1b63a419ab373e14419e
16c6b009d8d3ebf08594faf05c7ca4bb093f32ac
refs/heads/master
2018-12-27T14:14:59.847000
2018-12-25T14:31:58
2018-12-25T14:31:58
116,848,003
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.jobparser.exception; /** * Parser execution exception. * * @author Nikita Vavilov (vavilovns@gmail.com) * @version 1 * @since 02.10.2018 */ public class ParserException extends Exception { public ParserException() { } public ParserException(String message) { super(message); } public ParserException(String message, Throwable cause) { super(message, cause); } }
UTF-8
Java
434
java
ParserException.java
Java
[ { "context": "\n\n/**\n * Parser execution exception.\n *\n * @author Nikita Vavilov (vavilovns@gmail.com)\n * @version 1\n * @since 02.", "end": 102, "score": 0.9998831748962402, "start": 88, "tag": "NAME", "value": "Nikita Vavilov" }, { "context": "xecution exception.\n *\n * @author Nikita Vavilov (vavilovns@gmail.com)\n * @version 1\n * @since 02.10.2018\n */\npublic cl", "end": 123, "score": 0.9999358057975769, "start": 104, "tag": "EMAIL", "value": "vavilovns@gmail.com" } ]
null
[]
package ru.job4j.jobparser.exception; /** * Parser execution exception. * * @author <NAME> (<EMAIL>) * @version 1 * @since 02.10.2018 */ public class ParserException extends Exception { public ParserException() { } public ParserException(String message) { super(message); } public ParserException(String message, Throwable cause) { super(message, cause); } }
414
0.66129
0.638249
22
18.5
18.956289
61
false
false
0
0
0
0
0
0
0.227273
false
false
4
dfce711661349002ceb3ddb8ece91284a9f4a898
36,258,113,960,596
044a50593fa8b3094e704ac48b44850848b720c4
/soeasy-flink-table/src/main/java/com/mingzhang/table/source/file/OrcConnectDemo.java
94e0ad0a147ab208a7d33cc1478bd42b75f1a029
[]
no_license
bellmit/repo-soeasy
https://github.com/bellmit/repo-soeasy
956fb9a1b45268605a356e6441a3aa5f65438577
bc137c362703b3e198b9ad3ce6a0a6fe66f3a94e
refs/heads/master
2023-05-04T01:21:07.794000
2020-08-15T07:53:01
2020-08-15T07:53:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mingzhang.table.source.file; import org.apache.flink.configuration.Configuration; public class OrcConnectDemo { public static void main(String[] args) { // // create Hadoop Configuration // Configuration config = new Configuration(); // // OrcTableSource orcTableSource = OrcTableSource.builder() // // path to ORC file(s). NOTE: By default, directories are recursively scanned. // .path("file:///path/to/data") // // schema of ORC files // .forOrcSchema("struct<name:string,addresses:array<struct<street:string,zip:smallint>>>") // // Hadoop configuration // .withConfiguration(config) // // build OrcTableSource // .build(); } }
UTF-8
Java
795
java
OrcConnectDemo.java
Java
[]
null
[]
package com.mingzhang.table.source.file; import org.apache.flink.configuration.Configuration; public class OrcConnectDemo { public static void main(String[] args) { // // create Hadoop Configuration // Configuration config = new Configuration(); // // OrcTableSource orcTableSource = OrcTableSource.builder() // // path to ORC file(s). NOTE: By default, directories are recursively scanned. // .path("file:///path/to/data") // // schema of ORC files // .forOrcSchema("struct<name:string,addresses:array<struct<street:string,zip:smallint>>>") // // Hadoop configuration // .withConfiguration(config) // // build OrcTableSource // .build(); } }
795
0.596226
0.596226
21
36.857143
28.979937
106
false
false
0
0
0
0
0
0
0.333333
false
false
4
b7ae8978062d551d9c797f01def2a548e485d530
3,143,916,115,792
ef877695d2d4705702323326657726a277cf04cf
/chapter_302/carsale/src/main/java/ru/job4j/services/UserService.java
13b63e47ddde680cd87772c8f41faaf92859dd6c
[ "Apache-2.0" ]
permissive
mifodiy4j/smikhailov
https://github.com/mifodiy4j/smikhailov
449a57725e3a281e27b3d5947b8440e8ac97976d
09eb5317300acff501fa0932d75d6e5f5fc4048e
refs/heads/master
2021-01-01T06:31:52.343000
2018-08-05T11:37:00
2018-08-05T11:37:00
97,450,623
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.job4j.models.User; import ru.job4j.storage.UserDAO; import java.util.List; @Service public class UserService { @Autowired private UserDAO userDAO = UserDAO.getInstance(); public void add(User user) { userDAO.save(user); } public List<User> getAll() { return (List<User>) userDAO.getAll(); } }
UTF-8
Java
486
java
UserService.java
Java
[]
null
[]
package ru.job4j.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.job4j.models.User; import ru.job4j.storage.UserDAO; import java.util.List; @Service public class UserService { @Autowired private UserDAO userDAO = UserDAO.getInstance(); public void add(User user) { userDAO.save(user); } public List<User> getAll() { return (List<User>) userDAO.getAll(); } }
486
0.711934
0.705761
23
20.130434
18.767002
62
false
false
0
0
0
0
0
0
0.391304
false
false
4
3ebf542d8dcb2cdc4a4ffa28ae4368f79737e0e4
10,651,518,923,037
d4de626afcb46687861c0f92f61012b9795173df
/app/src/main/java/com/northmeter/sharedhotwatermeter/northmeter/activity/LoginActivity.java
8ccd294afd7e6d4f6aebbc3f9a000117887b07b7
[]
no_license
newYearsDeng/SharedHotWaterMeter
https://github.com/newYearsDeng/SharedHotWaterMeter
0f2812867d7fed91265c0c5b130bb4a114d276bb
73492b7afb09d4425c5bb3fc990e54ca4a4ce571
refs/heads/master
2020-07-10T21:10:11.395000
2017-12-13T10:04:07
2017-12-13T10:04:07
114,093,324
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.northmeter.sharedhotwatermeter.northmeter.activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.alibaba.fastjson.JSONObject; import com.mob.MobSDK; import com.northmeter.sharedhotwatermeter.R; import com.northmeter.sharedhotwatermeter.bt_bluetooth.BTMainActivity; import com.northmeter.sharedhotwatermeter.northmeter.BaseActivity.BaseActivity; import com.northmeter.sharedhotwatermeter.northmeter.helper.Constants; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import cn.smssdk.EventHandler; import cn.smssdk.SMSSDK; /** * Created by dyd on 2017/8/18. */ public class LoginActivity extends BaseActivity { private String TGA = "northmeter.activity.LoginActivity"; @BindView(R.id.et_telnumber) EditText etTelnumber; @BindView(R.id.et_login_code) EditText etLoginCode; @BindView(R.id.to_get_code) Button toGetCode; @BindView(R.id.btn_login) Button btnLogin; @BindView(R.id.iv_delete) ImageView ivDelete; private int i = 60; private SharedPreferences sp; @Override protected int getLayoutId() { return R.layout.activity_login; } @Override protected void inteView(Bundle savedInstanceState) { reg_smssdk(); sp = getSharedPreferences("UserInfo", MODE_PRIVATE); boolean login_flag = sp.getBoolean("LoginFlag", false);//判断是否登录 if (login_flag) { startActivity(new Intent(this, MainActivity.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_right); LoginActivity.this.finish(); } else { String telNum = sp.getString("TEL", null); if (telNum != null) { etTelnumber.setText(telNum); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } /** * 短信验证注册 */ private void reg_smssdk() { // 如果希望在读取通信录的时候提示用户,可以添加下面的代码,并且必须在其他代码调用之前,否则不起作用;如果没这个需求,可以不加这行代码 // SMSSDK.setAskPermisionOnReadContact(boolShowInDialog) MobSDK.init(this, Constants.MOB_APP_KEY, Constants.MOB_secret); // 创建EventHandler对象 EventHandler eventHandler = new EventHandler() { @Override public void afterEvent(int event, int result, Object data) { Message msg = new Message(); msg.arg1 = event; msg.arg2 = result; msg.obj = data; handler.sendMessage(msg); } }; // 注册监听器 SMSSDK.registerEventHandler(eventHandler); } @Override protected void onDestroy() { super.onDestroy(); SMSSDK.unregisterAllEventHandler(); } @OnClick({R.id.to_get_code, R.id.btn_login,R.id.iv_delete}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_delete: etTelnumber.setText(""); break; case R.id.to_get_code: // 1. 通过规则判断手机号 if (!judgePhoneNums(etTelnumber.getText().toString())) { return; } // 2. 通过sdk发送短信验证 SMSSDK.getVerificationCode("86", etTelnumber.getText().toString()); // 3. 把按钮变成不可点击,并且显示倒计时(正在获取) toGetCode.setClickable(false); toGetCode.setText("重新发送(" + i + ")"); new Thread(new Runnable() { @Override public void run() { for (; i > 0; i--) { handler.sendEmptyMessage(-9); if (i <= 0) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } handler.sendEmptyMessage(-8); } }).start(); break; case R.id.btn_login: showDialog(""); SMSSDK.submitVerificationCode("86", etTelnumber.getText().toString(), etLoginCode .getText().toString()); break; } } Handler handler = new Handler() { public void handleMessage(Message msg) { try { if (msg.what == -9) { toGetCode.setText("重新发送(" + i + ")"); } else if (msg.what == -8) { toGetCode.setText("获取验证码"); toGetCode.setClickable(true); i = 60; } else { int event = msg.arg1; int result = msg.arg2; Object data = msg.obj; Log.e(TGA, "event==== " + event); Log.e(TGA, "result==== " + result); Log.e(TGA, "data==== " + data.toString()); if (result == SMSSDK.RESULT_COMPLETE) { // 短信注册成功后,返回MainActivity if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功 stopDialog(); SharedPreferences.Editor editor = sp.edit(); editor.putString("TEL", etTelnumber.getText().toString()); editor.putBoolean("LoginFlag", true); editor.commit(); i = 0; startActivity(new Intent(LoginActivity.this, MainActivity.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_right); LoginActivity.this.finish(); } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { Toast.makeText(LoginActivity.this, "验证码已发出", Toast.LENGTH_SHORT).show(); } else { ((Throwable) data).printStackTrace(); Toast.makeText(LoginActivity.this, data.toString(), Toast.LENGTH_SHORT).show(); stopDialog(); } } else { int state = data.toString().indexOf("{"); String json = data.toString().substring(state, data.toString().length()); JSONObject jsonobject = JSONObject.parseObject(json); Object detail = jsonobject.get("detail"); Toast.makeText(LoginActivity.this, detail.toString(), Toast.LENGTH_SHORT).show(); stopDialog(); } } } catch (Exception e) { e.printStackTrace(); } } }; /** * 判断手机号码是否合理 * * @param phoneNums */ private boolean judgePhoneNums(String phoneNums) { if (isMatchLength(phoneNums, 11) && isMobileNO(phoneNums)) { return true; } Toast.makeText(this, "手机号码输入有误!", Toast.LENGTH_SHORT).show(); return false; } /** * 判断一个字符串的位数 * * @param str * @param length * @return */ public static boolean isMatchLength(String str, int length) { if (str.isEmpty()) { return false; } else { return str.length() == length ? true : false; } } /** * 验证手机格式 */ public static boolean isMobileNO(String mobileNums) { /* * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 */ String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 if (TextUtils.isEmpty(mobileNums)) return false; else return mobileNums.matches(telRegex); } /** * progressbar */ private void createProgressBar() { FrameLayout layout = (FrameLayout) findViewById(android.R.id.content); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; ProgressBar mProBar = new ProgressBar(this); mProBar.setLayoutParams(layoutParams); mProBar.setVisibility(View.VISIBLE); layout.addView(mProBar); } }
UTF-8
Java
10,000
java
LoginActivity.java
Java
[ { "context": "ndler;\nimport cn.smssdk.SMSSDK;\n\n/**\n * Created by dyd on 2017/8/18.\n */\npublic class LoginActivity exte", "end": 1078, "score": 0.9996160268783569, "start": 1075, "tag": "USERNAME", "value": "dyd" } ]
null
[]
package com.northmeter.sharedhotwatermeter.northmeter.activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.alibaba.fastjson.JSONObject; import com.mob.MobSDK; import com.northmeter.sharedhotwatermeter.R; import com.northmeter.sharedhotwatermeter.bt_bluetooth.BTMainActivity; import com.northmeter.sharedhotwatermeter.northmeter.BaseActivity.BaseActivity; import com.northmeter.sharedhotwatermeter.northmeter.helper.Constants; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import cn.smssdk.EventHandler; import cn.smssdk.SMSSDK; /** * Created by dyd on 2017/8/18. */ public class LoginActivity extends BaseActivity { private String TGA = "northmeter.activity.LoginActivity"; @BindView(R.id.et_telnumber) EditText etTelnumber; @BindView(R.id.et_login_code) EditText etLoginCode; @BindView(R.id.to_get_code) Button toGetCode; @BindView(R.id.btn_login) Button btnLogin; @BindView(R.id.iv_delete) ImageView ivDelete; private int i = 60; private SharedPreferences sp; @Override protected int getLayoutId() { return R.layout.activity_login; } @Override protected void inteView(Bundle savedInstanceState) { reg_smssdk(); sp = getSharedPreferences("UserInfo", MODE_PRIVATE); boolean login_flag = sp.getBoolean("LoginFlag", false);//判断是否登录 if (login_flag) { startActivity(new Intent(this, MainActivity.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_right); LoginActivity.this.finish(); } else { String telNum = sp.getString("TEL", null); if (telNum != null) { etTelnumber.setText(telNum); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } /** * 短信验证注册 */ private void reg_smssdk() { // 如果希望在读取通信录的时候提示用户,可以添加下面的代码,并且必须在其他代码调用之前,否则不起作用;如果没这个需求,可以不加这行代码 // SMSSDK.setAskPermisionOnReadContact(boolShowInDialog) MobSDK.init(this, Constants.MOB_APP_KEY, Constants.MOB_secret); // 创建EventHandler对象 EventHandler eventHandler = new EventHandler() { @Override public void afterEvent(int event, int result, Object data) { Message msg = new Message(); msg.arg1 = event; msg.arg2 = result; msg.obj = data; handler.sendMessage(msg); } }; // 注册监听器 SMSSDK.registerEventHandler(eventHandler); } @Override protected void onDestroy() { super.onDestroy(); SMSSDK.unregisterAllEventHandler(); } @OnClick({R.id.to_get_code, R.id.btn_login,R.id.iv_delete}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_delete: etTelnumber.setText(""); break; case R.id.to_get_code: // 1. 通过规则判断手机号 if (!judgePhoneNums(etTelnumber.getText().toString())) { return; } // 2. 通过sdk发送短信验证 SMSSDK.getVerificationCode("86", etTelnumber.getText().toString()); // 3. 把按钮变成不可点击,并且显示倒计时(正在获取) toGetCode.setClickable(false); toGetCode.setText("重新发送(" + i + ")"); new Thread(new Runnable() { @Override public void run() { for (; i > 0; i--) { handler.sendEmptyMessage(-9); if (i <= 0) { break; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } handler.sendEmptyMessage(-8); } }).start(); break; case R.id.btn_login: showDialog(""); SMSSDK.submitVerificationCode("86", etTelnumber.getText().toString(), etLoginCode .getText().toString()); break; } } Handler handler = new Handler() { public void handleMessage(Message msg) { try { if (msg.what == -9) { toGetCode.setText("重新发送(" + i + ")"); } else if (msg.what == -8) { toGetCode.setText("获取验证码"); toGetCode.setClickable(true); i = 60; } else { int event = msg.arg1; int result = msg.arg2; Object data = msg.obj; Log.e(TGA, "event==== " + event); Log.e(TGA, "result==== " + result); Log.e(TGA, "data==== " + data.toString()); if (result == SMSSDK.RESULT_COMPLETE) { // 短信注册成功后,返回MainActivity if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功 stopDialog(); SharedPreferences.Editor editor = sp.edit(); editor.putString("TEL", etTelnumber.getText().toString()); editor.putBoolean("LoginFlag", true); editor.commit(); i = 0; startActivity(new Intent(LoginActivity.this, MainActivity.class)); overridePendingTransition(R.anim.slide_left, R.anim.slide_right); LoginActivity.this.finish(); } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { Toast.makeText(LoginActivity.this, "验证码已发出", Toast.LENGTH_SHORT).show(); } else { ((Throwable) data).printStackTrace(); Toast.makeText(LoginActivity.this, data.toString(), Toast.LENGTH_SHORT).show(); stopDialog(); } } else { int state = data.toString().indexOf("{"); String json = data.toString().substring(state, data.toString().length()); JSONObject jsonobject = JSONObject.parseObject(json); Object detail = jsonobject.get("detail"); Toast.makeText(LoginActivity.this, detail.toString(), Toast.LENGTH_SHORT).show(); stopDialog(); } } } catch (Exception e) { e.printStackTrace(); } } }; /** * 判断手机号码是否合理 * * @param phoneNums */ private boolean judgePhoneNums(String phoneNums) { if (isMatchLength(phoneNums, 11) && isMobileNO(phoneNums)) { return true; } Toast.makeText(this, "手机号码输入有误!", Toast.LENGTH_SHORT).show(); return false; } /** * 判断一个字符串的位数 * * @param str * @param length * @return */ public static boolean isMatchLength(String str, int length) { if (str.isEmpty()) { return false; } else { return str.length() == length ? true : false; } } /** * 验证手机格式 */ public static boolean isMobileNO(String mobileNums) { /* * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188 * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通) * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9 */ String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。 if (TextUtils.isEmpty(mobileNums)) return false; else return mobileNums.matches(telRegex); } /** * progressbar */ private void createProgressBar() { FrameLayout layout = (FrameLayout) findViewById(android.R.id.content); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; ProgressBar mProBar = new ProgressBar(this); mProBar.setLayoutParams(layoutParams); mProBar.setVisibility(View.VISIBLE); layout.addView(mProBar); } }
10,000
0.531077
0.516284
271
33.671585
24.111502
114
false
false
0
0
0
0
0
0
0.601476
false
false
4
3267798a57b966f2b20f73141b8de6576cf392be
5,514,738,059,824
165bc2207bf678357de031877ac2f35321d29256
/src/multiThread_Lab/synchronize/MainThreadExample.java
0e1c493fc898d916a0601d22544e2a0b2a6d2045
[]
no_license
smathj/myJava
https://github.com/smathj/myJava
a5763977f05ff23ca81324e1ac0b5a75296de14e
31ca81a952926d535f451e4ef31ea132c9af737c
refs/heads/main
2023-07-18T01:05:48.856000
2021-09-05T13:47:25
2021-09-05T13:47:25
401,741,138
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package multiThread_Lab.synchronize; public class MainThreadExample { public static void main(String[] args) { Calculator calculator = new Calculator(); // calculator 객체 생성 User1 user1 = new User1(); // user1 객체 생성(스레드 상속) user1.setCalculator(calculator); // calculator, Thread-Name 초기화 user1.start(); // 작업 스레드 실행 memory 필드 100 으로 초기화 User2 user2 = new User2(); // user2 객체 생성(스레드 상속) user2.setCalculator(calculator); // calculator, Thread-Name 초기화 user2.start(); // 작업 스레드 실행 memory 필드 50 으로 초기화 } }
UHC
Java
676
java
MainThreadExample.java
Java
[]
null
[]
package multiThread_Lab.synchronize; public class MainThreadExample { public static void main(String[] args) { Calculator calculator = new Calculator(); // calculator 객체 생성 User1 user1 = new User1(); // user1 객체 생성(스레드 상속) user1.setCalculator(calculator); // calculator, Thread-Name 초기화 user1.start(); // 작업 스레드 실행 memory 필드 100 으로 초기화 User2 user2 = new User2(); // user2 객체 생성(스레드 상속) user2.setCalculator(calculator); // calculator, Thread-Name 초기화 user2.start(); // 작업 스레드 실행 memory 필드 50 으로 초기화 } }
676
0.652482
0.62234
21
25.857143
27.170162
68
false
false
0
0
0
0
0
0
3.285714
false
false
4
08e5527f9e30827b6b2b0b1e03a046617782ebc1
35,003,983,469,645
d4d9bf24bae98fe10718a52603d6f3df2b181bbf
/kafka-graphs-rest-app/src/main/java/io/kgraph/rest/server/actuator/KafkaHealthIndicator.java
57914c265be9c3432b0e149d195aa0afcb8b084a
[ "Apache-2.0" ]
permissive
rayokota/kafka-graphs
https://github.com/rayokota/kafka-graphs
3b3376f097af08cf4e1b000a78218615cd681bfc
0fa3122c61a2c1089ed47a781221aa534e9d9ed6
refs/heads/master
2023-08-07T15:22:38.806000
2023-08-06T07:32:40
2023-08-06T07:32:40
131,537,435
98
18
Apache-2.0
false
2023-09-13T05:32:10
2018-04-29T23:13:20
2023-07-06T19:25:02
2023-09-13T05:32:10
1,021
96
19
10
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 io.kgraph.rest.server.actuator; import java.util.Properties; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.DescribeClusterOptions; import org.apache.kafka.clients.admin.DescribeClusterResult; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import io.kgraph.rest.server.KafkaGraphsProperties; import reactor.core.publisher.Mono; @Component @EnableConfigurationProperties(KafkaGraphsProperties.class) public class KafkaHealthIndicator implements ReactiveHealthIndicator { private final KafkaGraphsProperties props; public KafkaHealthIndicator(KafkaGraphsProperties props) { this.props = props; } @Override public Mono<Health> health() { Health.Builder builder = new Health.Builder(); Properties properties = new Properties(); properties.put("bootstrap.servers", props.getBootstrapServers()); try (AdminClient adminClient = AdminClient.create(properties)) { DescribeClusterResult result = adminClient.describeCluster(new DescribeClusterOptions().timeoutMs(3000)); builder.withDetail("clusterId", result.clusterId().get()); builder.up(); } catch (Exception e) { builder.down(); } return Mono.just(builder.build()); } }
UTF-8
Java
2,325
java
KafkaHealthIndicator.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 io.kgraph.rest.server.actuator; import java.util.Properties; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.DescribeClusterOptions; import org.apache.kafka.clients.admin.DescribeClusterResult; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import io.kgraph.rest.server.KafkaGraphsProperties; import reactor.core.publisher.Mono; @Component @EnableConfigurationProperties(KafkaGraphsProperties.class) public class KafkaHealthIndicator implements ReactiveHealthIndicator { private final KafkaGraphsProperties props; public KafkaHealthIndicator(KafkaGraphsProperties props) { this.props = props; } @Override public Mono<Health> health() { Health.Builder builder = new Health.Builder(); Properties properties = new Properties(); properties.put("bootstrap.servers", props.getBootstrapServers()); try (AdminClient adminClient = AdminClient.create(properties)) { DescribeClusterResult result = adminClient.describeCluster(new DescribeClusterOptions().timeoutMs(3000)); builder.withDetail("clusterId", result.clusterId().get()); builder.up(); } catch (Exception e) { builder.down(); } return Mono.just(builder.build()); } }
2,325
0.752258
0.748817
58
39.103447
28.607143
117
false
false
0
0
0
0
0
0
0.482759
false
false
4
e1a028e6ab1380faa1a971f5036604f4a3a4aadd
30,623,116,870,488
fb391cc0594341683df8350d3a730ee0fc438d9c
/src/main/java/com/china/cn/design_patterns/builder_design_pattern/builder/Builder.java
5ca8711bc8d7ef1ab7068fcad4e12fb55de0215d
[]
no_license
jim0310/design-patterns
https://github.com/jim0310/design-patterns
c47b627840f1b373e188d34cc6f09e1a68716368
adf4c125bdc72566adac9bc1d2f92a87e1f6bda5
refs/heads/master
2021-09-24T09:13:54.899000
2018-10-06T10:54:53
2018-10-06T10:54:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.china.cn.design_patterns.builder_design_pattern.builder; import com.china.cn.design_patterns.builder_design_pattern.part.Part; /** * @Description: builder模式 * @ClassName: Builder * @Author: bin.ji * @Date: 2018-10-05 15:26 * @Version: 1.0.0.0 */ public interface Builder { /** * 创建部件A * @return */ Part builderPartA(); /** * 创建部件B * @return */ Part builderPartB(); /** * 创建部件C * @return */ Part builderPartC(); }
UTF-8
Java
546
java
Builder.java
Java
[ { "context": "tion: builder模式\n * @ClassName: Builder\n * @Author: bin.ji\n * @Date: 2018-10-05 15:26\n * @Version: 1.0.0.0\n ", "end": 213, "score": 0.9161955714225769, "start": 207, "tag": "NAME", "value": "bin.ji" } ]
null
[]
package com.china.cn.design_patterns.builder_design_pattern.builder; import com.china.cn.design_patterns.builder_design_pattern.part.Part; /** * @Description: builder模式 * @ClassName: Builder * @Author: bin.ji * @Date: 2018-10-05 15:26 * @Version: 1.0.0.0 */ public interface Builder { /** * 创建部件A * @return */ Part builderPartA(); /** * 创建部件B * @return */ Part builderPartB(); /** * 创建部件C * @return */ Part builderPartC(); }
546
0.565637
0.534749
32
15.1875
16.152472
69
false
false
0
0
0
0
0
0
0.15625
false
false
4
31b3ae6adb38a6f5cb88d1ec06da83488869b4b0
31,301,721,678,074
8f2c8c35c8cdc0653e917643d344501a038410e7
/src/test/java/com/papertrail/profiler/CpuProfileTest.java
9f60328729325a06b1b22c0a32c8c18571840a0e
[ "Apache-2.0" ]
permissive
rhowe/profiler
https://github.com/rhowe/profiler
efe532483b26b284de97224fd9af226a54fe30a3
8acd4deda1028f8806ea2dc84fad5374a881223f
refs/heads/master
2020-05-05T02:16:46.984000
2015-11-23T17:06:55
2015-11-23T17:06:55
179,632,110
0
0
null
true
2019-04-05T06:47:08
2019-04-05T06:47:08
2018-04-20T04:49:08
2018-02-22T20:55:01
19
0
0
0
null
false
false
package com.papertrail.profiler; import org.joda.time.Duration; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import static org.junit.Assert.*; /** * Ported from scala */ public class CpuProfileTest { @Test public void testRecord() throws Exception { Thread t = new Thread("CpuProfileTest") { @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException ignored) { } } }; t.setDaemon(true); t.start(); // Profile for 1000ms at 10 Hz => 100ms period; produces 10 samples. CpuProfile profile = CpuProfile.record(Duration.standardSeconds(1), 10, Thread.State.TIMED_WAITING); assertNotNull(profile); assertEquals(10, profile.count); assertEquals(0, profile.missed); OutputStream baos = new ByteArrayOutputStream(); profile.writeGoogleProfile(baos); assertTrue(baos.toString().contains("CpuProfileTest")); assertTrue(baos.toString().contains("Thread.sleep")); } @Test public void testisRunnable() { assertTrue(CpuProfile.isRunnable(newElem("foo", "bar"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.EPollArrayWrapper", "epollWait"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.KQueueArrayWrapper", "kevent0"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.ServerSocketChannelImpl", "accept0"))); } public static StackTraceElement newElem(String className, String methodName) { return new StackTraceElement(className, methodName, "SomeFile.java", 1); } }
UTF-8
Java
1,741
java
CpuProfileTest.java
Java
[]
null
[]
package com.papertrail.profiler; import org.joda.time.Duration; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import static org.junit.Assert.*; /** * Ported from scala */ public class CpuProfileTest { @Test public void testRecord() throws Exception { Thread t = new Thread("CpuProfileTest") { @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException ignored) { } } }; t.setDaemon(true); t.start(); // Profile for 1000ms at 10 Hz => 100ms period; produces 10 samples. CpuProfile profile = CpuProfile.record(Duration.standardSeconds(1), 10, Thread.State.TIMED_WAITING); assertNotNull(profile); assertEquals(10, profile.count); assertEquals(0, profile.missed); OutputStream baos = new ByteArrayOutputStream(); profile.writeGoogleProfile(baos); assertTrue(baos.toString().contains("CpuProfileTest")); assertTrue(baos.toString().contains("Thread.sleep")); } @Test public void testisRunnable() { assertTrue(CpuProfile.isRunnable(newElem("foo", "bar"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.EPollArrayWrapper", "epollWait"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.KQueueArrayWrapper", "kevent0"))); assertFalse(CpuProfile.isRunnable(newElem("sun.nio.ch.ServerSocketChannelImpl", "accept0"))); } public static StackTraceElement newElem(String className, String methodName) { return new StackTraceElement(className, methodName, "SomeFile.java", 1); } }
1,741
0.647904
0.633544
51
33.156864
29.791677
108
false
false
0
0
0
0
0
0
0.705882
false
false
4
15759e31017a0fad42c06b5575a62e3e4f36643d
19,344,532,749,287
d25f8b85b0ce28acc6d44721b910b38eaeaa9c0c
/src/one/nio/http/Request.java
5120095707c678f2785e5e89e51f84e37e762c23
[ "Apache-2.0" ]
permissive
odnoklassniki/one-nio
https://github.com/odnoklassniki/one-nio
f3dde5adad86acf30bb48c91ad7dd378a7b52393
f9a931e2df60719c629d59826b245aaa85ddd663
refs/heads/master
2023-09-01T19:08:51.514000
2023-07-27T11:17:28
2023-07-27T11:17:28
6,667,447
608
122
Apache-2.0
false
2023-07-04T13:31:24
2012-11-13T08:15:02
2023-06-06T12:38:50
2023-07-04T13:31:23
1,285
613
93
9
Java
false
false
/* * Copyright 2015 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package one.nio.http; import one.nio.util.ByteArrayBuilder; import one.nio.util.URLEncoder; import one.nio.util.Utf8; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Consumer; public class Request { public static final int METHOD_GET = 1; public static final int METHOD_POST = 2; public static final int METHOD_HEAD = 3; public static final int METHOD_OPTIONS = 4; public static final int METHOD_PUT = 5; public static final int METHOD_DELETE = 6; public static final int METHOD_TRACE = 7; public static final int METHOD_CONNECT = 8; public static final int METHOD_PATCH = 9; public static final int NUMBER_OF_METHODS = 10; static final String[] METHODS = { "", "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH" }; // Methods followed by a single space character static final byte[][] VERBS; static { VERBS = new byte[METHODS.length][]; VERBS[0] = new byte[0]; for (int i = 1; i < VERBS.length; i++) { VERBS[i] = Utf8.toBytes(METHODS[i] + ' '); } } private static final byte[] HTTP10_HEADER = Utf8.toBytes(" HTTP/1.0\r\n"); private static final byte[] HTTP11_HEADER = Utf8.toBytes(" HTTP/1.1\r\n"); private static final int PROTOCOL_HEADER_LENGTH = 13; private int method; private String uri; private boolean http11; private int params; // -1 if no query parameters private int headerCount; private String[] headers; private byte[] body; public Request(int method, String uri, boolean http11) { assert 0 <= method && method < METHODS.length; this.method = method; this.uri = uri; this.http11 = http11; this.params = uri.indexOf('?'); this.headerCount = 0; this.headers = new String[16]; } public Request(Request prototype) { this.method = prototype.method; this.uri = prototype.uri; this.http11 = prototype.http11; this.params = prototype.params; this.headerCount = prototype.headerCount; this.headers = prototype.headers.clone(); this.body = prototype.body; } public int getMethod() { return method; } public String getMethodName() { return METHODS[method]; } public String getURI() { return uri; } public boolean isHttp11() { return http11; } public String getPath() { return params >= 0 ? uri.substring(0, params) : uri; } public String getQueryString() { return params >= 0 ? URLEncoder.decode(uri.substring(params + 1)) : null; } public String getParameter(String key) { int cur = params + 1; while (cur > 0) { int next = uri.indexOf('&', cur); if (uri.startsWith(key, cur)) { cur += key.length(); String rawValue = next > 0 ? uri.substring(cur, next) : uri.substring(cur); return URLEncoder.decode(rawValue); } cur = next + 1; } return null; } public Iterator<String> getParameters(final String key) { return new Iterator<String>() { int cur = findNext(params + 1); @Override public boolean hasNext() { return cur > 0; } @Override public String next() { int next = uri.indexOf('&', cur); cur += key.length(); String rawValue = next > 0 ? uri.substring(cur, next) : uri.substring(cur); cur = findNext(next + 1); return URLEncoder.decode(rawValue); } @Override public void remove() { throw new UnsupportedOperationException(); } private int findNext(int cur) { while (cur > 0 && !uri.startsWith(key, cur)) { cur = uri.indexOf('&', cur) + 1; } return cur; } }; } public String getParameter(String key, String defaultValue) { String value = getParameter(key); return value != null ? value : defaultValue; } public String getRequiredParameter(String key) { String value = getParameter(key); if (value == null) { throw new NoSuchElementException("Missing required parameter: " + key); } return value; } /** * @return {@link Iterable} over {@code String} {@code key[=[value]]} parameters * skipping empty parameters */ public Iterable<Map.Entry<String, String>> getParameters() { if (params < 0) { return Collections.emptyList(); } return new Iterable<Map.Entry<String, String>>() { @Override public Iterator<Map.Entry<String, String>> iterator() { return new QueryParameterIterator(uri.substring(params + 1)); } }; } public Map<String, String> getPostParams() { if (method != METHOD_POST || body == null || body.length == 0) { return Collections.emptyMap(); } String rawParams = new String(body, StandardCharsets.UTF_8); Map<String, String> params = new HashMap<>(); int cur = 0; while (cur >= 0 && cur < rawParams.length()) { int eqIdx = rawParams.indexOf('=', cur); if (eqIdx < 0) return params; int ampIdx = rawParams.indexOf('&', eqIdx); if (eqIdx == cur) { // key=value&= if (eqIdx == rawParams.length() - 1) break; // filtering invalid sequences =&.. cur = ampIdx + 1; continue; } String key = URLEncoder.decode(rawParams.substring(cur, eqIdx)); if (ampIdx == -1) { // last key-value pair params.put(key, URLEncoder.decode(rawParams.substring(eqIdx + 1))); break; } params.put(key, URLEncoder.decode(rawParams.substring(eqIdx + 1, ampIdx))); cur = ampIdx + 1; } return params; } public int getHeaderCount() { return headerCount; } public String[] getHeaders() { return headers; } public String getHeader(String key) { int keyLength = key.length(); for (int i = 0; i < headerCount; i++) { if (headers[i].regionMatches(true, 0, key, 0, keyLength)) { return trim(headers[i], keyLength); } } return null; } public void consumeHeaders(String prefix, Consumer<String> suffixConsumer) { int keyLength = prefix.length(); for (int i = 0; i < headerCount; i++) { if (headers[i].regionMatches(true, 0, prefix, 0, keyLength)) { suffixConsumer.accept(trim(headers[i], keyLength)); } } } public String getHeader(String key, String defaultValue) { String value = getHeader(key); return value != null ? value : defaultValue; } public String getRequiredHeader(String key) { String value = getHeader(key); if (value == null) { throw new NoSuchElementException("Missing required header: " + key); } return value; } public void addHeader(String header) { if (headerCount >= headers.length) { headers = Arrays.copyOf(headers, headers.length + 8); } headers[headerCount++] = header; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } public void setBodyUtf8(String body) { this.body = body.getBytes(StandardCharsets.UTF_8); } public String getHost() { String host = getHeader("Host:"); if (host == null) { return null; } int hostEndIndex = host.indexOf(':'); return hostEndIndex >= 0 ? host.substring(0, hostEndIndex) : host; } public byte[] toBytes() { int estimatedSize = VERBS[method].length + Utf8.length(uri) + PROTOCOL_HEADER_LENGTH + headerCount * 2; for (int i = 0; i < headerCount; i++) { estimatedSize += headers[i].length(); } if (body != null) { estimatedSize += body.length; } ByteArrayBuilder builder = new ByteArrayBuilder(estimatedSize); builder.append(VERBS[method]).append(uri).append(http11 ? HTTP11_HEADER : HTTP10_HEADER); for (int i = 0; i < headerCount; i++) { builder.append(headers[i]).append('\r').append('\n'); } builder.append('\r').append('\n'); if (body != null) { builder.append(body); } return builder.trim(); } @Override public String toString() { return new String(toBytes(), StandardCharsets.UTF_8); } static String trim(String s, int from) { int to = s.length(); while (from < to && s.charAt(from) <= ' ') from++; while (from < to && s.charAt(to - 1) <= ' ') to--; return s.substring(from, to); } }
UTF-8
Java
10,212
java
Request.java
Java
[ { "context": "tHeader(String key) {\n int keyLength = key.length();\n for (int i = 0; i < headerCount; i++) ", "end": 7395, "score": 0.9248407483100891, "start": 7389, "tag": "KEY", "value": "length" }, { "context": " suffixConsumer) {\n int keyLength = prefix.length();\n for (int i = 0; i < headerCount; i++) ", "end": 7741, "score": 0.81974858045578, "start": 7735, "tag": "KEY", "value": "length" } ]
null
[]
/* * Copyright 2015 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package one.nio.http; import one.nio.util.ByteArrayBuilder; import one.nio.util.URLEncoder; import one.nio.util.Utf8; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Consumer; public class Request { public static final int METHOD_GET = 1; public static final int METHOD_POST = 2; public static final int METHOD_HEAD = 3; public static final int METHOD_OPTIONS = 4; public static final int METHOD_PUT = 5; public static final int METHOD_DELETE = 6; public static final int METHOD_TRACE = 7; public static final int METHOD_CONNECT = 8; public static final int METHOD_PATCH = 9; public static final int NUMBER_OF_METHODS = 10; static final String[] METHODS = { "", "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "CONNECT", "PATCH" }; // Methods followed by a single space character static final byte[][] VERBS; static { VERBS = new byte[METHODS.length][]; VERBS[0] = new byte[0]; for (int i = 1; i < VERBS.length; i++) { VERBS[i] = Utf8.toBytes(METHODS[i] + ' '); } } private static final byte[] HTTP10_HEADER = Utf8.toBytes(" HTTP/1.0\r\n"); private static final byte[] HTTP11_HEADER = Utf8.toBytes(" HTTP/1.1\r\n"); private static final int PROTOCOL_HEADER_LENGTH = 13; private int method; private String uri; private boolean http11; private int params; // -1 if no query parameters private int headerCount; private String[] headers; private byte[] body; public Request(int method, String uri, boolean http11) { assert 0 <= method && method < METHODS.length; this.method = method; this.uri = uri; this.http11 = http11; this.params = uri.indexOf('?'); this.headerCount = 0; this.headers = new String[16]; } public Request(Request prototype) { this.method = prototype.method; this.uri = prototype.uri; this.http11 = prototype.http11; this.params = prototype.params; this.headerCount = prototype.headerCount; this.headers = prototype.headers.clone(); this.body = prototype.body; } public int getMethod() { return method; } public String getMethodName() { return METHODS[method]; } public String getURI() { return uri; } public boolean isHttp11() { return http11; } public String getPath() { return params >= 0 ? uri.substring(0, params) : uri; } public String getQueryString() { return params >= 0 ? URLEncoder.decode(uri.substring(params + 1)) : null; } public String getParameter(String key) { int cur = params + 1; while (cur > 0) { int next = uri.indexOf('&', cur); if (uri.startsWith(key, cur)) { cur += key.length(); String rawValue = next > 0 ? uri.substring(cur, next) : uri.substring(cur); return URLEncoder.decode(rawValue); } cur = next + 1; } return null; } public Iterator<String> getParameters(final String key) { return new Iterator<String>() { int cur = findNext(params + 1); @Override public boolean hasNext() { return cur > 0; } @Override public String next() { int next = uri.indexOf('&', cur); cur += key.length(); String rawValue = next > 0 ? uri.substring(cur, next) : uri.substring(cur); cur = findNext(next + 1); return URLEncoder.decode(rawValue); } @Override public void remove() { throw new UnsupportedOperationException(); } private int findNext(int cur) { while (cur > 0 && !uri.startsWith(key, cur)) { cur = uri.indexOf('&', cur) + 1; } return cur; } }; } public String getParameter(String key, String defaultValue) { String value = getParameter(key); return value != null ? value : defaultValue; } public String getRequiredParameter(String key) { String value = getParameter(key); if (value == null) { throw new NoSuchElementException("Missing required parameter: " + key); } return value; } /** * @return {@link Iterable} over {@code String} {@code key[=[value]]} parameters * skipping empty parameters */ public Iterable<Map.Entry<String, String>> getParameters() { if (params < 0) { return Collections.emptyList(); } return new Iterable<Map.Entry<String, String>>() { @Override public Iterator<Map.Entry<String, String>> iterator() { return new QueryParameterIterator(uri.substring(params + 1)); } }; } public Map<String, String> getPostParams() { if (method != METHOD_POST || body == null || body.length == 0) { return Collections.emptyMap(); } String rawParams = new String(body, StandardCharsets.UTF_8); Map<String, String> params = new HashMap<>(); int cur = 0; while (cur >= 0 && cur < rawParams.length()) { int eqIdx = rawParams.indexOf('=', cur); if (eqIdx < 0) return params; int ampIdx = rawParams.indexOf('&', eqIdx); if (eqIdx == cur) { // key=value&= if (eqIdx == rawParams.length() - 1) break; // filtering invalid sequences =&.. cur = ampIdx + 1; continue; } String key = URLEncoder.decode(rawParams.substring(cur, eqIdx)); if (ampIdx == -1) { // last key-value pair params.put(key, URLEncoder.decode(rawParams.substring(eqIdx + 1))); break; } params.put(key, URLEncoder.decode(rawParams.substring(eqIdx + 1, ampIdx))); cur = ampIdx + 1; } return params; } public int getHeaderCount() { return headerCount; } public String[] getHeaders() { return headers; } public String getHeader(String key) { int keyLength = key.length(); for (int i = 0; i < headerCount; i++) { if (headers[i].regionMatches(true, 0, key, 0, keyLength)) { return trim(headers[i], keyLength); } } return null; } public void consumeHeaders(String prefix, Consumer<String> suffixConsumer) { int keyLength = prefix.length(); for (int i = 0; i < headerCount; i++) { if (headers[i].regionMatches(true, 0, prefix, 0, keyLength)) { suffixConsumer.accept(trim(headers[i], keyLength)); } } } public String getHeader(String key, String defaultValue) { String value = getHeader(key); return value != null ? value : defaultValue; } public String getRequiredHeader(String key) { String value = getHeader(key); if (value == null) { throw new NoSuchElementException("Missing required header: " + key); } return value; } public void addHeader(String header) { if (headerCount >= headers.length) { headers = Arrays.copyOf(headers, headers.length + 8); } headers[headerCount++] = header; } public byte[] getBody() { return body; } public void setBody(byte[] body) { this.body = body; } public void setBodyUtf8(String body) { this.body = body.getBytes(StandardCharsets.UTF_8); } public String getHost() { String host = getHeader("Host:"); if (host == null) { return null; } int hostEndIndex = host.indexOf(':'); return hostEndIndex >= 0 ? host.substring(0, hostEndIndex) : host; } public byte[] toBytes() { int estimatedSize = VERBS[method].length + Utf8.length(uri) + PROTOCOL_HEADER_LENGTH + headerCount * 2; for (int i = 0; i < headerCount; i++) { estimatedSize += headers[i].length(); } if (body != null) { estimatedSize += body.length; } ByteArrayBuilder builder = new ByteArrayBuilder(estimatedSize); builder.append(VERBS[method]).append(uri).append(http11 ? HTTP11_HEADER : HTTP10_HEADER); for (int i = 0; i < headerCount; i++) { builder.append(headers[i]).append('\r').append('\n'); } builder.append('\r').append('\n'); if (body != null) { builder.append(body); } return builder.trim(); } @Override public String toString() { return new String(toBytes(), StandardCharsets.UTF_8); } static String trim(String s, int from) { int to = s.length(); while (from < to && s.charAt(from) <= ' ') from++; while (from < to && s.charAt(to - 1) <= ' ') to--; return s.substring(from, to); } }
10,212
0.557188
0.54671
339
29.123894
23.760035
111
false
false
0
0
0
0
0
0
0.59882
false
false
4
bda0ceb077944b670c88106a234714ffd3739d38
9,835,475,158,634
2c5aca1abd0952a29118c1ca8a98da3d7573b9c4
/src/main/java/com/zbl/algorithm/leetcode/primary/Test0016IsValid.java
93d999ea6dcf7bc9302d5396e09b7fcefe91b54f
[]
no_license
ZBL0507/mycode
https://github.com/ZBL0507/mycode
bfb8e258b8409660652b8dd7e1a44775a6ffc281
3e360cdb47b09506fbea03908ff82306628f8c2a
refs/heads/master
2022-12-28T11:52:29.832000
2022-12-25T04:22:06
2022-12-25T04:22:06
267,891,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zbl.algorithm.leetcode.primary; import java.util.HashMap; import java.util.Stack; /** * 有效的括号 * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。 * <p> * 有效字符串需满足: * 左括号必须用相同类型的右括号闭合。 * 左括号必须以正确的顺序闭合。 *   * 示例 1: * 输入:s = "()" * 输出:true * <p> * 示例 2: * 输入:s = "()[]{}" * 输出:true * <p> * 示例 3: * 输入:s = "(]" * 输出:false * <p> * 示例 4: * 输入:s = "([)]" * 输出:false * <p> * 示例 5: * 输入:s = "{[]}" * 输出:true * <p> * 作者:力扣 (LeetCode) * 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnbcaj/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ @SuppressWarnings("unused") public class Test0016IsValid { public static void main(String[] args) { boolean valid = isValid("()"); boolean valid2 = isValid("()[]{}"); boolean valid3 = isValid("(]"); boolean valid4 = isValid("([)]"); boolean valid5 = isValid("{[]}"); } private static boolean isValid(String s) { HashMap<Character, Character> map = new HashMap<>(); map.put('(', ')'); map.put('{', '}'); map.put('[', ']'); char[] chars = s.toCharArray(); Stack<Character> stack = new Stack<>(); stack.push(chars[0]); for (int i = 1; i < chars.length; i++) { if (stack.isEmpty()) { stack.push(chars[i]); continue; } if (map.get(stack.peek()) != null && chars[i] == map.get(stack.peek())) stack.pop(); else stack.push(chars[i]); } return stack.isEmpty(); } }
UTF-8
Java
1,953
java
Test0016IsValid.java
Java
[ { "context": " * 示例 5:\n * 输入:s = \"{[]}\"\n * 输出:true\n * <p>\n * 作者:力扣 (LeetCode)\n * 链接:https://leetcode-cn.com/leetbook", "end": 455, "score": 0.998744010925293, "start": 453, "tag": "NAME", "value": "力扣" } ]
null
[]
package com.zbl.algorithm.leetcode.primary; import java.util.HashMap; import java.util.Stack; /** * 有效的括号 * 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。 * <p> * 有效字符串需满足: * 左括号必须用相同类型的右括号闭合。 * 左括号必须以正确的顺序闭合。 *   * 示例 1: * 输入:s = "()" * 输出:true * <p> * 示例 2: * 输入:s = "()[]{}" * 输出:true * <p> * 示例 3: * 输入:s = "(]" * 输出:false * <p> * 示例 4: * 输入:s = "([)]" * 输出:false * <p> * 示例 5: * 输入:s = "{[]}" * 输出:true * <p> * 作者:力扣 (LeetCode) * 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnbcaj/ * 来源:力扣(LeetCode) * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ @SuppressWarnings("unused") public class Test0016IsValid { public static void main(String[] args) { boolean valid = isValid("()"); boolean valid2 = isValid("()[]{}"); boolean valid3 = isValid("(]"); boolean valid4 = isValid("([)]"); boolean valid5 = isValid("{[]}"); } private static boolean isValid(String s) { HashMap<Character, Character> map = new HashMap<>(); map.put('(', ')'); map.put('{', '}'); map.put('[', ']'); char[] chars = s.toCharArray(); Stack<Character> stack = new Stack<>(); stack.push(chars[0]); for (int i = 1; i < chars.length; i++) { if (stack.isEmpty()) { stack.push(chars[i]); continue; } if (map.get(stack.peek()) != null && chars[i] == map.get(stack.peek())) stack.pop(); else stack.push(chars[i]); } return stack.isEmpty(); } }
1,953
0.495975
0.486687
70
22.071428
18.31184
83
false
false
0
0
0
0
0
0
0.371429
false
false
4
7765d5a5aac413cdc721c701d79603fdab92c24f
20,392,504,758,440
4668a791a3a392ee6a1e3496ae49dadd4b709e5c
/src/Box.java
00487d0a986d1146ef4fe5d8b0d6df07debd434f
[]
no_license
buterbrodskey/GenericsHW
https://github.com/buterbrodskey/GenericsHW
d8ba1516a54c77ce94535f353dffc6180a55b8e3
1442abf2b2f9989ebf8410ee58cf7f836794e95f
refs/heads/master
2023-03-23T20:20:14.706000
2021-03-22T08:57:38
2021-03-22T08:57:38
347,447,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Box<T> { private T element; public void put(T element) { this.element = element; } public T get() { return element; } @Override public String toString() { if (element == null) { return "коробка пуста"; } else { return "в коробке лежит " + element.toString(); } } }
UTF-8
Java
410
java
Box.java
Java
[]
null
[]
public class Box<T> { private T element; public void put(T element) { this.element = element; } public T get() { return element; } @Override public String toString() { if (element == null) { return "коробка пуста"; } else { return "в коробке лежит " + element.toString(); } } }
410
0.490909
0.490909
21
17.333334
14.862331
59
false
false
0
0
0
0
0
0
0.238095
false
false
4
04378d16714f6b5d4a04f11cffe5c8bf368b5163
8,375,186,283,812
505224b0ac1b4825df4e131249832841795f1161
/Leanandroid/src/loc/imgandanima/PaintImgView.java
780b42f17364f863725288b07ce46f16541763e8
[]
no_license
ak47007tiger/leaninandroid
https://github.com/ak47007tiger/leaninandroid
87db41f2c877ae0a1372d6d1260184db0767ed25
3a19dddca873d3dc098b0e69bbb4c0044e0552d8
refs/heads/master
2021-01-22T04:57:16.466000
2015-03-07T07:09:52
2015-03-07T07:09:52
31,804,154
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package loc.imgandanima; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import org.leanandroid.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.util.AttributeSet; import android.view.View; public class PaintImgView extends View { public PaintImgView(Context context) { super(context); } Bitmap bitmap; int hSum = 20; int vSum = 20; int sizeH;// 格子水平长 int sizeV;// 格子垂直长 int vertSum;// 顶点总数量 int vertSumH;// 水平顶点数量 int vertSumV;// 垂直顶点数量 float[] array_origin;// 保存顶点横、纵坐标 float[] array_cur; public PaintImgView(Context context, AttributeSet attrs) { super(context, attrs); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jiker201300163343703); vertSumH = hSum + 1; vertSumV = vSum + 1; sizeH = bitmap.getWidth() / hSum; sizeV = bitmap.getHeight() / vSum; vertSum = (vertSumH) * (vertSumV); array_origin = new float[vertSum * 2]; for (int i = 0; i < vertSum; i += 2) { array_origin[i] = i * sizeH;// 横坐标 = 顶点横向 * 格子水平长 array_origin[i + 1] = i / vertSumH * sizeV;// 纵坐标 = 顶点纵向 * 顶点垂直长 } array_cur = array_origin.clone(); Timer timer; timer = new Timer(); timer.schedule(timerTask, 1000, 1000); } TimerTask timerTask = new TimerTask() { Random random = new Random(System.currentTimeMillis()); int x, y; @Override public void run() { x = random.nextInt(bitmap.getWidth()); y = random.nextInt(bitmap.getHeight()); for(int i = 0; i < vertSum; i+=2){ array_cur[i] = array_origin[i] + x * y; array_cur[i + 1] = array_origin[i + 1] + x * y; } handler.sendEmptyMessage(0); } }; Handler handler = new Handler(){ public void dispatchMessage(android.os.Message msg) { invalidate(); }; }; public PaintImgView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmapMesh(bitmap, hSum, vSum, array_cur, 0, null, 0, null); canvas.drawBitmap(bitmap, 0, 400, null); Paint paint; paint = new Paint(); paint.setColor(0x32dcf4); canvas.drawText("hello", 100, 100, paint); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); bitmap.recycle(); } }
UTF-8
Java
2,547
java
PaintImgView.java
Java
[]
null
[]
package loc.imgandanima; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import org.leanandroid.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Handler; import android.util.AttributeSet; import android.view.View; public class PaintImgView extends View { public PaintImgView(Context context) { super(context); } Bitmap bitmap; int hSum = 20; int vSum = 20; int sizeH;// 格子水平长 int sizeV;// 格子垂直长 int vertSum;// 顶点总数量 int vertSumH;// 水平顶点数量 int vertSumV;// 垂直顶点数量 float[] array_origin;// 保存顶点横、纵坐标 float[] array_cur; public PaintImgView(Context context, AttributeSet attrs) { super(context, attrs); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jiker201300163343703); vertSumH = hSum + 1; vertSumV = vSum + 1; sizeH = bitmap.getWidth() / hSum; sizeV = bitmap.getHeight() / vSum; vertSum = (vertSumH) * (vertSumV); array_origin = new float[vertSum * 2]; for (int i = 0; i < vertSum; i += 2) { array_origin[i] = i * sizeH;// 横坐标 = 顶点横向 * 格子水平长 array_origin[i + 1] = i / vertSumH * sizeV;// 纵坐标 = 顶点纵向 * 顶点垂直长 } array_cur = array_origin.clone(); Timer timer; timer = new Timer(); timer.schedule(timerTask, 1000, 1000); } TimerTask timerTask = new TimerTask() { Random random = new Random(System.currentTimeMillis()); int x, y; @Override public void run() { x = random.nextInt(bitmap.getWidth()); y = random.nextInt(bitmap.getHeight()); for(int i = 0; i < vertSum; i+=2){ array_cur[i] = array_origin[i] + x * y; array_cur[i + 1] = array_origin[i + 1] + x * y; } handler.sendEmptyMessage(0); } }; Handler handler = new Handler(){ public void dispatchMessage(android.os.Message msg) { invalidate(); }; }; public PaintImgView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmapMesh(bitmap, hSum, vSum, array_cur, 0, null, 0, null); canvas.drawBitmap(bitmap, 0, 400, null); Paint paint; paint = new Paint(); paint.setColor(0x32dcf4); canvas.drawText("hello", 100, 100, paint); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); bitmap.recycle(); } }
2,547
0.689328
0.667079
93
25.096775
18.031075
77
false
false
0
0
0
0
0
0
2.301075
false
false
4
0a1eb5e6bec5a320874c5400456e23c904ab4a33
28,613,072,159,142
b6f00d9589644b71b505bd66de7a15e160a49087
/core/src/test/java/org/eclipse/krazo/binding/convert/impl/ShortConverterTest.java
ee1febfe36d12b7197e7f5ded8dc33e7cf638a67
[ "Apache-2.0" ]
permissive
eclipse-ee4j/krazo
https://github.com/eclipse-ee4j/krazo
fdddd5074cc3193f583f40c6fd0df5db3d51e19d
bd8b1ac2612a9ffbd6ef493e1979a9b7310e2b7c
refs/heads/master
2023-08-19T00:28:04.369000
2023-07-25T09:24:14
2023-07-25T09:24:14
158,213,242
55
26
Apache-2.0
false
2023-07-25T09:24:15
2018-11-19T11:48:35
2023-06-07T20:51:53
2023-07-25T09:24:14
1,443
50
21
13
Java
false
false
/* * Copyright (c) 2019 Eclipse Krazo committers and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.eclipse.krazo.binding.convert.impl; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.List; /** * @author Gregor Tudan */ @RunWith(Enclosed.class) public class ShortConverterTest { public static class ConversionTests extends ConversionTest<Short> { public ConversionTests() { super(new ShortConverter(), Short.class); } @Parameters(name = "{0} converts to {1}") public static List<Object[]> getParameters() { return Arrays.asList( new Object[]{"12", (short) 12, false}, new Object[]{"0", (short) 0, false}, new Object[]{"-2", (short) -2, false}, new Object[]{"3E2", (short) 300, false}, new Object[]{"", null, false}, new Object[]{null, null, false}, new Object[]{"asd", null, true} // Flaky test: NaN resolves to 0 (java 11) or null (java 8) in the long-converter. // It triggers a binding error in java 8, but not in java 11 //new Object[]{"NaN", null, false} ); } } public static class Supports extends SupportsTest<Short> { public Supports() { super(new ShortConverter()); } @Parameters(name = "supports {0} | {1} = {2}") public static List<Object[]> getParameters() { return Arrays.asList( new Object[]{Short.class, EMPTY_ANNOTATIONS, true}, new Object[]{Number.class, EMPTY_ANNOTATIONS, false}, new Object[]{Object.class, EMPTY_ANNOTATIONS, false}, new Object[]{Double.class, EMPTY_ANNOTATIONS, false}, new Object[]{List.class, EMPTY_ANNOTATIONS, false} ); } } }
UTF-8
Java
2,596
java
ShortConverterTest.java
Java
[ { "context": "il.Arrays;\nimport java.util.List;\n\n\n/**\n * @author Gregor Tudan\n */\n@RunWith(Enclosed.class)\npublic class ShortCo", "end": 930, "score": 0.9998483657836914, "start": 918, "tag": "NAME", "value": "Gregor Tudan" } ]
null
[]
/* * Copyright (c) 2019 Eclipse Krazo committers and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.eclipse.krazo.binding.convert.impl; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.List; /** * @author <NAME> */ @RunWith(Enclosed.class) public class ShortConverterTest { public static class ConversionTests extends ConversionTest<Short> { public ConversionTests() { super(new ShortConverter(), Short.class); } @Parameters(name = "{0} converts to {1}") public static List<Object[]> getParameters() { return Arrays.asList( new Object[]{"12", (short) 12, false}, new Object[]{"0", (short) 0, false}, new Object[]{"-2", (short) -2, false}, new Object[]{"3E2", (short) 300, false}, new Object[]{"", null, false}, new Object[]{null, null, false}, new Object[]{"asd", null, true} // Flaky test: NaN resolves to 0 (java 11) or null (java 8) in the long-converter. // It triggers a binding error in java 8, but not in java 11 //new Object[]{"NaN", null, false} ); } } public static class Supports extends SupportsTest<Short> { public Supports() { super(new ShortConverter()); } @Parameters(name = "supports {0} | {1} = {2}") public static List<Object[]> getParameters() { return Arrays.asList( new Object[]{Short.class, EMPTY_ANNOTATIONS, true}, new Object[]{Number.class, EMPTY_ANNOTATIONS, false}, new Object[]{Object.class, EMPTY_ANNOTATIONS, false}, new Object[]{Double.class, EMPTY_ANNOTATIONS, false}, new Object[]{List.class, EMPTY_ANNOTATIONS, false} ); } } }
2,590
0.608243
0.594761
74
34.081081
26.871445
98
false
false
0
0
0
0
0
0
0.72973
false
false
4
dfba178c94d0dbd5acdfc7d35a3077b07587d1a8
20,349,555,072,152
0cec21d889860512f5402dee62efe137e9bab590
/xoa/src/com/xoa/util/netdisk/CheckAll.java
1684892de5ea86ca83ddeb245415355919802dbf
[]
no_license
dhxxhcb/testemptypro
https://github.com/dhxxhcb/testemptypro
0ab489098c44fa2292ec954241f42543f513dddf
8fc90b6b56121d895e4f497c997990450ea914c2
refs/heads/master
2021-01-25T06:44:54.311000
2017-06-07T09:50:29
2017-06-07T09:50:29
93,601,225
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xoa.util.netdisk; import com.xoa.util.common.StringUtils; import org.apache.poi.util.StringUtil; import java.util.Map; /** * Created by gsb on 2017/6/1. */ @SuppressWarnings("all") public class CheckAll { /** * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:21:36 * 方法介绍: 检查部门权限Id * 参数说明: @param DeptId * 参数说明: @param deptIdOfuser_Id * 参数说明: @return * @return boolean */ public static boolean checkDeptPriv(String DeptId,String deptIdOfuser_Id){ //如果部门部分权限为“ALL_DEPT" 则部门范围有访问权限。将直返回return true;停止执行程序 if("ALL_DEPT".equals(DeptId)||"ALL_DEPT"==DeptId){ return true; } //如果部门部分权限为拼接字符串则将字符串拆开验证 ,如果登录人员匹配得所属部门则将直返回return true;停止执行程序 if(DeptId!=null&&!"".equals(DeptId)){ String[] deptIds=DeptId.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIdOfuser_Id.equals(deptIds)){ return true; } } } //如果部门字符串为其他类型 证明其无权限访问return false; return false; } /** * * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:54:36 * 方法介绍: 检查角色权限Id * 参数说明: @param userPriv 角色id * 参数说明: @param userPrivOfuser_Id 角色字符串 * 参数说明: @return * @return boolean */ public static boolean checkUserPriv(String userPriv,String userPrivOfuser_Id){ //角色部分权限为拼接字符串,将字符串拆开验证 ,如果登录人员匹配得所属部门则将直接返回return true;停止执行程序 if(userPriv!=null&&!"".equals(userPriv)){ String[] deptIds=userPriv.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIds.equals(userPrivOfuser_Id)){ return true; } } } //如果角色部分字符串为其他类型 证明其无权限访问return false; return false; } /** * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:57:41 * 方法介绍: 人员权限验证 * 参数说明: @param userId 人员userId * 参数说明: @param userIdOfuser_Id * 参数说明: @return boolean * @return boolean */ public static boolean checkUserId(String userId,String userIdOfuser_Id){ //如果部门部分权限为拼接字符串则将字符串拆开验证 ,如果登录人员匹配得所属部门则将直返回return true;停止执行程序 if(userId!=null&&!"".equals(userId)){ String[] deptIds=userId.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIds[i].equals(userIdOfuser_Id)){ return true; } } } //如果部门字符串为其他类型 证明其无权限访问return false; return false; } public static boolean checkAll(String checkString,Map<String,Object> map){ //"|"转义字符串 所以必须用\\进行转义 因为 而且取出数组长度不确定 if (StringUtils.checkNull(checkString)){ return false; } String[] checkStrings=checkString.split("/|"); if(checkStrings.length==0){ return false; } //数组长度为1时 说明此时角色和用户Id权限为空 if(checkStrings.length==1){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ //调用校验部门方法 传值为部门id if(map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } } //数组长度为2时 说明此时角色和用户Id权限为空 if(checkStrings.length==2){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ //调用校验部门范围方法 传值为部门id if (map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } String[] checkUserPriv=checkStrings[1].split(","); for(int i=0;i<checkUserPriv.length;i++){ //调用校验角色范围方法 传值为角色id if (map.get("userPriv")!=null){ String userPrivId=map.get("userPriv").toString(); if(checkUserPriv(checkUserPriv[i],userPrivId)){ return true; } } else{ return false; } } } //数组长度为3时 说明此时部门、角色和用户Id权限都不为空 if(checkStrings.length==3){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ if (map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } String[] checkUserPriv=checkStrings[1].split(","); for(int i=0;i<checkUserPriv.length;i++){ //调用校验角色范围方法 传值为角色id if(map.get("userPriv")!=null){ String userPrivId=map.get("userPriv").toString(); if(checkUserPriv(checkUserPriv[i],userPrivId)){ return true; } } else{ return false; } } } String[] checkUserId=checkStrings[2].split(","); for(int i=0;i<checkUserId.length;i++){ //调用校验用户范围方法 传值为用户id if(map.get("userId")!=null){ String userId=map.get("userId").toString(); if(checkUserId(checkUserId[i],userId)){ return true; } } else{ return false; } } // return false; } }
UTF-8
Java
6,933
java
CheckAll.java
Java
[ { "context": "ingUtil;\n\nimport java.util.Map;\n\n/**\n * Created by gsb on 2017/6/1.\n */\n@SuppressWarnings(\"all\")\npublic ", "end": 155, "score": 0.998916745185852, "start": 152, "tag": "USERNAME", "value": "gsb" }, { "context": "lic class CheckAll {\n /**\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:21:36\n * 方法介绍", "end": 251, "score": 0.8425020575523376, "start": 251, "tag": "NAME", "value": "" }, { "context": "ic class CheckAll {\n /**\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:21:36\n * 方法介绍: ", "end": 255, "score": 0.9957753419876099, "start": 252, "tag": "NAME", "value": "杨 胜" }, { "context": " false;\n }\n /**\n *\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:54:36\n * 方法介绍", "end": 1127, "score": 0.7918150424957275, "start": 1127, "tag": "NAME", "value": "" }, { "context": "false;\n }\n /**\n *\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:54:36\n * 方法介绍: ", "end": 1131, "score": 0.9982956051826477, "start": 1128, "tag": "NAME", "value": "杨 胜" }, { "context": " return false;\n }\n /**\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:57:41\n * 方法介绍", "end": 1867, "score": 0.9994674324989319, "start": 1867, "tag": "NAME", "value": "" }, { "context": "return false;\n }\n /**\n *\n * 创建作者: 杨 胜\n * 创建日期: 2017-4-26 上午9:57:41\n * 方法介绍: ", "end": 1871, "score": 0.9866889715194702, "start": 1868, "tag": "NAME", "value": "杨 胜" } ]
null
[]
package com.xoa.util.netdisk; import com.xoa.util.common.StringUtils; import org.apache.poi.util.StringUtil; import java.util.Map; /** * Created by gsb on 2017/6/1. */ @SuppressWarnings("all") public class CheckAll { /** * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:21:36 * 方法介绍: 检查部门权限Id * 参数说明: @param DeptId * 参数说明: @param deptIdOfuser_Id * 参数说明: @return * @return boolean */ public static boolean checkDeptPriv(String DeptId,String deptIdOfuser_Id){ //如果部门部分权限为“ALL_DEPT" 则部门范围有访问权限。将直返回return true;停止执行程序 if("ALL_DEPT".equals(DeptId)||"ALL_DEPT"==DeptId){ return true; } //如果部门部分权限为拼接字符串则将字符串拆开验证 ,如果登录人员匹配得所属部门则将直返回return true;停止执行程序 if(DeptId!=null&&!"".equals(DeptId)){ String[] deptIds=DeptId.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIdOfuser_Id.equals(deptIds)){ return true; } } } //如果部门字符串为其他类型 证明其无权限访问return false; return false; } /** * * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:54:36 * 方法介绍: 检查角色权限Id * 参数说明: @param userPriv 角色id * 参数说明: @param userPrivOfuser_Id 角色字符串 * 参数说明: @return * @return boolean */ public static boolean checkUserPriv(String userPriv,String userPrivOfuser_Id){ //角色部分权限为拼接字符串,将字符串拆开验证 ,如果登录人员匹配得所属部门则将直接返回return true;停止执行程序 if(userPriv!=null&&!"".equals(userPriv)){ String[] deptIds=userPriv.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIds.equals(userPrivOfuser_Id)){ return true; } } } //如果角色部分字符串为其他类型 证明其无权限访问return false; return false; } /** * * 创建作者: 杨 胜 * 创建日期: 2017-4-26 上午9:57:41 * 方法介绍: 人员权限验证 * 参数说明: @param userId 人员userId * 参数说明: @param userIdOfuser_Id * 参数说明: @return boolean * @return boolean */ public static boolean checkUserId(String userId,String userIdOfuser_Id){ //如果部门部分权限为拼接字符串则将字符串拆开验证 ,如果登录人员匹配得所属部门则将直返回return true;停止执行程序 if(userId!=null&&!"".equals(userId)){ String[] deptIds=userId.split(","); for(int i=0;i<deptIds.length;i++){ if(deptIds[i].equals(userIdOfuser_Id)){ return true; } } } //如果部门字符串为其他类型 证明其无权限访问return false; return false; } public static boolean checkAll(String checkString,Map<String,Object> map){ //"|"转义字符串 所以必须用\\进行转义 因为 而且取出数组长度不确定 if (StringUtils.checkNull(checkString)){ return false; } String[] checkStrings=checkString.split("/|"); if(checkStrings.length==0){ return false; } //数组长度为1时 说明此时角色和用户Id权限为空 if(checkStrings.length==1){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ //调用校验部门方法 传值为部门id if(map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } } //数组长度为2时 说明此时角色和用户Id权限为空 if(checkStrings.length==2){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ //调用校验部门范围方法 传值为部门id if (map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } String[] checkUserPriv=checkStrings[1].split(","); for(int i=0;i<checkUserPriv.length;i++){ //调用校验角色范围方法 传值为角色id if (map.get("userPriv")!=null){ String userPrivId=map.get("userPriv").toString(); if(checkUserPriv(checkUserPriv[i],userPrivId)){ return true; } } else{ return false; } } } //数组长度为3时 说明此时部门、角色和用户Id权限都不为空 if(checkStrings.length==3){ String[] checkDept=checkStrings[0].split(","); for(int i=0;i<checkDept.length;i++){ if (map.get("deptId")!=null){ String depId=map.get("deptId").toString(); if(checkDeptPriv(checkDept[i],depId)){ return true; } }else{ return false; } } String[] checkUserPriv=checkStrings[1].split(","); for(int i=0;i<checkUserPriv.length;i++){ //调用校验角色范围方法 传值为角色id if(map.get("userPriv")!=null){ String userPrivId=map.get("userPriv").toString(); if(checkUserPriv(checkUserPriv[i],userPrivId)){ return true; } } else{ return false; } } } String[] checkUserId=checkStrings[2].split(","); for(int i=0;i<checkUserId.length;i++){ //调用校验用户范围方法 传值为用户id if(map.get("userId")!=null){ String userId=map.get("userId").toString(); if(checkUserId(checkUserId[i],userId)){ return true; } } else{ return false; } } // return false; } }
6,933
0.483663
0.472829
182
31.456043
19.384932
82
false
false
0
0
0
0
0
0
0.478022
false
false
4
daeac2ec27b89672019f1e397c2287165c1e4269
21,225,728,433,159
1bfd7433da0fbca534f3bb0f88fc2788b88b6952
/src/java/Modelo/CargosDAO.java
ff7c38519a3e6aff567e448a66144419f3d628d0
[]
no_license
Gesticom/Gesticom
https://github.com/Gesticom/Gesticom
f216f528a41d3643af204f63b3ca0dbe18299beb
02183f02db310ad8a7e52bb07dea3d3f24659274
refs/heads/master
2021-01-10T17:31:21.341000
2015-06-08T12:16:27
2015-06-08T12:36:07
36,138,218
0
1
null
false
2015-06-08T13:02:29
2015-05-23T19:08:34
2015-06-08T12:13:40
2015-06-08T13:02:29
40,846
0
1
1
JavaScript
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 Modelo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Washington */ public class CargosDAO { Connection con = Conexion.getInstace(); PreparedStatement stmt = null; ResultSet rs = null; public ArrayList<CargosDTO> ConsultarTodos() { ArrayList<CargosDTO> listado = new ArrayList<CargosDTO>(); try { stmt = con.prepareStatement("SELECT * FROM tb_cargo "); rs = stmt.executeQuery(); while (rs.next()) { CargosDTO uncargonew = new CargosDTO(); uncargonew.setId_Cargo(rs.getInt("Id_Cargo")); uncargonew.setCargo(rs.getString("Cargo")); listado.add(uncargonew); } } catch (SQLException sqle) { } return listado; } public String IngresarCargo(CargosDTO InsertarCargo){ String rta = ""; try { stmt = con.prepareStatement("INSERT INTO tb_cargo (Id_Cargo,Cargo) VALUES(?,?)"); stmt.setInt(1, InsertarCargo.getId_Cargo()); stmt.setString(2, InsertarCargo.getCargo()); int resultado = stmt.executeUpdate(); if (resultado == 0) { //resul=false; rta = "Fallo el ingreso del registro"; } else { rta = "Registro ingresado exitosamente"; } } catch (SQLException sqle) { rta = sqle.getMessage(); } return rta; } public String ActualizarCargo(CargosDTO ActualizarCargo) { //boolean resul = false; String rta = ""; int resultado = 0; try { stmt = con.prepareStatement("UPDATE tb_cargo SET Cargo=? WHERE Id_Cargo=?;"); stmt.setString(1, ActualizarCargo.getCargo()); stmt.setInt(2, ActualizarCargo.getId_Cargo()); resultado = stmt.executeUpdate(); if (resultado == 0) { //resul=false; rta = "Fallo la actualizacion del registro"; } else { rta = "Registro actualizado exitosamente"; } } catch (SQLException sqle) { rta = sqle.getMessage(); } return rta; } public String BorrarCargo(CargosDTO BorrarCargo) { //boolean resul = false; String rta=""; try { stmt = con.prepareStatement("DELETE FROM tb_cargo WHERE Id_Cargo=?"); stmt.setLong(1,BorrarCargo.getId_Cargo()); int resultado = stmt.executeUpdate(); if(resultado==0) { //resul=false; rta="Fallo al eliminar"; } else { rta="Registro eliminado Exitosamente"; } } catch (SQLException sqle) { rta=sqle.getMessage(); } return rta; } public CargosDTO consultarUnRegistro1(int id) { CargosDTO cargosdto = null; try{ stmt = con.prepareStatement("SELECT Id_Cargo, Cargo from tb_cargo where Id_Cargo= ?"); stmt.setInt(1, id); // usdto.setNombre(pstmt.toString()); rs = stmt.executeQuery(); if (rs != null) { while (rs.next()) { cargosdto = new CargosDTO(); cargosdto.setId_Cargo(rs.getInt("Id_Cargo")); cargosdto.setCargo(rs.getString("Cargo")); } } else { cargosdto=null; // throw new MyException("error al consultar byId"); } } catch(Exception e){cargosdto=null;} return cargosdto; } private PreparedStatement setInt(int i, long id_Cargo) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
4,487
java
CargosDAO.java
Java
[ { "context": "import java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author Washington\r\n */\r\npublic class CargosDAO {\r\n\r\n Connection co", "end": 394, "score": 0.90141361951828, "start": 384, "tag": "NAME", "value": "Washington" } ]
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 Modelo; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Washington */ public class CargosDAO { Connection con = Conexion.getInstace(); PreparedStatement stmt = null; ResultSet rs = null; public ArrayList<CargosDTO> ConsultarTodos() { ArrayList<CargosDTO> listado = new ArrayList<CargosDTO>(); try { stmt = con.prepareStatement("SELECT * FROM tb_cargo "); rs = stmt.executeQuery(); while (rs.next()) { CargosDTO uncargonew = new CargosDTO(); uncargonew.setId_Cargo(rs.getInt("Id_Cargo")); uncargonew.setCargo(rs.getString("Cargo")); listado.add(uncargonew); } } catch (SQLException sqle) { } return listado; } public String IngresarCargo(CargosDTO InsertarCargo){ String rta = ""; try { stmt = con.prepareStatement("INSERT INTO tb_cargo (Id_Cargo,Cargo) VALUES(?,?)"); stmt.setInt(1, InsertarCargo.getId_Cargo()); stmt.setString(2, InsertarCargo.getCargo()); int resultado = stmt.executeUpdate(); if (resultado == 0) { //resul=false; rta = "Fallo el ingreso del registro"; } else { rta = "Registro ingresado exitosamente"; } } catch (SQLException sqle) { rta = sqle.getMessage(); } return rta; } public String ActualizarCargo(CargosDTO ActualizarCargo) { //boolean resul = false; String rta = ""; int resultado = 0; try { stmt = con.prepareStatement("UPDATE tb_cargo SET Cargo=? WHERE Id_Cargo=?;"); stmt.setString(1, ActualizarCargo.getCargo()); stmt.setInt(2, ActualizarCargo.getId_Cargo()); resultado = stmt.executeUpdate(); if (resultado == 0) { //resul=false; rta = "Fallo la actualizacion del registro"; } else { rta = "Registro actualizado exitosamente"; } } catch (SQLException sqle) { rta = sqle.getMessage(); } return rta; } public String BorrarCargo(CargosDTO BorrarCargo) { //boolean resul = false; String rta=""; try { stmt = con.prepareStatement("DELETE FROM tb_cargo WHERE Id_Cargo=?"); stmt.setLong(1,BorrarCargo.getId_Cargo()); int resultado = stmt.executeUpdate(); if(resultado==0) { //resul=false; rta="Fallo al eliminar"; } else { rta="Registro eliminado Exitosamente"; } } catch (SQLException sqle) { rta=sqle.getMessage(); } return rta; } public CargosDTO consultarUnRegistro1(int id) { CargosDTO cargosdto = null; try{ stmt = con.prepareStatement("SELECT Id_Cargo, Cargo from tb_cargo where Id_Cargo= ?"); stmt.setInt(1, id); // usdto.setNombre(pstmt.toString()); rs = stmt.executeQuery(); if (rs != null) { while (rs.next()) { cargosdto = new CargosDTO(); cargosdto.setId_Cargo(rs.getInt("Id_Cargo")); cargosdto.setCargo(rs.getString("Cargo")); } } else { cargosdto=null; // throw new MyException("error al consultar byId"); } } catch(Exception e){cargosdto=null;} return cargosdto; } private PreparedStatement setInt(int i, long id_Cargo) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
4,487
0.507243
0.504792
149
28.114094
24.613123
135
false
false
0
0
0
0
0
0
0.52349
false
false
4
fd81a5d7e81757dcc3f18f43ca4acd1ef4e42c15
9,758,165,733,315
61f34e724aad35bb97805b3b30f8f182850329de
/generated/java/src/AdvertisingBoard.java
94a88b59ed96fb8e7cd456a195ea79b231ddd274
[]
no_license
Caramelo18/MFES-Project
https://github.com/Caramelo18/MFES-Project
7b0a8fda6e8dad0b7c1a9dec0e37491c9a0a53e8
23ae20a42cf5a0385aa9bef2d44f4ce94a6408a2
refs/heads/master
2021-03-24T13:02:18.387000
2018-01-03T21:18:40
2018-01-03T21:18:40
114,814,165
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import org.overture.codegen.runtime.*; @SuppressWarnings("all") public class AdvertisingBoard { private VDMSet artistOffers; private VDMMap bandRoleOffers; private VDMMap roadieOffers; private VDMSet placeOffers; private VDMSet hireBandOffers; private VDMSet gigs; private static VDMSeq places = SeqUtil.seq(); public void cg_init_AdvertisingBoard_1() { artistOffers = SetUtil.set(); bandRoleOffers = MapUtil.map( new Maplet(quotes.GuitarQuote.getInstance(), SetUtil.set()), new Maplet(quotes.BassQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DrumsQuote.getInstance(), SetUtil.set()), new Maplet(quotes.PianoQuote.getInstance(), SetUtil.set()), new Maplet(quotes.VocalQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DJQuote.getInstance(), SetUtil.set()), new Maplet(quotes.SaxophoneQuote.getInstance(), SetUtil.set()), new Maplet(quotes.ViolinQuote.getInstance(), SetUtil.set()), new Maplet(quotes.AccordeonQuote.getInstance(), SetUtil.set()), new Maplet(quotes.TubaQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DoubleBassQuote.getInstance(), SetUtil.set()), new Maplet(quotes.ViolaQuote.getInstance(), SetUtil.set()), new Maplet(quotes.CelloQuote.getInstance(), SetUtil.set()), new Maplet(quotes.XylophoneQuote.getInstance(), SetUtil.set()), new Maplet(quotes.BagpipesQuote.getInstance(), SetUtil.set())); roadieOffers = MapUtil.map(); placeOffers = SetUtil.set(); hireBandOffers = SetUtil.set(); gigs = SetUtil.set(); return; } public AdvertisingBoard() { cg_init_AdvertisingBoard_1(); } public VDMSet listArtistOffers() { return Utils.copy(artistOffers); } public VDMSet listArtistOffers(final Object i) { VDMSet list = SetUtil.set(); for (Iterator iterator_4 = artistOffers.iterator(); iterator_4.hasNext(); ) { ArtistOffer artistOffer = (ArtistOffer) iterator_4.next(); if (artistOffer.getArtist().playsInstrument(((Object) i))) { list = SetUtil.union(Utils.copy(list), SetUtil.set(artistOffer)); } } return Utils.copy(list); } public VDMSet listBandRoleOffers() { VDMSet list = SetUtil.set(); for (Iterator iterator_5 = MapUtil.rng(Utils.copy(bandRoleOffers)).iterator(); iterator_5.hasNext(); ) { VDMSet bro = (VDMSet) iterator_5.next(); list = SetUtil.union(Utils.copy(list), Utils.copy(bro)); } return Utils.copy(list); } public VDMSet listBandRoleOffers(final Object i) { return Utils.copy(((VDMSet) Utils.get(bandRoleOffers, i))); } public VDMSet listRoadieOffers() { VDMSet res = SetUtil.set(); for (Iterator iterator_6 = MapUtil.rng(Utils.copy(roadieOffers)).iterator(); iterator_6.hasNext(); ) { VDMSet ro = (VDMSet) iterator_6.next(); res = SetUtil.union(Utils.copy(res), Utils.copy(ro)); } return Utils.copy(res); } public VDMSet listRoadieOffers(final Object task) { return Utils.copy(((VDMSet) Utils.get(roadieOffers, task))); } public VDMSet listPlaceOffers() { return Utils.copy(placeOffers); } public VDMSet listPlaceOffers( final Boolean venue, final Boolean rehearsal, final Boolean recording) { VDMSet list = SetUtil.set(); for (Iterator iterator_7 = placeOffers.iterator(); iterator_7.hasNext(); ) { PlaceOffer placeOffer = (PlaceOffer) iterator_7.next(); Boolean andResult_6 = false; if (venue) { if (placeOffer.getPlace() instanceof Venue) { andResult_6 = true; } } if (andResult_6) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } else { Boolean andResult_7 = false; if (!(venue)) { if (placeOffer.getPlace() instanceof Studio) { andResult_7 = true; } } if (andResult_7) { Studio place = (Studio) placeOffer.getPlace(); Boolean andResult_8 = false; if (place.isRehearsal()) { if (rehearsal) { andResult_8 = true; } } if (andResult_8) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } else { Boolean andResult_9 = false; if (place.isRecording()) { if (recording) { andResult_9 = true; } } if (andResult_9) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } } } } } return Utils.copy(list); } public VDMSet listAvailableVenues(final JyveUtils.Date date) { VDMSet list = SetUtil.set(); for (Iterator iterator_8 = placeOffers.iterator(); iterator_8.hasNext(); ) { PlaceOffer placeOffer = (PlaceOffer) iterator_8.next(); if (placeOffer.getPlace() instanceof Venue) { Venue venue = (Venue) placeOffer.getPlace(); if (venue.isAvailable(Utils.copy(date))) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } } } return Utils.copy(list); } public VDMSet listHireBandOffers() { return Utils.copy(hireBandOffers); } public VDMSet listGigs() { return Utils.copy(gigs); } public VDMSet listGigs(final Venue v) { VDMSet gs = SetUtil.set(); for (Iterator iterator_9 = gigs.iterator(); iterator_9.hasNext(); ) { Gig g = (Gig) iterator_9.next(); if (Utils.equals(g.getVenue(), v)) { gs = SetUtil.union(Utils.copy(gs), SetUtil.set(g)); } } return Utils.copy(gs); } public VDMSet listGigs(final JyveUtils.Date d) { VDMSet gs = SetUtil.set(); for (Iterator iterator_10 = gigs.iterator(); iterator_10.hasNext(); ) { Gig g = (Gig) iterator_10.next(); if (Utils.equals(g.getDate(), d)) { gs = SetUtil.union(Utils.copy(gs), SetUtil.set(g)); } } return Utils.copy(gs); } public static VDMSeq listPlaces() { return Utils.copy(AdvertisingBoard.places); } public static VDMSeq listVenues() { VDMSeq res = SeqUtil.seq(); for (Iterator iterator_11 = SeqUtil.elems(Utils.copy(AdvertisingBoard.places)).iterator(); iterator_11.hasNext(); ) { Place p = (Place) iterator_11.next(); if (p instanceof Venue) { res = SeqUtil.conc(Utils.copy(res), SeqUtil.seq(p)); } } return Utils.copy(res); } public void addArtistOffer(final ArtistOffer ao) { artistOffers = SetUtil.union(Utils.copy(artistOffers), SetUtil.set(ao)); } public void deleteArtistOffer(final ArtistOffer ao) { artistOffers = SetUtil.diff(Utils.copy(artistOffers), SetUtil.set(ao)); } public void addBandRoleOffer(final BandRole br) { VDMSet newOffers = Utils.copy(((VDMSet) Utils.get(bandRoleOffers, br.getRole()))); VDMMap newMap = null; newOffers = SetUtil.union(Utils.copy(newOffers), SetUtil.set(br)); newMap = MapUtil.map(new Maplet(br.getRole(), Utils.copy(newOffers))); bandRoleOffers = MapUtil.override(Utils.copy(bandRoleOffers), Utils.copy(newMap)); } public void deleteBandRoleOffer(final BandRole br) { VDMSet newOffers = Utils.copy(((VDMSet) Utils.get(bandRoleOffers, br.getRole()))); VDMMap newMap = null; newOffers = SetUtil.diff(Utils.copy(newOffers), SetUtil.set(br)); newMap = MapUtil.map(new Maplet(br.getRole(), Utils.copy(newOffers))); bandRoleOffers = MapUtil.override(Utils.copy(bandRoleOffers), Utils.copy(newMap)); } public void addRoadieOffer(final RoadieOffer oo) { VDMSet newOffers = SetUtil.set(); VDMMap newInMap = null; if (SetUtil.inSet(oo.getTask(), MapUtil.dom(Utils.copy(roadieOffers)))) { newOffers = Utils.copy(((VDMSet) Utils.get(roadieOffers, oo.getTask()))); } newOffers = SetUtil.union(Utils.copy(newOffers), SetUtil.set(oo)); newInMap = MapUtil.map(new Maplet(oo.getTask(), Utils.copy(newOffers))); roadieOffers = MapUtil.override(Utils.copy(roadieOffers), Utils.copy(newInMap)); } public void deleteRoadieOffer(final RoadieOffer oo) { VDMSet newOffers = SetUtil.set(); VDMMap newInMap = null; if (SetUtil.inSet(oo.getTask(), MapUtil.dom(Utils.copy(roadieOffers)))) { newOffers = Utils.copy(((VDMSet) Utils.get(roadieOffers, oo.getTask()))); } newOffers = SetUtil.diff(Utils.copy(newOffers), SetUtil.set(oo)); newInMap = MapUtil.map(new Maplet(oo.getTask(), Utils.copy(newOffers))); roadieOffers = MapUtil.override(Utils.copy(roadieOffers), Utils.copy(newInMap)); } public void addPlaceOffer(final PlaceOffer po) { placeOffers = SetUtil.union(Utils.copy(placeOffers), SetUtil.set(po)); } public void deletePlaceOffer(final PlaceOffer po) { placeOffers = SetUtil.diff(Utils.copy(placeOffers), SetUtil.set(po)); } public void addHireBandOffer(final HireBand hb) { hireBandOffers = SetUtil.union(Utils.copy(hireBandOffers), SetUtil.set(hb)); } public void deleteHireBandOffer(final HireBand hb) { hireBandOffers = SetUtil.diff(Utils.copy(hireBandOffers), SetUtil.set(hb)); } public void addGig(final Gig g) { gigs = SetUtil.union(Utils.copy(gigs), SetUtil.set(g)); } public static void addPlace(final Place p) { places = SeqUtil.conc(Utils.copy(AdvertisingBoard.places), SeqUtil.seq(p)); } public String toString() { return "AdvertisingBoard{" + "artistOffers := " + Utils.toString(artistOffers) + ", bandRoleOffers := " + Utils.toString(bandRoleOffers) + ", roadieOffers := " + Utils.toString(roadieOffers) + ", placeOffers := " + Utils.toString(placeOffers) + ", hireBandOffers := " + Utils.toString(hireBandOffers) + ", gigs := " + Utils.toString(gigs) + ", places := " + Utils.toString(places) + "}"; } }
UTF-8
Java
10,089
java
AdvertisingBoard.java
Java
[]
null
[]
import java.util.*; import org.overture.codegen.runtime.*; @SuppressWarnings("all") public class AdvertisingBoard { private VDMSet artistOffers; private VDMMap bandRoleOffers; private VDMMap roadieOffers; private VDMSet placeOffers; private VDMSet hireBandOffers; private VDMSet gigs; private static VDMSeq places = SeqUtil.seq(); public void cg_init_AdvertisingBoard_1() { artistOffers = SetUtil.set(); bandRoleOffers = MapUtil.map( new Maplet(quotes.GuitarQuote.getInstance(), SetUtil.set()), new Maplet(quotes.BassQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DrumsQuote.getInstance(), SetUtil.set()), new Maplet(quotes.PianoQuote.getInstance(), SetUtil.set()), new Maplet(quotes.VocalQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DJQuote.getInstance(), SetUtil.set()), new Maplet(quotes.SaxophoneQuote.getInstance(), SetUtil.set()), new Maplet(quotes.ViolinQuote.getInstance(), SetUtil.set()), new Maplet(quotes.AccordeonQuote.getInstance(), SetUtil.set()), new Maplet(quotes.TubaQuote.getInstance(), SetUtil.set()), new Maplet(quotes.DoubleBassQuote.getInstance(), SetUtil.set()), new Maplet(quotes.ViolaQuote.getInstance(), SetUtil.set()), new Maplet(quotes.CelloQuote.getInstance(), SetUtil.set()), new Maplet(quotes.XylophoneQuote.getInstance(), SetUtil.set()), new Maplet(quotes.BagpipesQuote.getInstance(), SetUtil.set())); roadieOffers = MapUtil.map(); placeOffers = SetUtil.set(); hireBandOffers = SetUtil.set(); gigs = SetUtil.set(); return; } public AdvertisingBoard() { cg_init_AdvertisingBoard_1(); } public VDMSet listArtistOffers() { return Utils.copy(artistOffers); } public VDMSet listArtistOffers(final Object i) { VDMSet list = SetUtil.set(); for (Iterator iterator_4 = artistOffers.iterator(); iterator_4.hasNext(); ) { ArtistOffer artistOffer = (ArtistOffer) iterator_4.next(); if (artistOffer.getArtist().playsInstrument(((Object) i))) { list = SetUtil.union(Utils.copy(list), SetUtil.set(artistOffer)); } } return Utils.copy(list); } public VDMSet listBandRoleOffers() { VDMSet list = SetUtil.set(); for (Iterator iterator_5 = MapUtil.rng(Utils.copy(bandRoleOffers)).iterator(); iterator_5.hasNext(); ) { VDMSet bro = (VDMSet) iterator_5.next(); list = SetUtil.union(Utils.copy(list), Utils.copy(bro)); } return Utils.copy(list); } public VDMSet listBandRoleOffers(final Object i) { return Utils.copy(((VDMSet) Utils.get(bandRoleOffers, i))); } public VDMSet listRoadieOffers() { VDMSet res = SetUtil.set(); for (Iterator iterator_6 = MapUtil.rng(Utils.copy(roadieOffers)).iterator(); iterator_6.hasNext(); ) { VDMSet ro = (VDMSet) iterator_6.next(); res = SetUtil.union(Utils.copy(res), Utils.copy(ro)); } return Utils.copy(res); } public VDMSet listRoadieOffers(final Object task) { return Utils.copy(((VDMSet) Utils.get(roadieOffers, task))); } public VDMSet listPlaceOffers() { return Utils.copy(placeOffers); } public VDMSet listPlaceOffers( final Boolean venue, final Boolean rehearsal, final Boolean recording) { VDMSet list = SetUtil.set(); for (Iterator iterator_7 = placeOffers.iterator(); iterator_7.hasNext(); ) { PlaceOffer placeOffer = (PlaceOffer) iterator_7.next(); Boolean andResult_6 = false; if (venue) { if (placeOffer.getPlace() instanceof Venue) { andResult_6 = true; } } if (andResult_6) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } else { Boolean andResult_7 = false; if (!(venue)) { if (placeOffer.getPlace() instanceof Studio) { andResult_7 = true; } } if (andResult_7) { Studio place = (Studio) placeOffer.getPlace(); Boolean andResult_8 = false; if (place.isRehearsal()) { if (rehearsal) { andResult_8 = true; } } if (andResult_8) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } else { Boolean andResult_9 = false; if (place.isRecording()) { if (recording) { andResult_9 = true; } } if (andResult_9) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } } } } } return Utils.copy(list); } public VDMSet listAvailableVenues(final JyveUtils.Date date) { VDMSet list = SetUtil.set(); for (Iterator iterator_8 = placeOffers.iterator(); iterator_8.hasNext(); ) { PlaceOffer placeOffer = (PlaceOffer) iterator_8.next(); if (placeOffer.getPlace() instanceof Venue) { Venue venue = (Venue) placeOffer.getPlace(); if (venue.isAvailable(Utils.copy(date))) { list = SetUtil.union(Utils.copy(list), SetUtil.set(placeOffer)); } } } return Utils.copy(list); } public VDMSet listHireBandOffers() { return Utils.copy(hireBandOffers); } public VDMSet listGigs() { return Utils.copy(gigs); } public VDMSet listGigs(final Venue v) { VDMSet gs = SetUtil.set(); for (Iterator iterator_9 = gigs.iterator(); iterator_9.hasNext(); ) { Gig g = (Gig) iterator_9.next(); if (Utils.equals(g.getVenue(), v)) { gs = SetUtil.union(Utils.copy(gs), SetUtil.set(g)); } } return Utils.copy(gs); } public VDMSet listGigs(final JyveUtils.Date d) { VDMSet gs = SetUtil.set(); for (Iterator iterator_10 = gigs.iterator(); iterator_10.hasNext(); ) { Gig g = (Gig) iterator_10.next(); if (Utils.equals(g.getDate(), d)) { gs = SetUtil.union(Utils.copy(gs), SetUtil.set(g)); } } return Utils.copy(gs); } public static VDMSeq listPlaces() { return Utils.copy(AdvertisingBoard.places); } public static VDMSeq listVenues() { VDMSeq res = SeqUtil.seq(); for (Iterator iterator_11 = SeqUtil.elems(Utils.copy(AdvertisingBoard.places)).iterator(); iterator_11.hasNext(); ) { Place p = (Place) iterator_11.next(); if (p instanceof Venue) { res = SeqUtil.conc(Utils.copy(res), SeqUtil.seq(p)); } } return Utils.copy(res); } public void addArtistOffer(final ArtistOffer ao) { artistOffers = SetUtil.union(Utils.copy(artistOffers), SetUtil.set(ao)); } public void deleteArtistOffer(final ArtistOffer ao) { artistOffers = SetUtil.diff(Utils.copy(artistOffers), SetUtil.set(ao)); } public void addBandRoleOffer(final BandRole br) { VDMSet newOffers = Utils.copy(((VDMSet) Utils.get(bandRoleOffers, br.getRole()))); VDMMap newMap = null; newOffers = SetUtil.union(Utils.copy(newOffers), SetUtil.set(br)); newMap = MapUtil.map(new Maplet(br.getRole(), Utils.copy(newOffers))); bandRoleOffers = MapUtil.override(Utils.copy(bandRoleOffers), Utils.copy(newMap)); } public void deleteBandRoleOffer(final BandRole br) { VDMSet newOffers = Utils.copy(((VDMSet) Utils.get(bandRoleOffers, br.getRole()))); VDMMap newMap = null; newOffers = SetUtil.diff(Utils.copy(newOffers), SetUtil.set(br)); newMap = MapUtil.map(new Maplet(br.getRole(), Utils.copy(newOffers))); bandRoleOffers = MapUtil.override(Utils.copy(bandRoleOffers), Utils.copy(newMap)); } public void addRoadieOffer(final RoadieOffer oo) { VDMSet newOffers = SetUtil.set(); VDMMap newInMap = null; if (SetUtil.inSet(oo.getTask(), MapUtil.dom(Utils.copy(roadieOffers)))) { newOffers = Utils.copy(((VDMSet) Utils.get(roadieOffers, oo.getTask()))); } newOffers = SetUtil.union(Utils.copy(newOffers), SetUtil.set(oo)); newInMap = MapUtil.map(new Maplet(oo.getTask(), Utils.copy(newOffers))); roadieOffers = MapUtil.override(Utils.copy(roadieOffers), Utils.copy(newInMap)); } public void deleteRoadieOffer(final RoadieOffer oo) { VDMSet newOffers = SetUtil.set(); VDMMap newInMap = null; if (SetUtil.inSet(oo.getTask(), MapUtil.dom(Utils.copy(roadieOffers)))) { newOffers = Utils.copy(((VDMSet) Utils.get(roadieOffers, oo.getTask()))); } newOffers = SetUtil.diff(Utils.copy(newOffers), SetUtil.set(oo)); newInMap = MapUtil.map(new Maplet(oo.getTask(), Utils.copy(newOffers))); roadieOffers = MapUtil.override(Utils.copy(roadieOffers), Utils.copy(newInMap)); } public void addPlaceOffer(final PlaceOffer po) { placeOffers = SetUtil.union(Utils.copy(placeOffers), SetUtil.set(po)); } public void deletePlaceOffer(final PlaceOffer po) { placeOffers = SetUtil.diff(Utils.copy(placeOffers), SetUtil.set(po)); } public void addHireBandOffer(final HireBand hb) { hireBandOffers = SetUtil.union(Utils.copy(hireBandOffers), SetUtil.set(hb)); } public void deleteHireBandOffer(final HireBand hb) { hireBandOffers = SetUtil.diff(Utils.copy(hireBandOffers), SetUtil.set(hb)); } public void addGig(final Gig g) { gigs = SetUtil.union(Utils.copy(gigs), SetUtil.set(g)); } public static void addPlace(final Place p) { places = SeqUtil.conc(Utils.copy(AdvertisingBoard.places), SeqUtil.seq(p)); } public String toString() { return "AdvertisingBoard{" + "artistOffers := " + Utils.toString(artistOffers) + ", bandRoleOffers := " + Utils.toString(bandRoleOffers) + ", roadieOffers := " + Utils.toString(roadieOffers) + ", placeOffers := " + Utils.toString(placeOffers) + ", hireBandOffers := " + Utils.toString(hireBandOffers) + ", gigs := " + Utils.toString(gigs) + ", places := " + Utils.toString(places) + "}"; } }
10,089
0.632867
0.628506
330
29.569696
27.432833
94
false
false
0
0
0
0
0
0
0.581818
false
false
4
02a845600bdcec00123a24f6f81e5a9ff0555412
14,233,521,669,536
2397f05d32bb1df4e23135d73232b9e202d1c6f1
/src/main/java/com/superyc/heiniu/api/wx/WxApi.java
59653b81788bdf026f4fcd571261b6affa5c80d7
[]
no_license
XiaoyaoEzio/BlackCowMiniProgram
https://github.com/XiaoyaoEzio/BlackCowMiniProgram
b15f9d1ddcce4ca00a479d4ae12771356e767090
919649210722597392d72a38a0cc46cc10e65b1b
refs/heads/master
2022-12-24T10:05:33.575000
2019-06-07T04:15:43
2019-06-07T04:15:43
189,923,988
0
0
null
false
2022-12-16T11:07:22
2019-06-03T02:49:22
2019-06-07T04:16:21
2022-12-16T11:07:19
105
0
0
6
Java
false
false
package com.superyc.heiniu.api.wx; import com.fasterxml.jackson.annotation.JsonProperty; import com.superyc.heiniu.bean.CommonResponse; import com.superyc.heiniu.bean.ProxyCilentBankInfo; import com.superyc.heiniu.bean.TransferOrder; import com.superyc.heiniu.enums.ResponseCodeEnum; import com.superyc.heiniu.utils.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.util.DigestUtils; import javax.xml.bind.annotation.XmlAccessOrder; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import static java.lang.Thread.sleep; /** * 与微信服务器交互的api接口 */ @Component @SuppressWarnings("unused") public class WxApi { private static Logger LOG = LoggerFactory.getLogger(WxApi.class); private static String code2sessionUrl; private static String accessTokenUrl; private static String transferToBankUrl; private static String appIdKey; private static String appIdValue; private static String secretKey; private static String secretValue; private static String codeKey; private static String grantTypeKey; private static String grantTypeValue4Code; private static String grantTypeValue4Access; private static String unifiedOrderUrl; private static String mchId; private static String callbackUrlForPay; private static String tradeType; private static String payKey; private static String payBody; private static String pemPath; private static final String FAIL = "FAIL"; public static final String SUCCESS = "SUCCESS"; private static final AccessTokenResult ACCESS_TOKEN_RESULT = new AccessTokenResult(); /** * 使用code从微信后台换取用户相关信息 * 文档:https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html * * @param code 小程序方法 wx.login() 返回的code * @return openid,session_key,unionid等参数组成的对象 */ public static WxCode2SessionResult code2Session(String code) throws IOException { String authUrl = baseUrl(code2sessionUrl, grantTypeValue4Code).append("&") .append(codeKey).append("=").append(code) .toString(); String response = HttpUtils.get(authUrl); LOG.info("wx code2session response: {}", response); return JsonUtils.parseString(response, WxCode2SessionResult.class); } /** * 统一下单 * 文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1 */ public static CommonResponse unifiedOrder(String orderNumber, String openId, String payment, String userIp) throws IOException { UnifiedOrderParam param = new UnifiedOrderParam(); param.setAppId(appIdValue); param.setMchId(mchId); param.setNonceStr(RandomUtils.getUUID()); param.setBody(payBody); param.setOutTradeNo(orderNumber); param.setTotalFee(payment); param.setSpbillCreateIp(userIp); param.setNotifyUrl(callbackUrlForPay); param.setTradeType(tradeType); param.setOpenId(openId); param.setSign(generateSign(param, UnifiedOrderParam.class, payKey)); // 生成参数xml /*JAXBContext context = JAXBContext.newInstance(UnifiedOrderParam.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); Writer writer = new StringWriter(); marshaller.marshal(param, writer);*/ String xmlParam = XmlUtils.getXmlStr(param, UnifiedOrderParam.class); String response = HttpUtils.postXml(unifiedOrderUrl, xmlParam); // 解析响应参数 //context = JAXBContext.newInstance(UnifiedOrderResult.class); //Unmarshaller unmarshaller = context.createUnmarshaller(); //UnifiedOrderResult result = (UnifiedOrderResult) unmarshaller.unmarshal(new StringReader(response)); UnifiedOrderResult result = XmlUtils.parseXml(response, UnifiedOrderResult.class); if (result.getReturnCode().equals(FAIL)) { LOG.error("order number: {}; result: {}", orderNumber, result.getReturnMsg()); return CommonResponse.failure(result.getReturnMsg()); } if (result.getResultCode().equals(FAIL)) { String errMsg = result.getErrCode() + "-" + result.getErrCodeDes(); LOG.error("order number: {}; result: {}", orderNumber, errMsg); return CommonResponse.failure(errMsg); } // return_code 和 result_code 都是 SUCCESS 时 boolean checkSign = checkSign(result, UnifiedOrderResult.class); if (!checkSign) { LOG.error("签名校验失败,orderNumber:{}", orderNumber); } return CommonResponse.success(result.getPrepayId()); } /** * 再次签名,生成前端响应 * 文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 */ public static CommonResponse reSign(String prePayId) { ReSignParam param = new ReSignParam(); param.setAppId(appIdValue); param.setNonceStr(RandomUtils.getUUID()); param.setPackages("prepay_id=" + prePayId); param.setSignType("MD5"); param.setTimeStamp(Long.toString(System.currentTimeMillis() / 1000)); param.setPaySign(generateSign(param, ReSignParam.class, payKey)); return CommonResponse.success(param); } /** * 获取access_token, 用于与微信后端交互 * 文档:https://developers.weixin.qq.com/miniprogram/dev/api/getAccessToken.html * errCode 类型 * -1 系统繁忙,此时请开发者稍候再试 * 0 请求成功 * 40001 AppSecret 错误或者 AppSecret 不属于这个小程序,请开发者确认 AppSecret 的正确性 * 40002 请确保 grant_type 字段值为 client_credential * 40013 不合法的 AppID,请开发者检查 AppID 的正确性,避免异常字符,注意大小写 */ private static String getAccessToken() throws IOException, InterruptedException { long expiredTime = ACCESS_TOKEN_RESULT.getExpiredTime(); if (expiredTime > System.currentTimeMillis()) { return ACCESS_TOKEN_RESULT.getAccessToken(); } String url = baseUrl(accessTokenUrl, grantTypeValue4Access).toString(); String response = HttpUtils.get(url); LOG.info("access_token response: {}", response); AccessTokenResult result = JsonUtils.parseString(response, AccessTokenResult.class); int errCode = result.getErrCode(); if (errCode == 0) { ACCESS_TOKEN_RESULT.update(result); return ACCESS_TOKEN_RESULT.getAccessToken(); } else if (errCode == -1) { sleep(500); return getAccessToken(); } else { LOG.error("access_token error: {}", response); return null; } } /** * 生成签名,熊猫云的签名方法与微信的签名方法一致 */ public static <T> String generateSign(Object param, Class<T> clazz, String secret) { // 获取所有字段 Field[] fieldsAsArray = clazz.getDeclaredFields(); // 处理父类字段 List<Field> fieldList = new ArrayList<>(Arrays.asList(fieldsAsArray)); Class<? super T> superclass = clazz.getSuperclass(); if (superclass == WxPayBaseResult.class) { fieldList.addAll(Arrays.asList(superclass.getDeclaredFields())); } Field[] fields = fieldList.toArray(new Field[0]); // 将所有非空字段排序 SortedMap<String, String> map = new TreeMap<>(); for (Field field : fields) { String fieldName = field.getName(); // 处理内部类的特殊字段 if ("this$0".equals(fieldName)) { continue; } String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method getMethod = null; try { getMethod = clazz.getMethod("get" + methodName); } catch (NoSuchMethodException e) { LOG.error(e.getMessage()); e.printStackTrace(); } Assert.notNull(getMethod); Method setMethod = null; try { setMethod = clazz.getMethod("set" + methodName, String.class); } catch (NoSuchMethodException e) { LOG.error(e.getMessage()); e.printStackTrace(); } Assert.notNull(setMethod); String value = null; try { value = (String) getMethod.invoke(param); } catch (InvocationTargetException | IllegalAccessException e) { LOG.error(e.getMessage()); e.printStackTrace(); } if (value != null) { String mapKey = fieldName; // 处理 JsonProperty 注解的属性名 boolean annotationOnField = field.isAnnotationPresent(JsonProperty.class); if (annotationOnField) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); mapKey = jsonProperty.value(); } // 处理 XmlElement 注解的属性名 boolean annotationOnMethod = setMethod.isAnnotationPresent(XmlElement.class); if (annotationOnMethod) { XmlElement xmlElement = setMethod.getAnnotation(XmlElement.class); mapKey = xmlElement.name(); } map.put(mapKey, value); } } // 拼接所有字段和key StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } sb.append("key=").append(secret); LOG.debug("param string with key: {}", sb.toString()); return DigestUtils.md5DigestAsHex(sb.toString().getBytes()).toUpperCase(); } /** * 校验签名 */ public static <T> boolean checkSign(Signable param, Class<T> clazz) { String resultSign = param.getSign(); if (StringUtils.isBlank(resultSign)) { LOG.error("sign为空"); return false; } param.setSign(null); String generateSign = generateSign(param, clazz, payKey); if (!resultSign.equals(generateSign)) { LOG.error("校验sign失败"); return false; } return true; } /** * 向代理商银行卡转账 * 文档:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_2 */ public static WxApi.TransferResult transferToBank(ProxyCilentBankInfo bankInfo, TransferOrder order) throws IOException { TransferParam param = new TransferParam(); param.setAmount(order.getAmount()); param.setBankCode(bankInfo.getBankCode()); param.setDesc("用户充值"); param.setEncBankNo(RSAUtils.encrypt(bankInfo.getCardNum(), pemPath)); param.setEncTrueName(RSAUtils.encrypt(bankInfo.getPayeeName(), pemPath)); param.setMchId(mchId); param.setNoticeStr(RandomUtils.getUUID()); param.setPartnerTradeNo(order.getOrderNumber()); param.setSign(generateSign(param, TransferParam.class, payKey)); String xmlParam = XmlUtils.getXmlStr(param, TransferParam.class); String response = HttpUtils.postXml(transferToBankUrl, xmlParam); return XmlUtils.parseXml(response, TransferResult.class); } private static StringBuilder baseUrl(String uri, String grantType) { return new StringBuilder() .append(uri).append("?") .append(appIdKey).append("=").append(appIdValue).append("&") .append(secretKey).append("=").append(secretValue).append("&") .append(grantTypeKey).append("=").append(grantType); } /** * 用于接收微信后台传来的参数 */ @SuppressWarnings("unused") public static class WxCode2SessionResult { private String openid; private String session_key; private String unionid; private Integer errcode; private String errmsg; public WxCode2SessionResult() { } public WxCode2SessionResult(String openid, String session_key, String unionid) { this.openid = openid; this.session_key = session_key; this.unionid = unionid; } public WxCode2SessionResult(String openid, String session_key, String unionid, Integer errcode, String errmsg) { this.openid = openid; this.session_key = session_key; this.unionid = unionid; this.errcode = errcode; this.errmsg = errmsg; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getSession_key() { return session_key; } public void setSession_key(String session_key) { this.session_key = session_key; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public Integer getErrcode() { return errcode; } public void setErrcode(Integer errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } } /** * 微信返回的errcode有效值 */ public enum ErrcodeEnum { BUSYNESS(-1), SUCCESS(0), INVALID_CODE(40029), FREQUENCY_LIMITATION(45011); private int code; ErrcodeEnum(int code) { this.code = code; } public int getCode() { return code; } /** * 通过微信返回的错误值,获取自定义的错误值 */ public static ResponseCodeEnum getResponseCodeEnum(int errCode) { if (errCode == BUSYNESS.getCode()) { return ResponseCodeEnum.BUSYNESS; } if (errCode == INVALID_CODE.getCode()) { return ResponseCodeEnum.INVALID_CODE; } if (errCode == FREQUENCY_LIMITATION.getCode()) { return ResponseCodeEnum.FREQUENCY_LIMITATION; } return null; } } /** * 再次签名参数 */ @SuppressWarnings("SameParameterValue") public static class ReSignParam { @JsonProperty(value = "appid") private String appId; // 秒值 private String timeStamp; private String nonceStr; @JsonProperty(value = "package") private String packages; private String signType; private String paySign; public String getAppId() { return appId; } void setAppId(String appId) { this.appId = appId; } public String getTimeStamp() { return timeStamp; } void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public String getNonceStr() { return nonceStr; } void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getPackages() { return packages; } void setPackages(String packages) { this.packages = packages; } public String getSignType() { return signType; } void setSignType(String signType) { this.signType = signType; } public String getPaySign() { return paySign; } void setPaySign(String paySign) { this.paySign = paySign; } } /** * 统一下单请求参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class UnifiedOrderParam { private String appId; private String mchId; private String deviceInfo; private String nonceStr; private String sign; private String signType; private String body; private String detail; private String attach; private String outTradeNo; private String feeType; private String totalFee; private String spbillCreateIp; private String timeStart; private String timeExpire; private String goodsTag; private String notifyUrl; private String tradeType; private String productId; private String limitPay; private String openId; private String receipt; private String sceneInfo; public String getAppId() { return appId; } @XmlElement(name = "appid") void setAppId(String appId) { this.appId = appId; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") void setMchId(String mchId) { this.mchId = mchId; } public String getDeviceInfo() { return deviceInfo; } @XmlElement(name = "device_info") public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonceStr") void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getSign() { return sign; } @XmlElement(name = "sign") void setSign(String sign) { this.sign = sign; } public String getSignType() { return signType; } @XmlElement(name = "sign_type") public void setSignType(String signType) { this.signType = signType; } public String getBody() { return body; } @XmlElement(name = "body") void setBody(String body) { this.body = body; } public String getDetail() { return detail; } @XmlElement(name = "detail") public void setDetail(String detail) { this.detail = detail; } public String getAttach() { return attach; } @XmlElement(name = "attach") public void setAttach(String attach) { this.attach = attach; } public String getOutTradeNo() { return outTradeNo; } @XmlElement(name = "out_trade_no") void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getFeeType() { return feeType; } @XmlElement(name = "fee_type") public void setFeeType(String feeType) { this.feeType = feeType; } public String getTotalFee() { return totalFee; } @XmlElement(name = "total_fee") void setTotalFee(String totalFee) { this.totalFee = totalFee; } public String getSpbillCreateIp() { return spbillCreateIp; } @XmlElement(name = "spbill_create_ip") void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } @XmlElement(name = "time_start") public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } @XmlElement(name = "time_expire") public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } @XmlElement(name = "goods_tag") public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } public String getNotifyUrl() { return notifyUrl; } @XmlElement(name = "notify_url") void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getTradeType() { return tradeType; } @XmlElement(name = "trade_type") void setTradeType(String tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } @XmlElement(name = "product_id") public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } @XmlElement(name = "limit_pay") public void setLimitPay(String limitPay) { this.limitPay = limitPay; } public String getOpenId() { return openId; } @XmlElement(name = "openid") void setOpenId(String openId) { this.openId = openId; } public String getReceipt() { return receipt; } @XmlElement(name = "receipt") public void setReceipt(String receipt) { this.receipt = receipt; } public String getSceneInfo() { return sceneInfo; } @XmlElement(name = "scene_info") public void setSceneInfo(String sceneInfo) { this.sceneInfo = sceneInfo; } } /** * 微信支付的基本返回参数 */ private static class WxPayBaseResult implements Serializable, Signable { private String returnCode; private String returnMsg; private String appId; private String mchId; private String deviceInfo; private String nonceStr; private String openId; private String sign; private String resultCode; private String errCode; private String errCodeDes; private String tradeType; public String getDeviceInfo() { return deviceInfo; } @XmlElement(name = "device_info") public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } String getErrCode() { return errCode; } @XmlElement(name = "err_code") public void setErrCode(String errCode) { this.errCode = errCode; } String getErrCodeDes() { return errCodeDes; } @XmlElement(name = "err_code_des") public void setErrCodeDes(String errCodeDes) { this.errCodeDes = errCodeDes; } String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } public String getAppId() { return appId; } @XmlElement(name = "appid") public void setAppId(String appId) { this.appId = appId; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonceStr") public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getOpenId() { return openId; } @XmlElement(name = "openid") public void setOpenId(String openId) { this.openId = openId; } public String getSign() { return sign; } @XmlElement(name = "sign") public void setSign(String sign) { this.sign = sign; } String getResultCode() { return resultCode; } @XmlElement(name = "result_code") public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getTradeType() { return tradeType; } @XmlElement(name = "trade_type") public void setTradeType(String tradeType) { this.tradeType = tradeType; } } /** * 统一下单返回参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class UnifiedOrderResult extends WxPayBaseResult { private String prepayId; private String codeUrl; public String getCodeUrl() { return codeUrl; } @XmlElement(name = "code_url") public void setCodeUrl(String codeUrl) { this.codeUrl = codeUrl; } String getPrepayId() { return prepayId; } @XmlElement(name = "prepay_id") public void setPrepayId(String prepayId) { this.prepayId = prepayId; } } /** * 支付完成后回调参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class AfterPayCallbackParam extends WxPayBaseResult { private String signType; private String isSubscribe; private String bankType; private String totalFee; private String cashFee; private String transactionId; private String outTradeNo; private String timeEnd; public String getSignType() { return signType; } @XmlElement(name = "sign_type") public void setSignType(String signType) { this.signType = signType; } public String getIsSubscribe() { return isSubscribe; } @XmlElement(name = "is_subscribe") public void setIsSubscribe(String isSubscribe) { this.isSubscribe = isSubscribe; } public String getBankType() { return bankType; } @XmlElement(name = "bank_type") public void setBankType(String bankType) { this.bankType = bankType; } public String getTotalFee() { return totalFee; } @XmlElement(name = "total_fee") public void setTotalFee(String totalFee) { this.totalFee = totalFee; } public String getCashFee() { return cashFee; } @XmlElement(name = "cash_fee") public void setCashFee(String cashFee) { this.cashFee = cashFee; } public String getTransactionId() { return transactionId; } @XmlElement(name = "transaction_id") public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getOutTradeNo() { return outTradeNo; } @XmlElement(name = "is_subscribe") public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getTimeEnd() { return timeEnd; } @XmlElement(name = "time_end") public void setTimeEnd(String timeEnd) { this.timeEnd = timeEnd; } } /** * 处理完回调后,返回给微信后端的参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class AfterPayCallbackResponse { private String returnCode; private String returnMsg; public String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } } /** * 请求access_token后获取的参数 */ @SuppressWarnings("WeakerAccess") public static class AccessTokenResult { @JsonProperty(value = "access_token") private String accessToken; @JsonProperty(value = "expires_in") private int expiresIn; @JsonProperty(value = "errcode") private int errCode; @JsonProperty(value = "errmsg") private String errMsg; private long expiredTime; public void update(AccessTokenResult result) { this.accessToken = result.getAccessToken(); this.expiresIn = result.getExpiresIn(); this.errCode = result.getErrCode(); this.errMsg = result.getErrMsg(); this.expiredTime = System.currentTimeMillis() + this.expiresIn * 1000; } public long getExpiredTime() { return expiredTime; } public void setExpiredTime(long expiredTime) { this.expiredTime = expiredTime; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } } /** * 转账给代理商银行卡使用的参数 */ @SuppressWarnings("WeakerAccess") @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) private static class TransferParam { private int amount; private String bankCode; private String desc; private String encBankNo; private String encTrueName; private String mchId; private String noticeStr; private String partnerTradeNo; private String sign; public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getBankCode() { return bankCode; } @XmlElement(name = "bank_code") public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getEncBankNo() { return encBankNo; } @XmlElement(name = "enc_bank_no") public void setEncBankNo(String encBankNo) { this.encBankNo = encBankNo; } public String getEncTrueName() { return encTrueName; } @XmlElement(name = "enc_true_name") public void setEncTrueName(String encTrueName) { this.encTrueName = encTrueName; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getNoticeStr() { return noticeStr; } @XmlElement(name = "notice_str") public void setNoticeStr(String noticeStr) { this.noticeStr = noticeStr; } public String getPartnerTradeNo() { return partnerTradeNo; } @XmlElement(name = "partner_trade_no") public void setPartnerTradeNo(String partnerTradeNo) { this.partnerTradeNo = partnerTradeNo; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } } @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class TransferResult { private String returnCode; private String returnMsg; private String resultCode; private String errCode; private String errCodeDes; private String mchId; private String partnerTradeNo; private int amount; private String nonceStr; private String sign; private String paymentNo; private int cmmsAmt; public String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } public String getResultCode() { return resultCode; } @XmlElement(name = "result_code") public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getErrCode() { return errCode; } @XmlElement(name = "err_code") public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrCodeDes() { return errCodeDes; } @XmlElement(name = "err_code_des") public void setErrCodeDes(String errCodeDes) { this.errCodeDes = errCodeDes; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getPartnerTradeNo() { return partnerTradeNo; } @XmlElement(name = "partner_trade_no") public void setPartnerTradeNo(String partnerTradeNo) { this.partnerTradeNo = partnerTradeNo; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonce_str") public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getPaymentNo() { return paymentNo; } @XmlElement(name = "payment_no") public void setPaymentNo(String paymentNo) { this.paymentNo = paymentNo; } public int getCmmsAmt() { return cmmsAmt; } @XmlElement(name = "cmms_amt") public void setCmmsAmt(int cmmsAmt) { this.cmmsAmt = cmmsAmt; } @Override public String toString() { return "TransferResult{" + "returnCode='" + returnCode + '\'' + ", returnMsg='" + returnMsg + '\'' + ", resultCode='" + resultCode + '\'' + ", errCode='" + errCode + '\'' + ", errCodeDes='" + errCodeDes + '\'' + ", mchId='" + mchId + '\'' + ", partnerTradeNo='" + partnerTradeNo + '\'' + ", amount=" + amount + ", nonceStr='" + nonceStr + '\'' + ", sign='" + sign + '\'' + ", paymentNo='" + paymentNo + '\'' + ", cmmsAmt=" + cmmsAmt + '}'; } } public interface Signable { String getSign(); void setSign(String sign); } @Value("#{wx['transferToBankUrl']}") public void setTransferToBankUrl(String transferToBankUrl) { WxApi.transferToBankUrl = transferToBankUrl; } @Value("#{wx['pemPath']}") public void setPemPath(String pemPath) { WxApi.pemPath = pemPath; } @Value("#{wx['payBody']}") public void setPayBody(String payBody) { WxApi.payBody = payBody; } public static String getPayBody() { return payBody; } @Value("#{wx['code2sessionUrl']}") public void setCode2sessionUrl(String code2sessionUrl) { WxApi.code2sessionUrl = code2sessionUrl; } @Value("#{wx['accessTokenUrl']}") public void setAccessTokenUrl(String accessTokenUrl) { WxApi.accessTokenUrl = accessTokenUrl; } @Value("#{wx['appidKey']}") public void setAppIdKey(String appIdKey) { WxApi.appIdKey = appIdKey; } @Value("#{wx['secretKey']}") public void setSecretKey(String secretKey) { WxApi.secretKey = secretKey; } @Value("#{wx['grantTypeKey']}") public void setGrantTypeKey(String grantTypeKey) { WxApi.grantTypeKey = grantTypeKey; } @Value("#{wx['appidValue']}") public void setAppIdValue(String appIdValue) { WxApi.appIdValue = appIdValue; } @Value("#{wx['secretValue']}") public void setSecretValue(String secretValue) { WxApi.secretValue = secretValue; } @Value("#{wx['grantTypeValue4Code']}") public void setGrantTypeValue4Code(String grantTypeValue4Code) { WxApi.grantTypeValue4Code = grantTypeValue4Code; } @Value("#{wx['grantTypeValue4Access']}") public void setGrantTypeValue4Access(String grantTypeValue4Access) { WxApi.grantTypeValue4Access = grantTypeValue4Access; } @Value("#{wx['codeKey']}") public void setCodeKey(String codeKey) { WxApi.codeKey = codeKey; } @Value("#{wx['unifiedOrderUrl']}") public void setUnifiedOrderUrl(String unifiedOrderUrl) { WxApi.unifiedOrderUrl = unifiedOrderUrl; } @Value("#{wx['mchId']}") public void setMchId(String mchId) { WxApi.mchId = mchId; } @Value("#{wx['callbackUrlForPay']}") public void setCallbackUrlForPay(String callbackUrlForPay) { WxApi.callbackUrlForPay = callbackUrlForPay; } @Value("#{wx['tradeType']}") public void setTradeType(String tradeType) { WxApi.tradeType = tradeType; } @Value("#{wx['payKey']}") public void setPayKey(String payKey) { WxApi.payKey = payKey; } }
UTF-8
Java
40,120
java
WxApi.java
Java
[ { "context": " (value != null) {\n String mapKey = fieldName;\n // 处理 JsonProperty 注解的属性名\n ", "end": 9064, "score": 0.6020787358283997, "start": 9055, "tag": "KEY", "value": "fieldName" } ]
null
[]
package com.superyc.heiniu.api.wx; import com.fasterxml.jackson.annotation.JsonProperty; import com.superyc.heiniu.bean.CommonResponse; import com.superyc.heiniu.bean.ProxyCilentBankInfo; import com.superyc.heiniu.bean.TransferOrder; import com.superyc.heiniu.enums.ResponseCodeEnum; import com.superyc.heiniu.utils.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import org.springframework.util.DigestUtils; import javax.xml.bind.annotation.XmlAccessOrder; import javax.xml.bind.annotation.XmlAccessorOrder; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import static java.lang.Thread.sleep; /** * 与微信服务器交互的api接口 */ @Component @SuppressWarnings("unused") public class WxApi { private static Logger LOG = LoggerFactory.getLogger(WxApi.class); private static String code2sessionUrl; private static String accessTokenUrl; private static String transferToBankUrl; private static String appIdKey; private static String appIdValue; private static String secretKey; private static String secretValue; private static String codeKey; private static String grantTypeKey; private static String grantTypeValue4Code; private static String grantTypeValue4Access; private static String unifiedOrderUrl; private static String mchId; private static String callbackUrlForPay; private static String tradeType; private static String payKey; private static String payBody; private static String pemPath; private static final String FAIL = "FAIL"; public static final String SUCCESS = "SUCCESS"; private static final AccessTokenResult ACCESS_TOKEN_RESULT = new AccessTokenResult(); /** * 使用code从微信后台换取用户相关信息 * 文档:https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html * * @param code 小程序方法 wx.login() 返回的code * @return openid,session_key,unionid等参数组成的对象 */ public static WxCode2SessionResult code2Session(String code) throws IOException { String authUrl = baseUrl(code2sessionUrl, grantTypeValue4Code).append("&") .append(codeKey).append("=").append(code) .toString(); String response = HttpUtils.get(authUrl); LOG.info("wx code2session response: {}", response); return JsonUtils.parseString(response, WxCode2SessionResult.class); } /** * 统一下单 * 文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1&index=1 */ public static CommonResponse unifiedOrder(String orderNumber, String openId, String payment, String userIp) throws IOException { UnifiedOrderParam param = new UnifiedOrderParam(); param.setAppId(appIdValue); param.setMchId(mchId); param.setNonceStr(RandomUtils.getUUID()); param.setBody(payBody); param.setOutTradeNo(orderNumber); param.setTotalFee(payment); param.setSpbillCreateIp(userIp); param.setNotifyUrl(callbackUrlForPay); param.setTradeType(tradeType); param.setOpenId(openId); param.setSign(generateSign(param, UnifiedOrderParam.class, payKey)); // 生成参数xml /*JAXBContext context = JAXBContext.newInstance(UnifiedOrderParam.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); Writer writer = new StringWriter(); marshaller.marshal(param, writer);*/ String xmlParam = XmlUtils.getXmlStr(param, UnifiedOrderParam.class); String response = HttpUtils.postXml(unifiedOrderUrl, xmlParam); // 解析响应参数 //context = JAXBContext.newInstance(UnifiedOrderResult.class); //Unmarshaller unmarshaller = context.createUnmarshaller(); //UnifiedOrderResult result = (UnifiedOrderResult) unmarshaller.unmarshal(new StringReader(response)); UnifiedOrderResult result = XmlUtils.parseXml(response, UnifiedOrderResult.class); if (result.getReturnCode().equals(FAIL)) { LOG.error("order number: {}; result: {}", orderNumber, result.getReturnMsg()); return CommonResponse.failure(result.getReturnMsg()); } if (result.getResultCode().equals(FAIL)) { String errMsg = result.getErrCode() + "-" + result.getErrCodeDes(); LOG.error("order number: {}; result: {}", orderNumber, errMsg); return CommonResponse.failure(errMsg); } // return_code 和 result_code 都是 SUCCESS 时 boolean checkSign = checkSign(result, UnifiedOrderResult.class); if (!checkSign) { LOG.error("签名校验失败,orderNumber:{}", orderNumber); } return CommonResponse.success(result.getPrepayId()); } /** * 再次签名,生成前端响应 * 文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3 */ public static CommonResponse reSign(String prePayId) { ReSignParam param = new ReSignParam(); param.setAppId(appIdValue); param.setNonceStr(RandomUtils.getUUID()); param.setPackages("prepay_id=" + prePayId); param.setSignType("MD5"); param.setTimeStamp(Long.toString(System.currentTimeMillis() / 1000)); param.setPaySign(generateSign(param, ReSignParam.class, payKey)); return CommonResponse.success(param); } /** * 获取access_token, 用于与微信后端交互 * 文档:https://developers.weixin.qq.com/miniprogram/dev/api/getAccessToken.html * errCode 类型 * -1 系统繁忙,此时请开发者稍候再试 * 0 请求成功 * 40001 AppSecret 错误或者 AppSecret 不属于这个小程序,请开发者确认 AppSecret 的正确性 * 40002 请确保 grant_type 字段值为 client_credential * 40013 不合法的 AppID,请开发者检查 AppID 的正确性,避免异常字符,注意大小写 */ private static String getAccessToken() throws IOException, InterruptedException { long expiredTime = ACCESS_TOKEN_RESULT.getExpiredTime(); if (expiredTime > System.currentTimeMillis()) { return ACCESS_TOKEN_RESULT.getAccessToken(); } String url = baseUrl(accessTokenUrl, grantTypeValue4Access).toString(); String response = HttpUtils.get(url); LOG.info("access_token response: {}", response); AccessTokenResult result = JsonUtils.parseString(response, AccessTokenResult.class); int errCode = result.getErrCode(); if (errCode == 0) { ACCESS_TOKEN_RESULT.update(result); return ACCESS_TOKEN_RESULT.getAccessToken(); } else if (errCode == -1) { sleep(500); return getAccessToken(); } else { LOG.error("access_token error: {}", response); return null; } } /** * 生成签名,熊猫云的签名方法与微信的签名方法一致 */ public static <T> String generateSign(Object param, Class<T> clazz, String secret) { // 获取所有字段 Field[] fieldsAsArray = clazz.getDeclaredFields(); // 处理父类字段 List<Field> fieldList = new ArrayList<>(Arrays.asList(fieldsAsArray)); Class<? super T> superclass = clazz.getSuperclass(); if (superclass == WxPayBaseResult.class) { fieldList.addAll(Arrays.asList(superclass.getDeclaredFields())); } Field[] fields = fieldList.toArray(new Field[0]); // 将所有非空字段排序 SortedMap<String, String> map = new TreeMap<>(); for (Field field : fields) { String fieldName = field.getName(); // 处理内部类的特殊字段 if ("this$0".equals(fieldName)) { continue; } String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method getMethod = null; try { getMethod = clazz.getMethod("get" + methodName); } catch (NoSuchMethodException e) { LOG.error(e.getMessage()); e.printStackTrace(); } Assert.notNull(getMethod); Method setMethod = null; try { setMethod = clazz.getMethod("set" + methodName, String.class); } catch (NoSuchMethodException e) { LOG.error(e.getMessage()); e.printStackTrace(); } Assert.notNull(setMethod); String value = null; try { value = (String) getMethod.invoke(param); } catch (InvocationTargetException | IllegalAccessException e) { LOG.error(e.getMessage()); e.printStackTrace(); } if (value != null) { String mapKey = fieldName; // 处理 JsonProperty 注解的属性名 boolean annotationOnField = field.isAnnotationPresent(JsonProperty.class); if (annotationOnField) { JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); mapKey = jsonProperty.value(); } // 处理 XmlElement 注解的属性名 boolean annotationOnMethod = setMethod.isAnnotationPresent(XmlElement.class); if (annotationOnMethod) { XmlElement xmlElement = setMethod.getAnnotation(XmlElement.class); mapKey = xmlElement.name(); } map.put(mapKey, value); } } // 拼接所有字段和key StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } sb.append("key=").append(secret); LOG.debug("param string with key: {}", sb.toString()); return DigestUtils.md5DigestAsHex(sb.toString().getBytes()).toUpperCase(); } /** * 校验签名 */ public static <T> boolean checkSign(Signable param, Class<T> clazz) { String resultSign = param.getSign(); if (StringUtils.isBlank(resultSign)) { LOG.error("sign为空"); return false; } param.setSign(null); String generateSign = generateSign(param, clazz, payKey); if (!resultSign.equals(generateSign)) { LOG.error("校验sign失败"); return false; } return true; } /** * 向代理商银行卡转账 * 文档:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_2 */ public static WxApi.TransferResult transferToBank(ProxyCilentBankInfo bankInfo, TransferOrder order) throws IOException { TransferParam param = new TransferParam(); param.setAmount(order.getAmount()); param.setBankCode(bankInfo.getBankCode()); param.setDesc("用户充值"); param.setEncBankNo(RSAUtils.encrypt(bankInfo.getCardNum(), pemPath)); param.setEncTrueName(RSAUtils.encrypt(bankInfo.getPayeeName(), pemPath)); param.setMchId(mchId); param.setNoticeStr(RandomUtils.getUUID()); param.setPartnerTradeNo(order.getOrderNumber()); param.setSign(generateSign(param, TransferParam.class, payKey)); String xmlParam = XmlUtils.getXmlStr(param, TransferParam.class); String response = HttpUtils.postXml(transferToBankUrl, xmlParam); return XmlUtils.parseXml(response, TransferResult.class); } private static StringBuilder baseUrl(String uri, String grantType) { return new StringBuilder() .append(uri).append("?") .append(appIdKey).append("=").append(appIdValue).append("&") .append(secretKey).append("=").append(secretValue).append("&") .append(grantTypeKey).append("=").append(grantType); } /** * 用于接收微信后台传来的参数 */ @SuppressWarnings("unused") public static class WxCode2SessionResult { private String openid; private String session_key; private String unionid; private Integer errcode; private String errmsg; public WxCode2SessionResult() { } public WxCode2SessionResult(String openid, String session_key, String unionid) { this.openid = openid; this.session_key = session_key; this.unionid = unionid; } public WxCode2SessionResult(String openid, String session_key, String unionid, Integer errcode, String errmsg) { this.openid = openid; this.session_key = session_key; this.unionid = unionid; this.errcode = errcode; this.errmsg = errmsg; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getSession_key() { return session_key; } public void setSession_key(String session_key) { this.session_key = session_key; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public Integer getErrcode() { return errcode; } public void setErrcode(Integer errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } } /** * 微信返回的errcode有效值 */ public enum ErrcodeEnum { BUSYNESS(-1), SUCCESS(0), INVALID_CODE(40029), FREQUENCY_LIMITATION(45011); private int code; ErrcodeEnum(int code) { this.code = code; } public int getCode() { return code; } /** * 通过微信返回的错误值,获取自定义的错误值 */ public static ResponseCodeEnum getResponseCodeEnum(int errCode) { if (errCode == BUSYNESS.getCode()) { return ResponseCodeEnum.BUSYNESS; } if (errCode == INVALID_CODE.getCode()) { return ResponseCodeEnum.INVALID_CODE; } if (errCode == FREQUENCY_LIMITATION.getCode()) { return ResponseCodeEnum.FREQUENCY_LIMITATION; } return null; } } /** * 再次签名参数 */ @SuppressWarnings("SameParameterValue") public static class ReSignParam { @JsonProperty(value = "appid") private String appId; // 秒值 private String timeStamp; private String nonceStr; @JsonProperty(value = "package") private String packages; private String signType; private String paySign; public String getAppId() { return appId; } void setAppId(String appId) { this.appId = appId; } public String getTimeStamp() { return timeStamp; } void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public String getNonceStr() { return nonceStr; } void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getPackages() { return packages; } void setPackages(String packages) { this.packages = packages; } public String getSignType() { return signType; } void setSignType(String signType) { this.signType = signType; } public String getPaySign() { return paySign; } void setPaySign(String paySign) { this.paySign = paySign; } } /** * 统一下单请求参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class UnifiedOrderParam { private String appId; private String mchId; private String deviceInfo; private String nonceStr; private String sign; private String signType; private String body; private String detail; private String attach; private String outTradeNo; private String feeType; private String totalFee; private String spbillCreateIp; private String timeStart; private String timeExpire; private String goodsTag; private String notifyUrl; private String tradeType; private String productId; private String limitPay; private String openId; private String receipt; private String sceneInfo; public String getAppId() { return appId; } @XmlElement(name = "appid") void setAppId(String appId) { this.appId = appId; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") void setMchId(String mchId) { this.mchId = mchId; } public String getDeviceInfo() { return deviceInfo; } @XmlElement(name = "device_info") public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonceStr") void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getSign() { return sign; } @XmlElement(name = "sign") void setSign(String sign) { this.sign = sign; } public String getSignType() { return signType; } @XmlElement(name = "sign_type") public void setSignType(String signType) { this.signType = signType; } public String getBody() { return body; } @XmlElement(name = "body") void setBody(String body) { this.body = body; } public String getDetail() { return detail; } @XmlElement(name = "detail") public void setDetail(String detail) { this.detail = detail; } public String getAttach() { return attach; } @XmlElement(name = "attach") public void setAttach(String attach) { this.attach = attach; } public String getOutTradeNo() { return outTradeNo; } @XmlElement(name = "out_trade_no") void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getFeeType() { return feeType; } @XmlElement(name = "fee_type") public void setFeeType(String feeType) { this.feeType = feeType; } public String getTotalFee() { return totalFee; } @XmlElement(name = "total_fee") void setTotalFee(String totalFee) { this.totalFee = totalFee; } public String getSpbillCreateIp() { return spbillCreateIp; } @XmlElement(name = "spbill_create_ip") void setSpbillCreateIp(String spbillCreateIp) { this.spbillCreateIp = spbillCreateIp; } public String getTimeStart() { return timeStart; } @XmlElement(name = "time_start") public void setTimeStart(String timeStart) { this.timeStart = timeStart; } public String getTimeExpire() { return timeExpire; } @XmlElement(name = "time_expire") public void setTimeExpire(String timeExpire) { this.timeExpire = timeExpire; } public String getGoodsTag() { return goodsTag; } @XmlElement(name = "goods_tag") public void setGoodsTag(String goodsTag) { this.goodsTag = goodsTag; } public String getNotifyUrl() { return notifyUrl; } @XmlElement(name = "notify_url") void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getTradeType() { return tradeType; } @XmlElement(name = "trade_type") void setTradeType(String tradeType) { this.tradeType = tradeType; } public String getProductId() { return productId; } @XmlElement(name = "product_id") public void setProductId(String productId) { this.productId = productId; } public String getLimitPay() { return limitPay; } @XmlElement(name = "limit_pay") public void setLimitPay(String limitPay) { this.limitPay = limitPay; } public String getOpenId() { return openId; } @XmlElement(name = "openid") void setOpenId(String openId) { this.openId = openId; } public String getReceipt() { return receipt; } @XmlElement(name = "receipt") public void setReceipt(String receipt) { this.receipt = receipt; } public String getSceneInfo() { return sceneInfo; } @XmlElement(name = "scene_info") public void setSceneInfo(String sceneInfo) { this.sceneInfo = sceneInfo; } } /** * 微信支付的基本返回参数 */ private static class WxPayBaseResult implements Serializable, Signable { private String returnCode; private String returnMsg; private String appId; private String mchId; private String deviceInfo; private String nonceStr; private String openId; private String sign; private String resultCode; private String errCode; private String errCodeDes; private String tradeType; public String getDeviceInfo() { return deviceInfo; } @XmlElement(name = "device_info") public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } String getErrCode() { return errCode; } @XmlElement(name = "err_code") public void setErrCode(String errCode) { this.errCode = errCode; } String getErrCodeDes() { return errCodeDes; } @XmlElement(name = "err_code_des") public void setErrCodeDes(String errCodeDes) { this.errCodeDes = errCodeDes; } String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } public String getAppId() { return appId; } @XmlElement(name = "appid") public void setAppId(String appId) { this.appId = appId; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonceStr") public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getOpenId() { return openId; } @XmlElement(name = "openid") public void setOpenId(String openId) { this.openId = openId; } public String getSign() { return sign; } @XmlElement(name = "sign") public void setSign(String sign) { this.sign = sign; } String getResultCode() { return resultCode; } @XmlElement(name = "result_code") public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getTradeType() { return tradeType; } @XmlElement(name = "trade_type") public void setTradeType(String tradeType) { this.tradeType = tradeType; } } /** * 统一下单返回参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class UnifiedOrderResult extends WxPayBaseResult { private String prepayId; private String codeUrl; public String getCodeUrl() { return codeUrl; } @XmlElement(name = "code_url") public void setCodeUrl(String codeUrl) { this.codeUrl = codeUrl; } String getPrepayId() { return prepayId; } @XmlElement(name = "prepay_id") public void setPrepayId(String prepayId) { this.prepayId = prepayId; } } /** * 支付完成后回调参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class AfterPayCallbackParam extends WxPayBaseResult { private String signType; private String isSubscribe; private String bankType; private String totalFee; private String cashFee; private String transactionId; private String outTradeNo; private String timeEnd; public String getSignType() { return signType; } @XmlElement(name = "sign_type") public void setSignType(String signType) { this.signType = signType; } public String getIsSubscribe() { return isSubscribe; } @XmlElement(name = "is_subscribe") public void setIsSubscribe(String isSubscribe) { this.isSubscribe = isSubscribe; } public String getBankType() { return bankType; } @XmlElement(name = "bank_type") public void setBankType(String bankType) { this.bankType = bankType; } public String getTotalFee() { return totalFee; } @XmlElement(name = "total_fee") public void setTotalFee(String totalFee) { this.totalFee = totalFee; } public String getCashFee() { return cashFee; } @XmlElement(name = "cash_fee") public void setCashFee(String cashFee) { this.cashFee = cashFee; } public String getTransactionId() { return transactionId; } @XmlElement(name = "transaction_id") public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getOutTradeNo() { return outTradeNo; } @XmlElement(name = "is_subscribe") public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; } public String getTimeEnd() { return timeEnd; } @XmlElement(name = "time_end") public void setTimeEnd(String timeEnd) { this.timeEnd = timeEnd; } } /** * 处理完回调后,返回给微信后端的参数 */ @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class AfterPayCallbackResponse { private String returnCode; private String returnMsg; public String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } } /** * 请求access_token后获取的参数 */ @SuppressWarnings("WeakerAccess") public static class AccessTokenResult { @JsonProperty(value = "access_token") private String accessToken; @JsonProperty(value = "expires_in") private int expiresIn; @JsonProperty(value = "errcode") private int errCode; @JsonProperty(value = "errmsg") private String errMsg; private long expiredTime; public void update(AccessTokenResult result) { this.accessToken = result.getAccessToken(); this.expiresIn = result.getExpiresIn(); this.errCode = result.getErrCode(); this.errMsg = result.getErrMsg(); this.expiredTime = System.currentTimeMillis() + this.expiresIn * 1000; } public long getExpiredTime() { return expiredTime; } public void setExpiredTime(long expiredTime) { this.expiredTime = expiredTime; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } } /** * 转账给代理商银行卡使用的参数 */ @SuppressWarnings("WeakerAccess") @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) private static class TransferParam { private int amount; private String bankCode; private String desc; private String encBankNo; private String encTrueName; private String mchId; private String noticeStr; private String partnerTradeNo; private String sign; public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getBankCode() { return bankCode; } @XmlElement(name = "bank_code") public void setBankCode(String bankCode) { this.bankCode = bankCode; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getEncBankNo() { return encBankNo; } @XmlElement(name = "enc_bank_no") public void setEncBankNo(String encBankNo) { this.encBankNo = encBankNo; } public String getEncTrueName() { return encTrueName; } @XmlElement(name = "enc_true_name") public void setEncTrueName(String encTrueName) { this.encTrueName = encTrueName; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getNoticeStr() { return noticeStr; } @XmlElement(name = "notice_str") public void setNoticeStr(String noticeStr) { this.noticeStr = noticeStr; } public String getPartnerTradeNo() { return partnerTradeNo; } @XmlElement(name = "partner_trade_no") public void setPartnerTradeNo(String partnerTradeNo) { this.partnerTradeNo = partnerTradeNo; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } } @XmlRootElement(name = "xml") @XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL) public static class TransferResult { private String returnCode; private String returnMsg; private String resultCode; private String errCode; private String errCodeDes; private String mchId; private String partnerTradeNo; private int amount; private String nonceStr; private String sign; private String paymentNo; private int cmmsAmt; public String getReturnCode() { return returnCode; } @XmlElement(name = "return_code") public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMsg() { return returnMsg; } @XmlElement(name = "return_msg") public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } public String getResultCode() { return resultCode; } @XmlElement(name = "result_code") public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getErrCode() { return errCode; } @XmlElement(name = "err_code") public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrCodeDes() { return errCodeDes; } @XmlElement(name = "err_code_des") public void setErrCodeDes(String errCodeDes) { this.errCodeDes = errCodeDes; } public String getMchId() { return mchId; } @XmlElement(name = "mch_id") public void setMchId(String mchId) { this.mchId = mchId; } public String getPartnerTradeNo() { return partnerTradeNo; } @XmlElement(name = "partner_trade_no") public void setPartnerTradeNo(String partnerTradeNo) { this.partnerTradeNo = partnerTradeNo; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public String getNonceStr() { return nonceStr; } @XmlElement(name = "nonce_str") public void setNonceStr(String nonceStr) { this.nonceStr = nonceStr; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getPaymentNo() { return paymentNo; } @XmlElement(name = "payment_no") public void setPaymentNo(String paymentNo) { this.paymentNo = paymentNo; } public int getCmmsAmt() { return cmmsAmt; } @XmlElement(name = "cmms_amt") public void setCmmsAmt(int cmmsAmt) { this.cmmsAmt = cmmsAmt; } @Override public String toString() { return "TransferResult{" + "returnCode='" + returnCode + '\'' + ", returnMsg='" + returnMsg + '\'' + ", resultCode='" + resultCode + '\'' + ", errCode='" + errCode + '\'' + ", errCodeDes='" + errCodeDes + '\'' + ", mchId='" + mchId + '\'' + ", partnerTradeNo='" + partnerTradeNo + '\'' + ", amount=" + amount + ", nonceStr='" + nonceStr + '\'' + ", sign='" + sign + '\'' + ", paymentNo='" + paymentNo + '\'' + ", cmmsAmt=" + cmmsAmt + '}'; } } public interface Signable { String getSign(); void setSign(String sign); } @Value("#{wx['transferToBankUrl']}") public void setTransferToBankUrl(String transferToBankUrl) { WxApi.transferToBankUrl = transferToBankUrl; } @Value("#{wx['pemPath']}") public void setPemPath(String pemPath) { WxApi.pemPath = pemPath; } @Value("#{wx['payBody']}") public void setPayBody(String payBody) { WxApi.payBody = payBody; } public static String getPayBody() { return payBody; } @Value("#{wx['code2sessionUrl']}") public void setCode2sessionUrl(String code2sessionUrl) { WxApi.code2sessionUrl = code2sessionUrl; } @Value("#{wx['accessTokenUrl']}") public void setAccessTokenUrl(String accessTokenUrl) { WxApi.accessTokenUrl = accessTokenUrl; } @Value("#{wx['appidKey']}") public void setAppIdKey(String appIdKey) { WxApi.appIdKey = appIdKey; } @Value("#{wx['secretKey']}") public void setSecretKey(String secretKey) { WxApi.secretKey = secretKey; } @Value("#{wx['grantTypeKey']}") public void setGrantTypeKey(String grantTypeKey) { WxApi.grantTypeKey = grantTypeKey; } @Value("#{wx['appidValue']}") public void setAppIdValue(String appIdValue) { WxApi.appIdValue = appIdValue; } @Value("#{wx['secretValue']}") public void setSecretValue(String secretValue) { WxApi.secretValue = secretValue; } @Value("#{wx['grantTypeValue4Code']}") public void setGrantTypeValue4Code(String grantTypeValue4Code) { WxApi.grantTypeValue4Code = grantTypeValue4Code; } @Value("#{wx['grantTypeValue4Access']}") public void setGrantTypeValue4Access(String grantTypeValue4Access) { WxApi.grantTypeValue4Access = grantTypeValue4Access; } @Value("#{wx['codeKey']}") public void setCodeKey(String codeKey) { WxApi.codeKey = codeKey; } @Value("#{wx['unifiedOrderUrl']}") public void setUnifiedOrderUrl(String unifiedOrderUrl) { WxApi.unifiedOrderUrl = unifiedOrderUrl; } @Value("#{wx['mchId']}") public void setMchId(String mchId) { WxApi.mchId = mchId; } @Value("#{wx['callbackUrlForPay']}") public void setCallbackUrlForPay(String callbackUrlForPay) { WxApi.callbackUrlForPay = callbackUrlForPay; } @Value("#{wx['tradeType']}") public void setTradeType(String tradeType) { WxApi.tradeType = tradeType; } @Value("#{wx['payKey']}") public void setPayKey(String payKey) { WxApi.payKey = payKey; } }
40,120
0.575445
0.57313
1,400
27.071428
21.593433
132
false
false
0
0
0
0
0
0
0.381429
false
false
4
620bfd78664b98c09ef25d6ff66ab2d86743e45d
6,004,364,328,408
8188027594cc9389fb6200f9e2d17588c233e780
/src/worm/entities/Smartbomb.java
1287408fde4a40a5cb7712856afc1cd44c2d85df
[]
no_license
alilah/revengeofthetitans
https://github.com/alilah/revengeofthetitans
65a972480a24ef9428f87a3b3390f1b6a7652753
3152274bcb8355a33874fc0489992d5142fbad4a
refs/heads/master
2020-07-11T10:21:14.772000
2015-06-20T16:41:45
2015-06-20T16:41:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2003-onwards Shaven Puppy Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'Shaven Puppy' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package worm.entities; import net.puppygames.applet.effects.StrobeEffect; import org.lwjgl.util.ReadableColor; import org.lwjgl.util.Rectangle; import worm.Entity; import worm.GameStateInterface; import worm.SFX; import worm.effects.SmartbombEffect; import worm.screens.GameScreen; /** * $Id: Smartbomb.java,v 1.7 2010/03/29 22:39:46 foo Exp $ * * @author $Author: foo $ * @version $Revision: 1.7 $ */ public class Smartbomb extends Entity { private static final long serialVersionUID = 1L; /** Damage caused */ public static final int DAMAGE = 100; /** Effect */ private transient SmartbombEffect effect; /** * C'tor */ public Smartbomb(float x, float y) { setLocation(x, y); } @Override public boolean isShootable() { return false; } @Override public boolean isHoverable() { return false; } @Override protected void doSpawn() { effect = new SmartbombEffect(getMapX(), getMapY()); effect.setOffset(GameScreen.getSpriteOffset()); effect.spawn(GameScreen.getInstance()); StrobeEffect strobe = new StrobeEffect(ReadableColor.WHITE, SmartbombEffect.DURATION * 2); strobe.spawn(GameScreen.getInstance()); GameScreen.shake(32); SFX.smartbomb(); } @Override protected void doRespawn() { // Too much hassle remove(); } @Override protected void doRemove() { if (effect != null) { effect.remove(); effect = null; } } @Override protected void doTick() { if (effect == null || !effect.isActive()) { remove(); } } @Override public boolean canCollide() { return true; } @Override public void onCollision(Entity entity) { entity.onCollisionWithSmartbomb(this); } @Override public float getRadius() { if (effect == null) { return 0.0f; } else { return effect.getRadius(); } } @Override public boolean isRound() { return true; } @Override public Rectangle getBounds(Rectangle bounds) { bounds.setBounds(0, 0, 0, 0); return bounds; } @Override public final void addToGameState(GameStateInterface gsi) { // Ignore } @Override public final void removeFromGameState(GameStateInterface gsi) { // Ignore } }
UTF-8
Java
3,872
java
Smartbomb.java
Java
[ { "context": "/03/29 22:39:46 foo Exp $\r\n *\r\n * @author $Author: foo $\r\n * @version $Revision: 1.7 $\r\n */\r\npublic clas", "end": 2007, "score": 0.9949832558631897, "start": 2004, "tag": "USERNAME", "value": "foo" } ]
null
[]
/* * Copyright (c) 2003-onwards Shaven Puppy Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'Shaven Puppy' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package worm.entities; import net.puppygames.applet.effects.StrobeEffect; import org.lwjgl.util.ReadableColor; import org.lwjgl.util.Rectangle; import worm.Entity; import worm.GameStateInterface; import worm.SFX; import worm.effects.SmartbombEffect; import worm.screens.GameScreen; /** * $Id: Smartbomb.java,v 1.7 2010/03/29 22:39:46 foo Exp $ * * @author $Author: foo $ * @version $Revision: 1.7 $ */ public class Smartbomb extends Entity { private static final long serialVersionUID = 1L; /** Damage caused */ public static final int DAMAGE = 100; /** Effect */ private transient SmartbombEffect effect; /** * C'tor */ public Smartbomb(float x, float y) { setLocation(x, y); } @Override public boolean isShootable() { return false; } @Override public boolean isHoverable() { return false; } @Override protected void doSpawn() { effect = new SmartbombEffect(getMapX(), getMapY()); effect.setOffset(GameScreen.getSpriteOffset()); effect.spawn(GameScreen.getInstance()); StrobeEffect strobe = new StrobeEffect(ReadableColor.WHITE, SmartbombEffect.DURATION * 2); strobe.spawn(GameScreen.getInstance()); GameScreen.shake(32); SFX.smartbomb(); } @Override protected void doRespawn() { // Too much hassle remove(); } @Override protected void doRemove() { if (effect != null) { effect.remove(); effect = null; } } @Override protected void doTick() { if (effect == null || !effect.isActive()) { remove(); } } @Override public boolean canCollide() { return true; } @Override public void onCollision(Entity entity) { entity.onCollisionWithSmartbomb(this); } @Override public float getRadius() { if (effect == null) { return 0.0f; } else { return effect.getRadius(); } } @Override public boolean isRound() { return true; } @Override public Rectangle getBounds(Rectangle bounds) { bounds.setBounds(0, 0, 0, 0); return bounds; } @Override public final void addToGameState(GameStateInterface gsi) { // Ignore } @Override public final void removeFromGameState(GameStateInterface gsi) { // Ignore } }
3,872
0.694473
0.685434
154
23.142857
24.672512
92
false
false
0
0
0
0
0
0
1.175325
false
false
4
c2281123ddf040bcc87fdad8e23c0e57765fde92
19,628,000,584,760
104a8f667098c112dfa4e933b97fadebcf42ce96
/src/main/java/com/venosyd/open/commons/log/Debuggable.java
29ca67f3a1be95e0fdc4c9c1793dcc0bef9d0ed0
[ "MIT" ]
permissive
venosyd/opensyd_commons
https://github.com/venosyd/opensyd_commons
78032429ebb6671b24286fdcc488c177d354837e
f0e080b2acdff3d7c139a1dec2f50277aada8dbd
refs/heads/master
2023-03-31T07:18:30.920000
2021-04-10T01:34:50
2021-04-10T01:34:50
317,367,490
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.venosyd.open.commons.log; /** * @author sergio lisan <sels@venosyd.com> * * Utilidades para debug no console */ public interface Debuggable { /** */ Out out = new Out(); /** */ Err err = new Err(); }
UTF-8
Java
244
java
Debuggable.java
Java
[ { "context": "kage com.venosyd.open.commons.log;\n\n/**\n * @author sergio lisan <sels@venosyd.com>\n * \n * Utilidades para", "end": 66, "score": 0.9997806549072266, "start": 54, "tag": "NAME", "value": "sergio lisan" }, { "context": "d.open.commons.log;\n\n/**\n * @author sergio lisan <sels@venosyd.com>\n * \n * Utilidades para debug no console\n", "end": 84, "score": 0.9999334812164307, "start": 68, "tag": "EMAIL", "value": "sels@venosyd.com" } ]
null
[]
package com.venosyd.open.commons.log; /** * @author <NAME> <<EMAIL>> * * Utilidades para debug no console */ public interface Debuggable { /** */ Out out = new Out(); /** */ Err err = new Err(); }
229
0.569672
0.569672
15
15.266666
15.720334
43
false
false
0
0
0
0
0
0
0.2
false
false
4
6ffede91c7390de117c8ec628b2049d79b71ebed
8,211,977,510,768
5631d943723dd64b9a5c82f9be9ca708c0ef97b9
/seed-common/src/main/java/com/base/seed/common/monad/primitive/BoolFunctor.java
6b25c190834282bb73b36e88e427f5d6249e5d59
[ "MIT" ]
permissive
CoderEugene/Seed
https://github.com/CoderEugene/Seed
d6884d5a94e91b8880623c018436a8b09f8aca08
70e3c629586bdbfbee30aa3e8e0e0861d9f45879
refs/heads/master
2020-11-25T08:05:17.422000
2020-10-18T15:23:46
2020-10-18T15:23:46
228,567,175
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.base.seed.common.monad.primitive; @FunctionalInterface public interface BoolFunctor<T> { T apply(boolean value); default T apply(Boolean value) { return apply(value.booleanValue()); } }
UTF-8
Java
223
java
BoolFunctor.java
Java
[]
null
[]
package com.base.seed.common.monad.primitive; @FunctionalInterface public interface BoolFunctor<T> { T apply(boolean value); default T apply(Boolean value) { return apply(value.booleanValue()); } }
223
0.695067
0.695067
11
19.181818
17.667732
45
false
false
0
0
0
0
0
0
0.272727
false
false
4
f2667d214e8b6140e62a60fc258c7690d6c94b7b
26,568,667,702,361
0868235424f294a4866fb5e3e8148b2f88be51dc
/MBWSServers/src/de/mbws/server/data/db/generated/NpcSkillMapping.java
dada7d9a29dc8872a4d60e2b5efbeb7e8b416124
[]
no_license
BackupTheBerlios/bmws-svn
https://github.com/BackupTheBerlios/bmws-svn
27abdb417b082020d680668a42953f781ade5696
a4486eaa03af3d91ba878bf0066a662f92840f8c
refs/heads/master
2016-09-01T19:20:17.429000
2007-06-07T07:54:46
2007-06-07T07:54:46
40,669,489
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.mbws.server.data.db.generated; // Generated 14.04.2006 22:07:22 by Hibernate Tools 3.1.0.beta4 /** * NpcSkillMapping generated by hbm2java */ public class NpcSkillMapping implements java.io.Serializable { // Fields private NpcSkillMappingPK comp_id; private int value; private Skill skill; private Npc npc; // Constructors /** default constructor */ public NpcSkillMapping() { } /** minimal constructor */ public NpcSkillMapping(NpcSkillMappingPK comp_id, int value) { this.comp_id = comp_id; this.value = value; } /** full constructor */ public NpcSkillMapping(NpcSkillMappingPK comp_id, int value, Skill skill, Npc npc) { this.comp_id = comp_id; this.value = value; this.skill = skill; this.npc = npc; } // Property accessors public NpcSkillMappingPK getComp_id() { return this.comp_id; } public void setComp_id(NpcSkillMappingPK comp_id) { this.comp_id = comp_id; } public int getValue() { return this.value; } public void setValue(int value) { this.value = value; } public Skill getSkill() { return this.skill; } public void setSkill(Skill skill) { this.skill = skill; } public Npc getNpc() { return this.npc; } public void setNpc(Npc npc) { this.npc = npc; } }
UTF-8
Java
1,572
java
NpcSkillMapping.java
Java
[]
null
[]
package de.mbws.server.data.db.generated; // Generated 14.04.2006 22:07:22 by Hibernate Tools 3.1.0.beta4 /** * NpcSkillMapping generated by hbm2java */ public class NpcSkillMapping implements java.io.Serializable { // Fields private NpcSkillMappingPK comp_id; private int value; private Skill skill; private Npc npc; // Constructors /** default constructor */ public NpcSkillMapping() { } /** minimal constructor */ public NpcSkillMapping(NpcSkillMappingPK comp_id, int value) { this.comp_id = comp_id; this.value = value; } /** full constructor */ public NpcSkillMapping(NpcSkillMappingPK comp_id, int value, Skill skill, Npc npc) { this.comp_id = comp_id; this.value = value; this.skill = skill; this.npc = npc; } // Property accessors public NpcSkillMappingPK getComp_id() { return this.comp_id; } public void setComp_id(NpcSkillMappingPK comp_id) { this.comp_id = comp_id; } public int getValue() { return this.value; } public void setValue(int value) { this.value = value; } public Skill getSkill() { return this.skill; } public void setSkill(Skill skill) { this.skill = skill; } public Npc getNpc() { return this.npc; } public void setNpc(Npc npc) { this.npc = npc; } }
1,572
0.552799
0.540712
85
16.494118
18.660196
88
false
false
0
0
0
0
0
0
0.282353
false
false
13
66011857765cd6fca9140f60a3295ea83727c73c
30,691,836,303,813
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/neo4j--neo4j/1953f43fa5e925f82fe5873448e4798b7efd3cdd/after/TestApplyTransactions.java
180ec7b845340c4c5226fd0c2adb2a5284e003a6
[]
no_license
fracz/refactor-extractor
https://github.com/fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211000
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.transaction.xaframework; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.kernel.configuration.Config; import org.neo4j.test.TestGraphDatabaseFactory; import org.neo4j.test.impl.EphemeralFileSystemAbstraction; public class TestApplyTransactions { @Test public void testCommittedTransactionReceivedAreForcedToLog() throws Exception { /* GIVEN * Create a tx on a db (as if the master), extract that, apply on dest (as if pullUpdate on slave). * Let slave crash uncleanly. */ EphemeralFileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction(); File baseStoreDir = new File( "base" ); File originStoreDir = new File( baseStoreDir, "origin" ); File destStoreDir = new File( baseStoreDir, "destination" ); GraphDatabaseAPI origin = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fileSystem ) .newImpermanentDatabase( originStoreDir.getPath() ); Transaction tx = origin.beginTx(); origin.createNode(); tx.success(); tx.finish(); XaDataSource originNeoDataSource = origin.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); int latestTxId = (int) originNeoDataSource.getLastCommittedTxId(); InMemoryLogBuffer theTx = new InMemoryLogBuffer(); originNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); GraphDatabaseAPI dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fileSystem ) .newImpermanentDatabase( destStoreDir.getPath() ); XaDataSource destNeoDataSource = dest.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); destNeoDataSource.applyCommittedTransaction( latestTxId, theTx ); origin.shutdown(); EphemeralFileSystemAbstraction snapshot = fileSystem.snapshot(); dest.shutdown(); /* * Open crashed db, try to extract the transaction it reports as latest. It should be there. */ dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot ) .newImpermanentDatabase( destStoreDir.getPath() ); destNeoDataSource = dest.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); latestTxId = (int) destNeoDataSource.getLastCommittedTxId(); theTx = new InMemoryLogBuffer(); long extractedTxId = destNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); assertEquals( latestTxId, extractedTxId ); } }
UTF-8
Java
3,598
java
TestApplyTransactions.java
Java
[]
null
[]
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.transaction.xaframework; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; import org.neo4j.graphdb.Transaction; import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.kernel.configuration.Config; import org.neo4j.test.TestGraphDatabaseFactory; import org.neo4j.test.impl.EphemeralFileSystemAbstraction; public class TestApplyTransactions { @Test public void testCommittedTransactionReceivedAreForcedToLog() throws Exception { /* GIVEN * Create a tx on a db (as if the master), extract that, apply on dest (as if pullUpdate on slave). * Let slave crash uncleanly. */ EphemeralFileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction(); File baseStoreDir = new File( "base" ); File originStoreDir = new File( baseStoreDir, "origin" ); File destStoreDir = new File( baseStoreDir, "destination" ); GraphDatabaseAPI origin = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fileSystem ) .newImpermanentDatabase( originStoreDir.getPath() ); Transaction tx = origin.beginTx(); origin.createNode(); tx.success(); tx.finish(); XaDataSource originNeoDataSource = origin.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); int latestTxId = (int) originNeoDataSource.getLastCommittedTxId(); InMemoryLogBuffer theTx = new InMemoryLogBuffer(); originNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); GraphDatabaseAPI dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fileSystem ) .newImpermanentDatabase( destStoreDir.getPath() ); XaDataSource destNeoDataSource = dest.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); destNeoDataSource.applyCommittedTransaction( latestTxId, theTx ); origin.shutdown(); EphemeralFileSystemAbstraction snapshot = fileSystem.snapshot(); dest.shutdown(); /* * Open crashed db, try to extract the transaction it reports as latest. It should be there. */ dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot ) .newImpermanentDatabase( destStoreDir.getPath() ); destNeoDataSource = dest.getXaDataSourceManager().getXaDataSource( Config.DEFAULT_DATA_SOURCE_NAME ); latestTxId = (int) destNeoDataSource.getLastCommittedTxId(); theTx = new InMemoryLogBuffer(); long extractedTxId = destNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); assertEquals( latestTxId, extractedTxId ); } }
3,598
0.716231
0.711506
77
45.740261
34.011612
122
false
false
0
0
0
0
0
0
0.636364
false
false
13
6b251b788b0053b8e79a9a2d99e81ca052f19ddd
1,803,886,275,894
0262787a016729a3220d11c33f376cdff896fa71
/struts2_day4/src/com/demo/action1/ValueStackAction.java
6d44e14dd40b3806073ec3390f11a6b182dbc5af
[]
no_license
sy235327/sy_code
https://github.com/sy235327/sy_code
a77679cd0139e9f8d2d9cb95f68847ad9648cdea
d3fe6d4be3dbb8ff4deed1a9365e0c45578bc39d
refs/heads/master
2020-03-10T22:40:25.403000
2018-04-17T00:26:43
2018-04-17T00:26:43
129,624,574
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.action1; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * 每个新的请求就会创建一个新的action就会单独创建一个ValueStack对象(值栈),将值栈放入request域对象中 * * 值栈就相当于Struts2框架的数据的中转站,向值栈存入一些数据。从值栈中获取到数据。 * ValueStack 是 struts2 提供一个接口,实现类 OgnlValueStack ---- 值栈对象 (OGNL是从值栈中获取数据的 ) * Action是多例的,有一起请求,创建Action实例,创建一个ActionContext对象,代表的是Action的上下文对象,还会创建一个ValueStack对象。 * 每个Action实例都有一个ValueStack对象 (一个请求 对应 一个ValueStack对象 ) * 在其中保存当前Action 对象和其他相关对象 * Struts 框架把 ValueStack 对象保存在名为 “struts.valueStack” 的请求属性中,request中 (值栈对象 是 request一个属性) * 获取值栈 ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack"); */ public class ValueStackAction extends ActionSupport { //框架在调用action前会创建一个StrutsActionProxy对象,对其初始化把action对象放入值栈中 // private User user = new User("王五","456"); // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } /** * 演示值栈对象的目录结构 * @return * @throws Exception */ @Override public String execute() throws Exception { /* //使用获取值栈对象 //获取request对象 HttpServletRequest request = ServletActionContext.getRequest(); //获取值栈 ValueStack vs = (ValueStack) request.getAttribute("struts.valueStack"); System.out.println(vs);*/ //获取到值栈对象,先获取到ActionContext对象 ValueStack vs = ActionContext.getContext().getValueStack(); System.out.println(vs); //向值栈中的root栈压入值 从栈顶压入栈顶后续的数据向后移动 vs.push("老王"); //判断栈顶值是否为map集合,如果是则将数据存储到map集合中,如果不是创建一个map将数据放入map集合中,压入栈顶,后续的数据向后移动 vs.set("msg","大桥未久"); //栈顶已经有了map集合,直接将值放入map集合中 vs.set("info","苍老师"); return SUCCESS; } /** * 演示从值栈中取值 * @return */ public String save(){ //从ActionContext上下文对象中获取到值栈 ValueStack vs = ActionContext.getContext().getValueStack(); //压栈 // vs.push("大桥未久"); // vs.set("msg","苍老师"); //创建User对象 // User user = new User("大桥未久","123"); //压栈 // vs.push(user); //set压栈 // vs.set("user",user); List<User> userList = new ArrayList<User>(); userList.add(new User("王一","1")); userList.add(new User("王二","2")); userList.add(new User("王3","3")); //将集合压入栈中 // vs.push(userList); //set方法压栈 vs.set("userList",userList); //从context栈中获取值,底层已经封装了request session application attr parameters对象,操作就是map集合 // HttpServletRequest request = ServletActionContext.getRequest(); //自动将request封装到context栈中 // request.setAttribute("msg","波多野结衣"); // ActionContext.getContext().getSession().put("msg","张三"); return SUCCESS; } }
UTF-8
Java
3,933
java
ValueStackAction.java
Java
[ { "context": "action对象放入值栈中\n// private User user = new User(\"王五\",\"456\");\n//\n// public User getUser() {\n// ", "end": 1009, "score": 0.6507412791252136, "start": 1008, "tag": "NAME", "value": "王" }, { "context": "ction对象放入值栈中\n// private User user = new User(\"王五\",\"456\");\n//\n// public User getUser() {\n// ", "end": 1010, "score": 0.6350232362747192, "start": 1009, "tag": "USERNAME", "value": "五" }, { "context": "ArrayList<User>();\n userList.add(new User(\"王一\",\"1\"));\n userList.add(new User(\"王二\",\"2\"));", "end": 2440, "score": 0.9939691424369812, "start": 2438, "tag": "NAME", "value": "王一" }, { "context": "w User(\"王一\",\"1\"));\n userList.add(new User(\"王二\",\"2\"));\n userList.add(new User(\"王3\",\"3\"));", "end": 2482, "score": 0.9966560006141663, "start": 2480, "tag": "NAME", "value": "王二" }, { "context": "w User(\"王二\",\"2\"));\n userList.add(new User(\"王3\",\"3\"));\n\n //将集合压入栈中\n// vs.push(user", "end": 2524, "score": 0.9920960068702698, "start": 2522, "tag": "NAME", "value": "王3" } ]
null
[]
package com.demo.action1; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * 每个新的请求就会创建一个新的action就会单独创建一个ValueStack对象(值栈),将值栈放入request域对象中 * * 值栈就相当于Struts2框架的数据的中转站,向值栈存入一些数据。从值栈中获取到数据。 * ValueStack 是 struts2 提供一个接口,实现类 OgnlValueStack ---- 值栈对象 (OGNL是从值栈中获取数据的 ) * Action是多例的,有一起请求,创建Action实例,创建一个ActionContext对象,代表的是Action的上下文对象,还会创建一个ValueStack对象。 * 每个Action实例都有一个ValueStack对象 (一个请求 对应 一个ValueStack对象 ) * 在其中保存当前Action 对象和其他相关对象 * Struts 框架把 ValueStack 对象保存在名为 “struts.valueStack” 的请求属性中,request中 (值栈对象 是 request一个属性) * 获取值栈 ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack"); */ public class ValueStackAction extends ActionSupport { //框架在调用action前会创建一个StrutsActionProxy对象,对其初始化把action对象放入值栈中 // private User user = new User("王五","456"); // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } /** * 演示值栈对象的目录结构 * @return * @throws Exception */ @Override public String execute() throws Exception { /* //使用获取值栈对象 //获取request对象 HttpServletRequest request = ServletActionContext.getRequest(); //获取值栈 ValueStack vs = (ValueStack) request.getAttribute("struts.valueStack"); System.out.println(vs);*/ //获取到值栈对象,先获取到ActionContext对象 ValueStack vs = ActionContext.getContext().getValueStack(); System.out.println(vs); //向值栈中的root栈压入值 从栈顶压入栈顶后续的数据向后移动 vs.push("老王"); //判断栈顶值是否为map集合,如果是则将数据存储到map集合中,如果不是创建一个map将数据放入map集合中,压入栈顶,后续的数据向后移动 vs.set("msg","大桥未久"); //栈顶已经有了map集合,直接将值放入map集合中 vs.set("info","苍老师"); return SUCCESS; } /** * 演示从值栈中取值 * @return */ public String save(){ //从ActionContext上下文对象中获取到值栈 ValueStack vs = ActionContext.getContext().getValueStack(); //压栈 // vs.push("大桥未久"); // vs.set("msg","苍老师"); //创建User对象 // User user = new User("大桥未久","123"); //压栈 // vs.push(user); //set压栈 // vs.set("user",user); List<User> userList = new ArrayList<User>(); userList.add(new User("王一","1")); userList.add(new User("王二","2")); userList.add(new User("王3","3")); //将集合压入栈中 // vs.push(userList); //set方法压栈 vs.set("userList",userList); //从context栈中获取值,底层已经封装了request session application attr parameters对象,操作就是map集合 // HttpServletRequest request = ServletActionContext.getRequest(); //自动将request封装到context栈中 // request.setAttribute("msg","波多野结衣"); // ActionContext.getContext().getSession().put("msg","张三"); return SUCCESS; } }
3,933
0.64854
0.642833
101
28.49505
24.264069
89
false
false
0
0
0
0
0
0
0.594059
false
false
13
1d62c93e9dfee753d436b38e1182d8545ec906f5
22,771,916,613,415
d76909f6bbad53c6d804ec348e4c22e57cffbe63
/src/tree/LowestCommonAncestorOfABinaryTree_236/Solution.java
cb6da51b8e5ea3183a8a444372a2575ac75ebbf7
[]
no_license
k1ema/LeetCodeProblems
https://github.com/k1ema/LeetCodeProblems
60b6e5c4f107c5d68286f42e4ade3629d8919c50
cc077faad3ce3e1f8b7a57bb6df52f0d44ba8eb9
refs/heads/master
2022-11-09T01:50:35.269000
2022-10-22T10:58:04
2022-10-22T10:58:04
186,883,840
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tree.LowestCommonAncestorOfABinaryTree_236; import tree.utils.TreeNode; import java.util.LinkedList; import java.util.Queue; /** * 236. Lowest Common Ancestor of a Binary Tree * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ * * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. * * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined * between two nodes p and q as the lowest node in T that has both p and q as descendants * (where we allow a node to be a descendant of itself).” * * Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] * * Example 1: * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 * Output: 3 * Explanation: The LCA of nodes 5 and 1 is 3. * * Example 2: * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 * Output: 5 * Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself * according to the LCA definition. * * Note: * All of the nodes' values will be unique. * p and q are different and both values will exist in the binary tree. */ public class Solution { // tc O(n), sc O(n) // 5 ms, faster than 100.00%; 35.9 MB, less than 5.55% // https://discuss.leetcode.com/topic/18561/4-lines-c-java-python-ruby TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root.equals(p) || root.equals(q)) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : (right == null ? left : root); } // tc O(n), sc O(n) // 5 ms, faster than 100.00%; 35.2 MB, less than 5.55% private TreeNode ans; TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { if (p.val == q.val) return p; ans = null; dfs(root, p.val, q.val); return ans; } private boolean dfs(TreeNode root, int p, int q) { if (root == null) return false; int mid = root.val == p || root.val == q ? 1 : 0; int left = dfs(root.left, p, q) ? 1 : 0; int right = dfs(root.right, p, q) ? 1 : 0; if (left + right + mid >= 2) { ans = root; } return left + right + mid >= 1; } // my solution // tc O(n), sc O(n) // 6 ms, faster than 71.20%; 35.6 MB, less than 5.55% TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) { if (p.val == q.val) return p; Queue<TreeNode> trackP = new LinkedList<>(); Queue<TreeNode> trackQ = new LinkedList<>(); dfs1(root, trackP, p.val); dfs1(root, trackQ, q.val); while (!trackP.isEmpty()) { TreeNode node = trackP.poll(); if (trackQ.contains(node)) return node; } return root; } private boolean dfs1(TreeNode root, Queue<TreeNode> track, int val) { if (root == null) return false; if (root.val == val) { track.add(root); return true; } boolean b1 = dfs1(root.left, track, val); boolean b2 = dfs1(root.right, track, val); if (b1 || b2) track.add(root); return b1 || b2; } }
UTF-8
Java
3,323
java
Solution.java
Java
[]
null
[]
package tree.LowestCommonAncestorOfABinaryTree_236; import tree.utils.TreeNode; import java.util.LinkedList; import java.util.Queue; /** * 236. Lowest Common Ancestor of a Binary Tree * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ * * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. * * According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined * between two nodes p and q as the lowest node in T that has both p and q as descendants * (where we allow a node to be a descendant of itself).” * * Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] * * Example 1: * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 * Output: 3 * Explanation: The LCA of nodes 5 and 1 is 3. * * Example 2: * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 * Output: 5 * Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself * according to the LCA definition. * * Note: * All of the nodes' values will be unique. * p and q are different and both values will exist in the binary tree. */ public class Solution { // tc O(n), sc O(n) // 5 ms, faster than 100.00%; 35.9 MB, less than 5.55% // https://discuss.leetcode.com/topic/18561/4-lines-c-java-python-ruby TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root.equals(p) || root.equals(q)) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); return left == null ? right : (right == null ? left : root); } // tc O(n), sc O(n) // 5 ms, faster than 100.00%; 35.2 MB, less than 5.55% private TreeNode ans; TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) { if (p.val == q.val) return p; ans = null; dfs(root, p.val, q.val); return ans; } private boolean dfs(TreeNode root, int p, int q) { if (root == null) return false; int mid = root.val == p || root.val == q ? 1 : 0; int left = dfs(root.left, p, q) ? 1 : 0; int right = dfs(root.right, p, q) ? 1 : 0; if (left + right + mid >= 2) { ans = root; } return left + right + mid >= 1; } // my solution // tc O(n), sc O(n) // 6 ms, faster than 71.20%; 35.6 MB, less than 5.55% TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) { if (p.val == q.val) return p; Queue<TreeNode> trackP = new LinkedList<>(); Queue<TreeNode> trackQ = new LinkedList<>(); dfs1(root, trackP, p.val); dfs1(root, trackQ, q.val); while (!trackP.isEmpty()) { TreeNode node = trackP.poll(); if (trackQ.contains(node)) return node; } return root; } private boolean dfs1(TreeNode root, Queue<TreeNode> track, int val) { if (root == null) return false; if (root.val == val) { track.add(root); return true; } boolean b1 = dfs1(root.left, track, val); boolean b2 = dfs1(root.right, track, val); if (b1 || b2) track.add(root); return b1 || b2; } }
3,323
0.597469
0.564628
94
34.30851
26.241524
93
false
false
0
0
0
0
0
0
1.276596
false
false
13
e7e35229afdb9fcea65a2446302b61cf061bef75
30,227,979,843,048
d98bc0a626023dbf6a6ee56e4e59fec364136e36
/Java/ch05/src/Quiz05_05.java
9de5d9309a791f7d5959871b0b095619ac646699
[]
no_license
HanTaeYong/kosmo41_HanTaeYong
https://github.com/HanTaeYong/kosmo41_HanTaeYong
a743ac1756a785ac175adfdb32207319d4eb2c54
36ff9e20f97796824689ade72d550c9155419cb3
refs/heads/master
2020-03-21T04:42:36.148000
2018-11-20T00:40:33
2018-11-20T00:40:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Quiz05_05 { public static void main(String args[]) { for(int i=1; i<10; i++) { if(i%2==0) { for(int j=1; j<=i; j++) { System.out.println(i+" x "+j+" = "+(i*j)); } System.out.println(); } } /* int i=1, j=1; while(i<10) { j=1; if(i%2==0) { while(j<=i) { System.out.println(i+" x "+j+" = "+(i*j)); j++; } System.out.println(); } i++; } */ } }
UTF-8
Java
430
java
Quiz05_05.java
Java
[]
null
[]
public class Quiz05_05 { public static void main(String args[]) { for(int i=1; i<10; i++) { if(i%2==0) { for(int j=1; j<=i; j++) { System.out.println(i+" x "+j+" = "+(i*j)); } System.out.println(); } } /* int i=1, j=1; while(i<10) { j=1; if(i%2==0) { while(j<=i) { System.out.println(i+" x "+j+" = "+(i*j)); j++; } System.out.println(); } i++; } */ } }
430
0.423256
0.383721
27
14.888889
13.633655
47
false
false
0
0
0
0
0
0
3.259259
false
false
13
701aa41bbd5479b687a44b7542580bd9bad6fda3
22,101,901,716,539
86518661b39b9f308e76a7be31bf64f0deed8478
/src/main/java/com/ex/musicdb/model/view/AlbumCardViewModel.java
b0a25f2742d34160a277760c825391584b56cc4e
[]
no_license
KaloyanBratovanov/MusicDB
https://github.com/KaloyanBratovanov/MusicDB
b6a25e980c323b7803244a1a033d323efde2c66b
ce2c85b758b9c8d76cb438f7dfb004be2e6a9e2b
refs/heads/main
2023-04-04T06:38:09.246000
2021-04-11T10:16:46
2021-04-11T10:16:46
349,534,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ex.musicdb.model.view; import com.ex.musicdb.model.entities.enums.Genre; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; public class AlbumCardViewModel { private Long id; private String name; private String imageUrl; private Integer copies; private BigDecimal price; private LocalDate releaseDate; private Genre genre; private String artist; public AlbumCardViewModel() { } public Long getId() { return id; } public AlbumCardViewModel setId(Long id) { this.id = id; return this; } public String getName() { return name; } public AlbumCardViewModel setName(String name) { this.name = name; return this; } public String getImageUrl() { return imageUrl; } public AlbumCardViewModel setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public Integer getCopies() { return copies; } public AlbumCardViewModel setCopies(Integer copies) { this.copies = copies; return this; } public BigDecimal getPrice() { return price; } public AlbumCardViewModel setPrice(BigDecimal price) { this.price = price; return this; } public LocalDate getReleaseDate() { return releaseDate; } public AlbumCardViewModel setReleaseDate(LocalDate releaseDate) { this.releaseDate = releaseDate; return this; } public Genre getGenre() { return genre; } public AlbumCardViewModel setGenre(Genre genre) { this.genre = genre; return this; } public String getArtist() { return artist; } public AlbumCardViewModel setArtist(String artist) { this.artist = artist; return this; } }
UTF-8
Java
1,890
java
AlbumCardViewModel.java
Java
[]
null
[]
package com.ex.musicdb.model.view; import com.ex.musicdb.model.entities.enums.Genre; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; public class AlbumCardViewModel { private Long id; private String name; private String imageUrl; private Integer copies; private BigDecimal price; private LocalDate releaseDate; private Genre genre; private String artist; public AlbumCardViewModel() { } public Long getId() { return id; } public AlbumCardViewModel setId(Long id) { this.id = id; return this; } public String getName() { return name; } public AlbumCardViewModel setName(String name) { this.name = name; return this; } public String getImageUrl() { return imageUrl; } public AlbumCardViewModel setImageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; } public Integer getCopies() { return copies; } public AlbumCardViewModel setCopies(Integer copies) { this.copies = copies; return this; } public BigDecimal getPrice() { return price; } public AlbumCardViewModel setPrice(BigDecimal price) { this.price = price; return this; } public LocalDate getReleaseDate() { return releaseDate; } public AlbumCardViewModel setReleaseDate(LocalDate releaseDate) { this.releaseDate = releaseDate; return this; } public Genre getGenre() { return genre; } public AlbumCardViewModel setGenre(Genre genre) { this.genre = genre; return this; } public String getArtist() { return artist; } public AlbumCardViewModel setArtist(String artist) { this.artist = artist; return this; } }
1,890
0.625397
0.625397
95
18.894737
17.11046
69
false
false
0
0
0
0
0
0
0.389474
false
false
13
1159a723571ef4a182321555e014c99851e57f54
33,724,083,217,908
b3dc6887d3611c2c87d077ffc4dca9071a328537
/src/kingery/game/gfx/Animation.java
51a8fc8dc1b4078ee4747ff6ac4a23711e57f9c3
[]
no_license
SeriousSirToad/Tree2d
https://github.com/SeriousSirToad/Tree2d
cbc51804e6c3fd1f91ad6fc0108b3f5c140e3e9b
a681a460ed418c91aa55038e732eccb3708344a9
refs/heads/master
2021-07-13T11:12:53.434000
2020-05-26T17:54:38
2020-05-26T17:54:38
146,236,161
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kingery.game.gfx; import java.awt.image.BufferedImage; public class Animation { public BufferedImage[] frames; public BufferedImage currentFrame; public int frameSkip; private int frameIndex; boolean skipFirst = false; public Animation(boolean skipFirst, int frameSkip, BufferedImage[] images) { this.frameSkip = frameSkip; this.skipFirst = skipFirst; frames = images; currentFrame = images[0]; } long lastTime = System.currentTimeMillis(); public BufferedImage animate() { long now = System.currentTimeMillis(); if ((now - lastTime) / 16 >= frameSkip) { frameIndex++; if (frameIndex >= frames.length) { if (skipFirst) frameIndex = 1; else frameIndex = 0; } currentFrame = frames[frameIndex]; lastTime = now; } return frames[frameIndex]; } public void reset() { frameIndex = 0; currentFrame = frames[0]; } }
UTF-8
Java
938
java
Animation.java
Java
[]
null
[]
package kingery.game.gfx; import java.awt.image.BufferedImage; public class Animation { public BufferedImage[] frames; public BufferedImage currentFrame; public int frameSkip; private int frameIndex; boolean skipFirst = false; public Animation(boolean skipFirst, int frameSkip, BufferedImage[] images) { this.frameSkip = frameSkip; this.skipFirst = skipFirst; frames = images; currentFrame = images[0]; } long lastTime = System.currentTimeMillis(); public BufferedImage animate() { long now = System.currentTimeMillis(); if ((now - lastTime) / 16 >= frameSkip) { frameIndex++; if (frameIndex >= frames.length) { if (skipFirst) frameIndex = 1; else frameIndex = 0; } currentFrame = frames[frameIndex]; lastTime = now; } return frames[frameIndex]; } public void reset() { frameIndex = 0; currentFrame = frames[0]; } }
938
0.656716
0.649254
46
18.391304
16.733822
77
false
false
0
0
0
0
0
0
1.913043
false
false
13
fc5ddf797311ff60e5600ba7905bf8d11145aa80
807,453,874,936
e708a549c91d60e8ec921811e093e666a9900585
/src/test/java/com/dywl/iot/testCase/LoginTest2.java
f4a2af5c49165fa927d402a668a0db5078ead47a
[]
no_license
maidou1152/moon
https://github.com/maidou1152/moon
9d7fd2bbdb073a05db9624dad7ecc5b94fb36dde
eed9b09e8821df706961f62074749b3307bcfd0e
refs/heads/master
2022-07-06T17:25:07.830000
2020-05-13T02:24:51
2020-05-13T02:24:51
255,784,672
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dywl.iot.testCase; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.dywl.iot.base.BaseTest; public class LoginTest2 extends BaseTest { @Test(enabled=false,dataProvider="getDatas") public void f1(String name,String password,String expectedTip,String css) { driver.manage().window().maximize(); String url="http://183.129.159.166:10056/login"; driver.get(url); WaitTime(); driver.findElement(By.id("name")).sendKeys(name); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys(password); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style=+'"+css+"']")).getText(); System.out.println(actual); Assert.assertEquals(actual,expectedTip); } @Test public void f3() { driver.manage().window().maximize(); String url="http://183.129.159.166:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("123"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(244, 68, 68);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"用户名或密码错误"); } @Test public void f4() { driver.manage().window().maximize(); String url="http://183.129.159.166:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys(""); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(0, 204, 255);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"密码不能为空!"); } @Test public void f5() { driver.manage().window().maximize(); String url="http://183.129.159.166:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys(""); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("12345"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(0, 204, 255);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"用户名不能为空!"); } @Test public void f2() { driver.manage().window().maximize(); String url="http://183.129.159.166:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("123456"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(62, 231, 70);")).getText(); System.out.println(actual); Assert.assertEquals(actual, "登录成功"); } @DataProvider public Object[][] getDatas() { Object[][] datas={{"admin","123","用户名或密码错误","color: rgb(244, 68, 68);"}, // {"admin","","密码不能为空!","color: rgb(0, 204, 255);"}, // {"","123456","用户名不能为空!","color: rgb(0, 204, 255);"}, // {"admin","1234","用户名或密码错误!","color: rgb(244, 68, 68);"}, // {"admin","123456","登录成功","color: rgb(62, 231, 70);"} }; return datas; } }
UTF-8
Java
4,557
java
LoginTest2.java
Java
[ { "context": "nage().window().maximize();\r\n\t\tString url=\"http://183.129.159.166:10056/login\";\r\n\t\tdriver.get(url);\r\n\t\tWaitTime();\r", "end": 553, "score": 0.9988755583763123, "start": 538, "tag": "IP_ADDRESS", "value": "183.129.159.166" }, { "context": "nage().window().maximize();\r\n\t\tString url=\"http://183.129.159.166:10056/login\";\r\n\t\tdriver.get(url);\r\n\t\tdriver.findE", "end": 1271, "score": 0.9967343211174011, "start": 1256, "tag": "IP_ADDRESS", "value": "183.129.159.166" }, { "context": ");\r\n\t\tdriver.findElement(By.id(\"name\")).sendKeys(\"admin\");\r\n\t\tWebElement inputPassword=driver.findElement", "end": 1358, "score": 0.8555359244346619, "start": 1353, "tag": "USERNAME", "value": "admin" }, { "context": "utPassword).perform();\r\n\t\tinputPassword.sendKeys(\"123\");\r\n\t\tWebElement loginButton=driver.findElement(B", "end": 1522, "score": 0.9993484616279602, "start": 1519, "tag": "PASSWORD", "value": "123" }, { "context": "nage().window().maximize();\r\n\t\tString url=\"http://183.129.159.166:10056/login\";\r\n\t\tdriver.get(url);\r\n\t\tdriver.findE", "end": 1986, "score": 0.9436224102973938, "start": 1971, "tag": "IP_ADDRESS", "value": "183.129.159.166" }, { "context": ");\r\n\t\tdriver.findElement(By.id(\"name\")).sendKeys(\"admin\");\r\n\t\tWebElement inputPassword=driver.findElement", "end": 2073, "score": 0.881687581539154, "start": 2068, "tag": "USERNAME", "value": "admin" }, { "context": "nage().window().maximize();\r\n\t\tString url=\"http://183.129.159.166:10056/login\";\r\n\t\tdriver.get(url);\r\n\t\tdriver.findE", "end": 2697, "score": 0.9947218298912048, "start": 2682, "tag": "IP_ADDRESS", "value": "183.129.159.166" }, { "context": "utPassword).perform();\r\n\t\tinputPassword.sendKeys(\"12345\");\r\n\t\tWebElement loginButton=driver.findElement(B", "end": 2945, "score": 0.9994179606437683, "start": 2940, "tag": "PASSWORD", "value": "12345" }, { "context": "nage().window().maximize();\r\n\t\tString url=\"http://183.129.159.166:10056/login\";\r\n\t\tdriver.get(url);\r\n\t\tdriver.findE", "end": 3409, "score": 0.9993445873260498, "start": 3394, "tag": "IP_ADDRESS", "value": "183.129.159.166" }, { "context": ");\r\n\t\tdriver.findElement(By.id(\"name\")).sendKeys(\"admin\");\r\n\t\tWebElement inputPassword=driver.findElement", "end": 3496, "score": 0.9880713224411011, "start": 3491, "tag": "USERNAME", "value": "admin" }, { "context": "utPassword).perform();\r\n\t\tinputPassword.sendKeys(\"123456\");\r\n\t\tWebElement loginButton=driver.findElement(B", "end": 3663, "score": 0.9994459748268127, "start": 3657, "tag": "PASSWORD", "value": "123456" }, { "context": "lor: rgb(244, 68, 68);\"},\r\n\t\t\t\t//\t\t {\"admin\",\"\",\"密码不能为空!\",\"color: rgb(0, 204, 255);\"},\r\n\t\t\t\t//\t\t {\"\",\"123", "end": 4170, "score": 0.808898389339447, "start": 4164, "tag": "PASSWORD", "value": "密码不能为空" } ]
null
[]
package com.dywl.iot.testCase; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.dywl.iot.base.BaseTest; public class LoginTest2 extends BaseTest { @Test(enabled=false,dataProvider="getDatas") public void f1(String name,String password,String expectedTip,String css) { driver.manage().window().maximize(); String url="http://192.168.127.12:10056/login"; driver.get(url); WaitTime(); driver.findElement(By.id("name")).sendKeys(name); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys(password); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style=+'"+css+"']")).getText(); System.out.println(actual); Assert.assertEquals(actual,expectedTip); } @Test public void f3() { driver.manage().window().maximize(); String url="http://192.168.127.12:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("123"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(244, 68, 68);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"用户名或密码错误"); } @Test public void f4() { driver.manage().window().maximize(); String url="http://192.168.127.12:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys(""); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(0, 204, 255);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"密码不能为空!"); } @Test public void f5() { driver.manage().window().maximize(); String url="http://192.168.127.12:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys(""); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("<PASSWORD>"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(0, 204, 255);']")).getText(); System.out.println(actual); Assert.assertEquals(actual,"用户名不能为空!"); } @Test public void f2() { driver.manage().window().maximize(); String url="http://192.168.127.12:10056/login"; driver.get(url); driver.findElement(By.id("name")).sendKeys("admin"); WebElement inputPassword=driver.findElement(By.id("password")); new Actions(driver).moveToElement(inputPassword).perform(); inputPassword.sendKeys("<PASSWORD>"); WebElement loginButton=driver.findElement(By.tagName("button")); new Actions(driver).moveToElement(loginButton).perform(); loginButton.click(); WaitTime(); String actual=driver.findElement(By.cssSelector("span[style='color: rgb(62, 231, 70);")).getText(); System.out.println(actual); Assert.assertEquals(actual, "登录成功"); } @DataProvider public Object[][] getDatas() { Object[][] datas={{"admin","123","用户名或密码错误","color: rgb(244, 68, 68);"}, // {"admin","","<PASSWORD>!","color: rgb(0, 204, 255);"}, // {"","123456","用户名不能为空!","color: rgb(0, 204, 255);"}, // {"admin","1234","用户名或密码错误!","color: rgb(244, 68, 68);"}, // {"admin","123456","登录成功","color: rgb(62, 231, 70);"} }; return datas; } }
4,553
0.69262
0.650418
116
36.215519
25.746378
103
false
false
0
0
0
0
0
0
2.896552
false
false
13
1cc13cb3104b8c815c85903679cbaadae6d16af0
23,433,341,605,330
1cb69b1f5e528c276a18b4e2e1df4f2f7980eb9f
/src/main/java/org/asuki/springboot/controller/api/OpenIdConnectResource.java
56dea3b006d0eb0490dd6cb4497a71762756bbcd
[]
no_license
AsukiLiu/Spring-Boot
https://github.com/AsukiLiu/Spring-Boot
2a96b7855b0091ce7b17b4b067dc1ee466aef49b
df1309f75737b13f363ce928ebd5091134911e45
refs/heads/master
2021-01-13T00:55:51.257000
2015-11-29T08:58:57
2015-11-29T08:58:57
44,817,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.asuki.springboot.controller.api; import com.nimbusds.oauth2.sdk.*; import com.nimbusds.oauth2.sdk.id.ClientID; import com.nimbusds.oauth2.sdk.id.State; import com.nimbusds.openid.connect.sdk.AuthenticationRequest; import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.util.Map; import static org.springframework.http.HttpStatus.FOUND; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController @RequestMapping("api") public class OpenIdConnectResource { private static final Logger log = LoggerFactory.getLogger(OpenIdConnectResource.class); @RequestMapping(value = "login", method = GET) public void redirectCode(@RequestParam Map<String, String> queryParameters, HttpServletResponse resp) throws ParseException, SerializeException, IOException { log.info(queryParameters.toString()); AuthenticationSuccessResponse authResponse = createAuthResponse(queryParameters); resp.setStatus(FOUND.value()); resp.sendRedirect(authResponse.toURI().toString()); } private AuthenticationSuccessResponse createAuthResponse(Map<String, String> queryParameters) throws ParseException { AuthenticationRequest request = AuthenticationRequest.parse(queryParameters); // Required to look up the client in database ClientID clientID = request.getClientID(); // Required to be registered in database URI callbackUri = request.getRedirectionURI(); ResponseType responseType = request.getResponseType(); State state = request.getState(); Scope scope = request.getScope(); AuthorizationCode code = new AuthorizationCode(); return new AuthenticationSuccessResponse(callbackUri, code, null, null, state); } }
UTF-8
Java
2,172
java
OpenIdConnectResource.java
Java
[]
null
[]
package org.asuki.springboot.controller.api; import com.nimbusds.oauth2.sdk.*; import com.nimbusds.oauth2.sdk.id.ClientID; import com.nimbusds.oauth2.sdk.id.State; import com.nimbusds.openid.connect.sdk.AuthenticationRequest; import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URI; import java.util.Map; import static org.springframework.http.HttpStatus.FOUND; import static org.springframework.web.bind.annotation.RequestMethod.GET; @RestController @RequestMapping("api") public class OpenIdConnectResource { private static final Logger log = LoggerFactory.getLogger(OpenIdConnectResource.class); @RequestMapping(value = "login", method = GET) public void redirectCode(@RequestParam Map<String, String> queryParameters, HttpServletResponse resp) throws ParseException, SerializeException, IOException { log.info(queryParameters.toString()); AuthenticationSuccessResponse authResponse = createAuthResponse(queryParameters); resp.setStatus(FOUND.value()); resp.sendRedirect(authResponse.toURI().toString()); } private AuthenticationSuccessResponse createAuthResponse(Map<String, String> queryParameters) throws ParseException { AuthenticationRequest request = AuthenticationRequest.parse(queryParameters); // Required to look up the client in database ClientID clientID = request.getClientID(); // Required to be registered in database URI callbackUri = request.getRedirectionURI(); ResponseType responseType = request.getResponseType(); State state = request.getState(); Scope scope = request.getScope(); AuthorizationCode code = new AuthorizationCode(); return new AuthenticationSuccessResponse(callbackUri, code, null, null, state); } }
2,172
0.763352
0.76105
62
34.032257
30.519146
105
false
false
0
0
0
0
0
0
0.645161
false
false
13
3e7ca39e2511a1004082159979504e18de26e72a
2,482,491,149,774
e78c4cd51b20cc0124f1b9fc2b52c017c69182a4
/msip-bhu-business-impl/msip_bhu_business_redis_impl/src/main/java/com/bhu/vas/business/bucache/redis/serviceimpl/devices/WifiDeviceHandsetAliasService.java
e1a178b0963008943643192d1bf4ace0c5deb1b1
[]
no_license
Major-Lee/my-first-company
https://github.com/Major-Lee/my-first-company
b4e20181b55557c2b71de0aa81f4b706614c1565
7cbe95891d3da0df35a9cf5b3eb9a962da9b101d
refs/heads/master
2020-05-20T23:02:30.797000
2015-10-30T07:08:26
2015-10-30T07:08:26
84,528,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bhu.vas.business.bucache.redis.serviceimpl.devices; import com.bhu.vas.business.bucache.redis.serviceimpl.BusinessKeyDefine; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.RedisKeyEnum; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.RedisPoolManager; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.impl.AbstractRelationHashCache; import com.smartwork.msip.cores.helper.StringHelper; import redis.clients.jedis.JedisPool; /** * 获取用户设备终端别名 */ public class WifiDeviceHandsetAliasService extends AbstractRelationHashCache { private static class ServiceHolder{ private static WifiDeviceHandsetAliasService instance =new WifiDeviceHandsetAliasService(); } /** * 获取工厂单例 * @return */ public static WifiDeviceHandsetAliasService getInstance() { return ServiceHolder.instance; } private WifiDeviceHandsetAliasService() { } @Override public JedisPool getRedisPool() { return RedisPoolManager.getInstance().getPool(RedisKeyEnum.PRESENT); } @Override public String getRedisKey() { return null; } @Override public String getName() { return WifiDeviceHandsetAliasService.class.getName(); } private static String generateKey(String wifiId){ StringBuilder sb = new StringBuilder(BusinessKeyDefine.UserWifiDeviceHandset.Nick); sb.append(StringHelper.POINT_CHAR_GAP).append(wifiId); return sb.toString(); } public Long hsetHandsetAlias(int uid, String handsetMac, String alias) { return this.hset(generateKey(String.valueOf(uid)), handsetMac, alias); } public Long hdelHandsetAlias(int uid, String handsetMac) { return this.hdel(generateKey(String.valueOf(uid)), handsetMac); } public String hgetHandsetAlias(int uid, String handsetMac) { return this.hget(generateKey(String.valueOf(uid)), handsetMac); } public boolean hexistsHandsetAlias(int uid, String handsetMac) { return this.hexists(generateKey(String.valueOf(uid)), handsetMac); } }
UTF-8
Java
2,144
java
WifiDeviceHandsetAliasService.java
Java
[]
null
[]
package com.bhu.vas.business.bucache.redis.serviceimpl.devices; import com.bhu.vas.business.bucache.redis.serviceimpl.BusinessKeyDefine; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.RedisKeyEnum; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.RedisPoolManager; import com.smartwork.msip.cores.cache.relationcache.impl.jedis.impl.AbstractRelationHashCache; import com.smartwork.msip.cores.helper.StringHelper; import redis.clients.jedis.JedisPool; /** * 获取用户设备终端别名 */ public class WifiDeviceHandsetAliasService extends AbstractRelationHashCache { private static class ServiceHolder{ private static WifiDeviceHandsetAliasService instance =new WifiDeviceHandsetAliasService(); } /** * 获取工厂单例 * @return */ public static WifiDeviceHandsetAliasService getInstance() { return ServiceHolder.instance; } private WifiDeviceHandsetAliasService() { } @Override public JedisPool getRedisPool() { return RedisPoolManager.getInstance().getPool(RedisKeyEnum.PRESENT); } @Override public String getRedisKey() { return null; } @Override public String getName() { return WifiDeviceHandsetAliasService.class.getName(); } private static String generateKey(String wifiId){ StringBuilder sb = new StringBuilder(BusinessKeyDefine.UserWifiDeviceHandset.Nick); sb.append(StringHelper.POINT_CHAR_GAP).append(wifiId); return sb.toString(); } public Long hsetHandsetAlias(int uid, String handsetMac, String alias) { return this.hset(generateKey(String.valueOf(uid)), handsetMac, alias); } public Long hdelHandsetAlias(int uid, String handsetMac) { return this.hdel(generateKey(String.valueOf(uid)), handsetMac); } public String hgetHandsetAlias(int uid, String handsetMac) { return this.hget(generateKey(String.valueOf(uid)), handsetMac); } public boolean hexistsHandsetAlias(int uid, String handsetMac) { return this.hexists(generateKey(String.valueOf(uid)), handsetMac); } }
2,144
0.730114
0.730114
66
31
31.632837
99
false
false
0
0
0
0
0
0
0.439394
false
false
13
7b7452c3b88dc26b846b8f50be682b6febb8ba3e
31,860,067,418,304
c5c7eff45184d241f7e5b6e85863f64c0e78a493
/src/metier/reservDao.java
ee511c9182db2a580b43fd866bfdf0ebc6d80b68
[]
no_license
aymanP/Gestion-biblioteque
https://github.com/aymanP/Gestion-biblioteque
6158f5dee205ecb573620f62177134fe6c4d6ea6
6daa69601a6031a12e42cdec9e52c62053ee796a
refs/heads/master
2021-01-15T17:09:48.779000
2017-08-08T20:37:05
2017-08-08T20:37:05
99,733,767
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package metier; import java.util.List; import metier.entities.Reservation; public interface reservDao { public void addReserv(Reservation user); public void updateReserv(Reservation user); public List<Reservation> ListReserv(); public Reservation getReserv(int Id); public void deleteReserv(int id); }
UTF-8
Java
311
java
reservDao.java
Java
[]
null
[]
package metier; import java.util.List; import metier.entities.Reservation; public interface reservDao { public void addReserv(Reservation user); public void updateReserv(Reservation user); public List<Reservation> ListReserv(); public Reservation getReserv(int Id); public void deleteReserv(int id); }
311
0.790997
0.790997
14
21.214285
17.230284
44
false
false
0
0
0
0
0
0
0.928571
false
false
13
7641e627ac7abf54a6da6fe4041ab60c64a80b7a
27,676,769,271,753
aedb022e3f23a93cd48cedb58af0599132534f3d
/src/test/java/com/looveh/blog_web/BlogWebApplicationTests.java
18331f7430f4cf1d4a1209db60b984c937b2f121
[]
no_license
MrRohwei/blog_web
https://github.com/MrRohwei/blog_web
456b53e3c57d6c538cdde8074d7bea070b5b0a72
ca6ceaa7f3a278a06b397ffd7f653336cc02146f
refs/heads/master
2022-07-01T12:11:22.268000
2019-06-19T07:51:29
2019-06-19T07:51:29
187,319,244
0
0
null
false
2022-06-17T02:12:15
2019-05-18T05:42:14
2019-06-19T07:51:40
2022-06-17T02:12:14
7,120
0
0
3
JavaScript
false
false
//package com.looveh.blog_web; // //import com.looveh.blog_web.service.BlogNavigationService; //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.jdbc.core.JdbcTemplate; //import org.springframework.test.context.junit4.SpringRunner; // //@RunWith(SpringRunner.class) //@SpringBootTest //public class BlogWebApplicationTests { // // @Autowired // JdbcTemplate jdbcTemplate; // // @Autowired // BlogNavigationService blogNavigationService; // // @Test // public void contextLoads() { // //// String sql = "select * from t_user"; //// List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); //// //// System.out.println(maps); // } // // @Test // public void testNavigation(){ // BlogNavigation navigation = new BlogNavigation(); // navigation.setTitle("首页"); // navigation.setOrderNum(1); // navigation.setStatus(0); // blogNavigationService.addNavigation(navigation); // } // //}
UTF-8
Java
1,143
java
BlogWebApplicationTests.java
Java
[]
null
[]
//package com.looveh.blog_web; // //import com.looveh.blog_web.service.BlogNavigationService; //import org.junit.Test; //import org.junit.runner.RunWith; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.boot.test.context.SpringBootTest; //import org.springframework.jdbc.core.JdbcTemplate; //import org.springframework.test.context.junit4.SpringRunner; // //@RunWith(SpringRunner.class) //@SpringBootTest //public class BlogWebApplicationTests { // // @Autowired // JdbcTemplate jdbcTemplate; // // @Autowired // BlogNavigationService blogNavigationService; // // @Test // public void contextLoads() { // //// String sql = "select * from t_user"; //// List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); //// //// System.out.println(maps); // } // // @Test // public void testNavigation(){ // BlogNavigation navigation = new BlogNavigation(); // navigation.setTitle("首页"); // navigation.setOrderNum(1); // navigation.setStatus(0); // blogNavigationService.addNavigation(navigation); // } // //}
1,143
0.679543
0.67691
39
28.205128
22.199768
76
false
false
0
0
0
0
0
0
0.487179
false
false
13
01cc5925de7d30b9d5132f925e45ffb554aebe51
27,676,769,269,555
cb91bcb98beb602898414def0cecb516961627e6
/src/main/java/com/ch/sms/simulator/sms/cmpp/CMPPConfigure.java
ea4675191e91e46862c24a0da9cb95ad6beac82b
[ "Apache-2.0" ]
permissive
OpenRCS/sms-simulator
https://github.com/OpenRCS/sms-simulator
0ecfbc7086978ee9e44db7d9fe031bcddee1b4c5
03741e8edff4c21aa5ff40436710dcc8c7f3dd0f
refs/heads/main
2023-03-09T02:43:07.595000
2021-02-23T08:29:25
2021-02-23T08:29:25
335,307,420
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ch.sms.simulator.sms.cmpp; import com.ch.sms.simulator.sms.AbstractConfigure; import com.ch.sms.simulator.sms.SmsVersion; public class CMPPConfigure extends AbstractConfigure { private SmsVersion version; public void setVersion(SmsVersion version) { this.version = version; } @Override public SmsVersion getVersion() { return version; } }
UTF-8
Java
367
java
CMPPConfigure.java
Java
[]
null
[]
package com.ch.sms.simulator.sms.cmpp; import com.ch.sms.simulator.sms.AbstractConfigure; import com.ch.sms.simulator.sms.SmsVersion; public class CMPPConfigure extends AbstractConfigure { private SmsVersion version; public void setVersion(SmsVersion version) { this.version = version; } @Override public SmsVersion getVersion() { return version; } }
367
0.773842
0.773842
19
18.31579
19.542269
54
false
false
0
0
0
0
0
0
0.842105
false
false
13
21003c7c5e5c7beebae833443afe29a915b3f887
7,834,020,367,314
b3e306472ef9dc19cf383c8c776684ca7cec4f14
/src/main/java/mandarin/StartupListener.java
b22989cc35a95db2585e21660a6480165b758148
[]
no_license
mayi12/nwpu-mandarin
https://github.com/mayi12/nwpu-mandarin
b424718b4447e93f813f0273f0bb87ed0199cd17
2b3b1429eaeb02e1020fbbd410fc253a3453bf7a
refs/heads/master
2020-08-01T21:18:01.328000
2019-09-26T15:18:59
2019-09-26T15:18:59
211,119,850
0
0
null
true
2019-10-05T03:04:40
2019-09-26T15:17:22
2019-09-26T15:35:03
2019-09-26T15:35:01
271
0
0
1
Java
false
false
package mandarin; import mandarin.entities.Book; import mandarin.entities.Category; import org.apache.commons.io.IOUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.*; @Component public class StartupListener { private static boolean firstTime = true; private DataSource dataSource; @Resource EntityManagerFactory entityManagerFactory; public StartupListener(DataSource dataSource) { this.dataSource = dataSource; } @EventListener(ContextRefreshedEvent.class) public void addEntities() { if (firstTime) { firstTime = false; SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Category c1 = new Category("Programming", null); session.save(c1); session.flush(); Category c2 = new Category("Algorithms", c1); session.save(c2); Category c3 = new Category("Cryptography", c1); session.save(c3); session.save(new Book("9781617294945", "Spring in Action", "Craig Walls", "Shelf 1", BigDecimal.ONE, Collections.singletonList(c1))); session.save(new Book("9780262033848", "Introduction to Algorithms", "Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein", "Shelf 1", BigDecimal.ONE, Arrays.asList(c1, c2))); session.save(new Book("9781119183471", "Applied Cryptography: Protocols, Algorithms, and Source Code in C", "Bruce Schneier", "Shelf 1", BigDecimal.ONE, Arrays.asList(c1, c2, c3))); session.flush(); tx.commit(); session.close(); } } public void run() { Connection conn = null; try { Properties props = new Properties(); props.load(getClass().getClassLoader().getResourceAsStream("application.properties")); if (!Boolean.parseBoolean(props.getProperty("mandarin.exec-init-sql", "false"))) { return; } conn = dataSource.getConnection(); conn.setAutoCommit(false); conn.nativeSQL("BEGIN;"); StringWriter writer = new StringWriter(); IOUtils.copy(StartupListener.class.getClassLoader().getResourceAsStream("data.sql"), writer, StandardCharsets.UTF_8); Statement stmt = conn.createStatement(); stmt.execute(writer.toString()); conn.commit(); } catch (IOException | SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException ex) { ex.printStackTrace(); } throw new RuntimeException(e); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
UTF-8
Java
3,688
java
StartupListener.java
Java
[ { "context": "k(\"9780262033848\", \"Introduction to Algorithms\", \"Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford", "end": 1973, "score": 0.9998756051063538, "start": 1957, "tag": "NAME", "value": "Thomas H. Cormen" }, { "context": ", \"Introduction to Algorithms\", \"Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein\", \"Shelf 1\", Bi", "end": 1995, "score": 0.9998708963394165, "start": 1975, "tag": "NAME", "value": "Charles E. Leiserson" }, { "context": "orithms\", \"Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein\", \"Shelf 1\", BigDecimal.ONE, Arra", "end": 2013, "score": 0.9998733997344971, "start": 1997, "tag": "NAME", "value": "Ronald L. Rivest" }, { "context": "H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein\", \"Shelf 1\", BigDecimal.ONE, Arrays.asList(c1, c2", "end": 2029, "score": 0.9998685717582703, "start": 2015, "tag": "NAME", "value": "Clifford Stein" }, { "context": "y: Protocols, Algorithms, and Source Code in C\", \"Bruce Schneier\", \"Shelf 1\", BigDecimal.ONE, Arrays.asList(c1, c2", "end": 2219, "score": 0.9998785853385925, "start": 2205, "tag": "NAME", "value": "Bruce Schneier" } ]
null
[]
package mandarin; import mandarin.entities.Book; import mandarin.entities.Category; import org.apache.commons.io.IOUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.*; @Component public class StartupListener { private static boolean firstTime = true; private DataSource dataSource; @Resource EntityManagerFactory entityManagerFactory; public StartupListener(DataSource dataSource) { this.dataSource = dataSource; } @EventListener(ContextRefreshedEvent.class) public void addEntities() { if (firstTime) { firstTime = false; SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class); Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Category c1 = new Category("Programming", null); session.save(c1); session.flush(); Category c2 = new Category("Algorithms", c1); session.save(c2); Category c3 = new Category("Cryptography", c1); session.save(c3); session.save(new Book("9781617294945", "Spring in Action", "Craig Walls", "Shelf 1", BigDecimal.ONE, Collections.singletonList(c1))); session.save(new Book("9780262033848", "Introduction to Algorithms", "<NAME>, <NAME>, <NAME>, <NAME>", "Shelf 1", BigDecimal.ONE, Arrays.asList(c1, c2))); session.save(new Book("9781119183471", "Applied Cryptography: Protocols, Algorithms, and Source Code in C", "<NAME>", "Shelf 1", BigDecimal.ONE, Arrays.asList(c1, c2, c3))); session.flush(); tx.commit(); session.close(); } } public void run() { Connection conn = null; try { Properties props = new Properties(); props.load(getClass().getClassLoader().getResourceAsStream("application.properties")); if (!Boolean.parseBoolean(props.getProperty("mandarin.exec-init-sql", "false"))) { return; } conn = dataSource.getConnection(); conn.setAutoCommit(false); conn.nativeSQL("BEGIN;"); StringWriter writer = new StringWriter(); IOUtils.copy(StartupListener.class.getClassLoader().getResourceAsStream("data.sql"), writer, StandardCharsets.UTF_8); Statement stmt = conn.createStatement(); stmt.execute(writer.toString()); conn.commit(); } catch (IOException | SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException ex) { ex.printStackTrace(); } throw new RuntimeException(e); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
3,638
0.630965
0.61551
97
37.03093
34.129665
208
false
false
0
0
0
0
0
0
0.948454
false
false
13
07f1b1486fda5b111b7dea226427999d1ba67af2
7,834,020,366,870
352b447126d637efe5cfcac75729deea93117ffc
/android/KMAPro/kMAPro/src/main/java/com/tavultesoft/kmapro/WebBrowserActivity.java
3d72f77bbaa5df75f75218ef94c4cfd1111e6f5f
[ "MIT" ]
permissive
gitarthakalita/keyman
https://github.com/gitarthakalita/keyman
5ffd7b77df7dbe9acdf841a776493fda3e98ecd3
102613e1b0a85716b90aa6691d617a6aeb5c58f5
refs/heads/master
2020-03-18T20:41:35.999000
2018-05-18T08:33:49
2018-05-18T08:33:49
135,232,390
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (C) 2017 SIL International. All rights reserved. */ package com.tavultesoft.kmapro; import java.net.MalformedURLException; import java.net.URL; import com.tavultesoft.kmea.KMManager; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Patterns; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.app.ActionBar; import android.app.Activity; public class WebBrowserActivity extends Activity { private WebView webView; private EditText addressField; private ImageButton clearButton; private ImageButton stopButton; private ImageButton reloadButton; private ProgressBar progressBar; private static final String fontBaseUri = "https://s.keyman.com/font/deploy/"; private String loadedFont; private boolean isLoading = false; private boolean didFinishLoading = false; @SuppressLint({"SetJavaScriptEnabled", "InflateParams"}) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context context = this; final ActionBar actionBar = getActionBar(); actionBar.setLogo(null); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowCustomEnabled(true); actionBar.setBackgroundDrawable(MainActivity.getActionBarDrawable(this)); final ViewGroup webBarLayout = (ViewGroup) getLayoutInflater().inflate( R.layout.web_browser_bar_layout, null); actionBar.setCustomView(webBarLayout); setContentView(R.layout.activity_web_browser); webView = (WebView) findViewById(R.id.browserWebView); addressField = (EditText) findViewById(R.id.address_field); clearButton = (ImageButton) findViewById(R.id.clear_button); stopButton = (ImageButton) findViewById(R.id.stop_button); reloadButton = (ImageButton) findViewById(R.id.reload_button); final ImageButton backButton = (ImageButton) findViewById(R.id.backButton); final ImageButton forwardButton = (ImageButton) findViewById(R.id.forwardButton); final ImageButton bookmarksButton = (ImageButton) findViewById(R.id.bookmarksButton); final ImageButton globeButton = (ImageButton) findViewById(R.id.globeButton); final ImageButton closeButton = (ImageButton) findViewById(R.id.closeButton); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setRotation(180); addressField.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (addressField.length() > 0) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } else { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.GONE); } } else { if (isLoading) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); addressField.setText(webView.getUrl()); } else if (didFinishLoading) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); addressField.setText(webView.getUrl()); } } } }); addressField.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void afterTextChanged(Editable s) { if (s.length() >= 1) { if (addressField.hasFocus()) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } } else { if (addressField.hasFocus()) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.GONE); } else { if (isLoading) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); } else if (didFinishLoading) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } } } } }); clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.setText(""); } }); stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.stopLoading(); updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } loadFont(); } }); reloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.reload(); } }); backButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.goBack(); } }); forwardButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.goForward(); } }); bookmarksButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); Intent i = new Intent(context, BookmarksActivity.class); i.putExtra("title", webView.getTitle()); i.putExtra("url", webView.getUrl()); startActivityForResult(i, 1); } }); globeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); KMManager.showKeyboardPicker(context, KMManager.KeyboardType.KEYBOARD_TYPE_INAPP); } }); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); overridePendingTransition(0, android.R.anim.fade_out); } }); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSupportZoom(true); webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { progressBar.setProgress(100 - progress); } }); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (!url.toLowerCase().equals("about:blank")) view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { updateButtons(); isLoading = true; didFinishLoading = false; addressField.setText(url); if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); } } @Override public void onPageFinished(WebView view, String url) { updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } loadFont(); } }); addressField.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_GO || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(addressField.getWindowToken(), 0); String urlStr = v.getText().toString(); try { new URL(urlStr); } catch (MalformedURLException e) { if (Patterns.WEB_URL.matcher(String.format("%s%s", "http://", urlStr)).matches()) { urlStr = String.format("%s%s", "http://", urlStr); } else { urlStr = String.format("https://www.google.com/search?q=%s", urlStr); } } webView.loadUrl(urlStr); addressField.clearFocus(); handled = true; } return handled; } }); updateButtons(); addressField.clearFocus(); // Load last visited Url SharedPreferences prefs = getSharedPreferences(getString(R.string.kma_prefs_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); String url = prefs.getString("lastVisitedUrl", "https://www.google.com/"); webView.loadUrl(url); } @Override protected void onResume() { super.onResume(); if (webView != null) { webView.resumeTimers(); if (didFinishLoading) { String fontFilename = KMManager.getKeyboardTextFontFilename(); if (!loadedFont.equals(fontFilename)) { webView.reload(); } } } } @Override protected void onPause() { super.onPause(); if (webView != null) { webView.pauseTimers(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (webView != null) { if (resultCode == RESULT_OK && data != null) { String url = data.getStringExtra("url"); if (url != null) webView.loadUrl(url); } } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override public void onBackPressed() { if (webView != null && webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); finish(); } } private void loadFont() { String font = KMManager.getKeyboardTextFontFilename(); if (!font.isEmpty()) { loadedFont = font; String fontUrl = String.format("%s%s", fontBaseUri, font); String jsStr = String.format( "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = '@font-face{font-family:\"KMCustomFont\";src:url(\"%s\");} " + "*{font-family:\"KMCustomFont\" !important;}';" + "document.getElementsByTagName('head')[0].appendChild(style);", fontUrl); webView.loadUrl(String.format("javascript:%s", jsStr)); } else { loadedFont = "sans-serif"; String jsStr = "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = '*{font-family:\"sans-serif\" !important;}';" + "document.getElementsByTagName('head')[0].appendChild(style);"; webView.loadUrl(String.format("javascript:%s", jsStr)); } } private void updateButtons() { ImageButton backButton = (ImageButton) findViewById(R.id.backButton); ImageButton forwardButton = (ImageButton) findViewById(R.id.forwardButton); setImageButtonEnabled(backButton, R.drawable.ic_navigation_back, webView.canGoBack()); setImageButtonEnabled(forwardButton, R.drawable.ic_navigation_forward, webView.canGoForward()); } private void setImageButtonEnabled(ImageButton imgButton, int resId, boolean enabled) { imgButton.setEnabled(enabled); Drawable originalIcon; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { originalIcon = getResources().getDrawable(resId, getTheme()); } else { originalIcon = getResources().getDrawable(resId); } Drawable icon = enabled ? originalIcon : convertDrawableToGrayScale(originalIcon); imgButton.setImageDrawable(icon); } private static Drawable convertDrawableToGrayScale(Drawable drawable) { if (drawable == null) return null; Drawable drw = drawable.mutate(); drw.setColorFilter(Color.LTGRAY, Mode.SRC_IN); return drw; } }
UTF-8
Java
14,460
java
WebBrowserActivity.java
Java
[]
null
[]
/** * Copyright (C) 2017 SIL International. All rights reserved. */ package com.tavultesoft.kmapro; import java.net.MalformedURLException; import java.net.URL; import com.tavultesoft.kmea.KMManager; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Patterns; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.app.ActionBar; import android.app.Activity; public class WebBrowserActivity extends Activity { private WebView webView; private EditText addressField; private ImageButton clearButton; private ImageButton stopButton; private ImageButton reloadButton; private ProgressBar progressBar; private static final String fontBaseUri = "https://s.keyman.com/font/deploy/"; private String loadedFont; private boolean isLoading = false; private boolean didFinishLoading = false; @SuppressLint({"SetJavaScriptEnabled", "InflateParams"}) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context context = this; final ActionBar actionBar = getActionBar(); actionBar.setLogo(null); actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowCustomEnabled(true); actionBar.setBackgroundDrawable(MainActivity.getActionBarDrawable(this)); final ViewGroup webBarLayout = (ViewGroup) getLayoutInflater().inflate( R.layout.web_browser_bar_layout, null); actionBar.setCustomView(webBarLayout); setContentView(R.layout.activity_web_browser); webView = (WebView) findViewById(R.id.browserWebView); addressField = (EditText) findViewById(R.id.address_field); clearButton = (ImageButton) findViewById(R.id.clear_button); stopButton = (ImageButton) findViewById(R.id.stop_button); reloadButton = (ImageButton) findViewById(R.id.reload_button); final ImageButton backButton = (ImageButton) findViewById(R.id.backButton); final ImageButton forwardButton = (ImageButton) findViewById(R.id.forwardButton); final ImageButton bookmarksButton = (ImageButton) findViewById(R.id.bookmarksButton); final ImageButton globeButton = (ImageButton) findViewById(R.id.globeButton); final ImageButton closeButton = (ImageButton) findViewById(R.id.closeButton); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setRotation(180); addressField.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (addressField.length() > 0) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } else { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.GONE); } } else { if (isLoading) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); addressField.setText(webView.getUrl()); } else if (didFinishLoading) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); addressField.setText(webView.getUrl()); } } } }); addressField.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void afterTextChanged(Editable s) { if (s.length() >= 1) { if (addressField.hasFocus()) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.VISIBLE); } } else { if (addressField.hasFocus()) { reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); clearButton.setVisibility(View.GONE); } else { if (isLoading) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); } else if (didFinishLoading) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } } } } }); clearButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.setText(""); } }); stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.stopLoading(); updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } loadFont(); } }); reloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.reload(); } }); backButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.goBack(); } }); forwardButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); webView.goForward(); } }); bookmarksButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); Intent i = new Intent(context, BookmarksActivity.class); i.putExtra("title", webView.getTitle()); i.putExtra("url", webView.getUrl()); startActivityForResult(i, 1); } }); globeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addressField.clearFocus(); KMManager.showKeyboardPicker(context, KMManager.KeyboardType.KEYBOARD_TYPE_INAPP); } }); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); overridePendingTransition(0, android.R.anim.fade_out); } }); webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSupportZoom(true); webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { progressBar.setProgress(100 - progress); } }); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (!url.toLowerCase().equals("about:blank")) view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { updateButtons(); isLoading = true; didFinishLoading = false; addressField.setText(url); if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE); stopButton.setVisibility(View.VISIBLE); } } @Override public void onPageFinished(WebView view, String url) { updateButtons(); didFinishLoading = true; isLoading = false; if (!addressField.hasFocus()) { clearButton.setVisibility(View.GONE); stopButton.setVisibility(View.GONE); reloadButton.setVisibility(View.VISIBLE); } loadFont(); } }); addressField.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_GO || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(addressField.getWindowToken(), 0); String urlStr = v.getText().toString(); try { new URL(urlStr); } catch (MalformedURLException e) { if (Patterns.WEB_URL.matcher(String.format("%s%s", "http://", urlStr)).matches()) { urlStr = String.format("%s%s", "http://", urlStr); } else { urlStr = String.format("https://www.google.com/search?q=%s", urlStr); } } webView.loadUrl(urlStr); addressField.clearFocus(); handled = true; } return handled; } }); updateButtons(); addressField.clearFocus(); // Load last visited Url SharedPreferences prefs = getSharedPreferences(getString(R.string.kma_prefs_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); String url = prefs.getString("lastVisitedUrl", "https://www.google.com/"); webView.loadUrl(url); } @Override protected void onResume() { super.onResume(); if (webView != null) { webView.resumeTimers(); if (didFinishLoading) { String fontFilename = KMManager.getKeyboardTextFontFilename(); if (!loadedFont.equals(fontFilename)) { webView.reload(); } } } } @Override protected void onPause() { super.onPause(); if (webView != null) { webView.pauseTimers(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (webView != null) { if (resultCode == RESULT_OK && data != null) { String url = data.getStringExtra("url"); if (url != null) webView.loadUrl(url); } } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); } @Override public void onBackPressed() { if (webView != null && webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); finish(); } } private void loadFont() { String font = KMManager.getKeyboardTextFontFilename(); if (!font.isEmpty()) { loadedFont = font; String fontUrl = String.format("%s%s", fontBaseUri, font); String jsStr = String.format( "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = '@font-face{font-family:\"KMCustomFont\";src:url(\"%s\");} " + "*{font-family:\"KMCustomFont\" !important;}';" + "document.getElementsByTagName('head')[0].appendChild(style);", fontUrl); webView.loadUrl(String.format("javascript:%s", jsStr)); } else { loadedFont = "sans-serif"; String jsStr = "var style = document.createElement('style');" + "style.type = 'text/css';" + "style.innerHTML = '*{font-family:\"sans-serif\" !important;}';" + "document.getElementsByTagName('head')[0].appendChild(style);"; webView.loadUrl(String.format("javascript:%s", jsStr)); } } private void updateButtons() { ImageButton backButton = (ImageButton) findViewById(R.id.backButton); ImageButton forwardButton = (ImageButton) findViewById(R.id.forwardButton); setImageButtonEnabled(backButton, R.drawable.ic_navigation_back, webView.canGoBack()); setImageButtonEnabled(forwardButton, R.drawable.ic_navigation_forward, webView.canGoForward()); } private void setImageButtonEnabled(ImageButton imgButton, int resId, boolean enabled) { imgButton.setEnabled(enabled); Drawable originalIcon; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { originalIcon = getResources().getDrawable(resId, getTheme()); } else { originalIcon = getResources().getDrawable(resId); } Drawable icon = enabled ? originalIcon : convertDrawableToGrayScale(originalIcon); imgButton.setImageDrawable(icon); } private static Drawable convertDrawableToGrayScale(Drawable drawable) { if (drawable == null) return null; Drawable drw = drawable.mutate(); drw.setColorFilter(Color.LTGRAY, Mode.SRC_IN); return drw; } }
14,460
0.65982
0.658645
435
32.243679
24.569777
109
false
false
0
0
0
0
0
0
0.636782
false
false
13
ff78f8870d599534b74b2467c02063900df2b827
28,346,784,177,267
c5b8f09683598bc6b34c01e5f50ad59b9a4c7c0a
/app/src/main/java/ca/shahnewazkhan/locator/MainActivity.java
3d59a8c496393f74c2bdc34cce2c2c22e0208407
[]
no_license
ShahNewazKhan/locatorAndroid
https://github.com/ShahNewazKhan/locatorAndroid
edeeed24a283d67069cae57b95ec0dc38f0078e9
d6f33f4ec1c694e0be422ec4c3a4ea6a023f036a
refs/heads/master
2021-01-20T06:20:19.146000
2015-07-31T07:00:23
2015-07-31T07:00:23
38,581,651
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.shahnewazkhan.locator; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.AccessTokenTracker; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.Profile; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.facebook.login.widget.ProfilePictureView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final String TAG = "LOCATOR-APP"; public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 6000; public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. private final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key"; private final static String LOCATION_KEY = "location-key"; private final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key"; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private Location mCurrentLocation; private Boolean mRequestingLocationUpdates; private String mLastUpdateTime; private String mongoID; private CallbackManager mCallbackManager; private Context context; private ProfilePictureView profilePictureView; private RecyclerView recList; private Profile profile; private String locatorApi = "http://107.170.234.15:3000/api/users/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); mCallbackManager = CallbackManager.Factory.create(); context = getApplicationContext(); profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture); profilePictureView.isInEditMode(); mRequestingLocationUpdates = true; mLastUpdateTime = ""; recList = (RecyclerView) findViewById(R.id.cardList); recList.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recList.setLayoutManager(llm); LoginButton loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.isInEditMode(); LoginManager.getInstance().registerCallback(mCallbackManager, mCallback); AccessTokenTracker tracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) { if(newToken == null){ logOut(); } } }; Intent intent = getIntent(); String url = intent.getExtras().getString("url"); if( !url.equals("pass") ){ locatorApi = url + "/api/users/" ; Toast.makeText(context, "Updated: " + locatorApi, Toast.LENGTH_SHORT ).show(); } updateValuesFromBundle(savedInstanceState); buildGoogleApiClient(); } private void updateValuesFromBundle(Bundle savedInstanceState) { Log.i(TAG, "Updating values from bundle"); if (savedInstanceState != null) { if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( REQUESTING_LOCATION_UPDATES_KEY); } if (savedInstanceState.keySet().contains(LOCATION_KEY)) { mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY); } if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) { mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY); } } } protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); createLocationRequest(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { mGoogleApiClient.disconnect(); logOut(); super.onStop(); } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); } if (mRequestingLocationUpdates) { startLocationUpdates(); } } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); /* Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();*/ if(profile != null){ deleteUserFromApi(true); } } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates); savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation); savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } //After successful facebook login Store user fb id, name & location to api & load cards with //current users logged in from api private FacebookCallback<LoginResult> mCallback= new FacebookCallback<LoginResult>(){ @Override public void onSuccess(LoginResult loginResult) { profile = Profile.getCurrentProfile(); if(profile != null){ preparePostUser(); } } @Override public void onCancel() {} @Override public void onError(FacebookException e) {} }; private void preparePostUser(){ //Set fb profile picture profilePictureView.setProfileId(profile.getId()); //Prepare params for api post call RequestParams params = new RequestParams(); params.put("name", profile.getName()); params.put("fb_id", profile.getId()); params.put("lat", mCurrentLocation.getLatitude()); params.put("lon", mCurrentLocation.getLongitude()); //Post to api postNewUser(params); //Populate user cards populateCards(); } //Post user data (fb id, name & location) to api private void postNewUser(RequestParams params){ LocatorRestClient.post(locatorApi, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { //Get mongo id from response try { mongoID = response.getString("_id"); } catch (Exception e) { e.printStackTrace(); } } }); } private void populateCards(){ Log.d("GETTING", "USERS"); AsyncHttpClient client = new AsyncHttpClient(); client.get(locatorApi, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { try { JSONArray res = new JSONArray(new String(response)); updateUI(res); } catch (Exception e) { } } @Override public void onFailure(int sc, Header[] h, byte[] errorRes, Throwable e) { } }); } private void updateUI(JSONArray res){ List users = new ArrayList(); try{ for (int i = 0; i < res.length(); i++) { JSONObject jsonObj = (JSONObject) res.get(i); //Current user loged into app if( mongoID != null && mongoID.equals(jsonObj.getString("_id"))) continue; UserCardInfo uci = new UserCardInfo(); uci.name = (String) jsonObj.get("name"); uci.fb_id = String.valueOf(jsonObj.get("fb_id")); uci.distance = getDistance(jsonObj.getDouble("lat"), jsonObj.getDouble("lon")); users.add(uci); } Collections.sort(users, compDistance()); }catch(Exception e){ e.printStackTrace();} UserAdapter userAdapter = new UserAdapter(users); if(recList != null){ Log.d(TAG, "Updating UI"); recList.setAdapter(userAdapter); userAdapter.notifyDataSetChanged(); //mSwipeRefreshLayout.setRefreshing(false); } else { Log.d(TAG, "recList is NULL"); } } public static Comparator<UserCardInfo> compDistance() { Comparator comp = new Comparator<UserCardInfo>(){ @Override public int compare(UserCardInfo u1, UserCardInfo u2) { return Double.compare(Double.parseDouble(u1.distance), Double.parseDouble(u2.distance)); } }; return comp; } private String getDistance( double lat, double lon ){ Location userLocation = new Location("User location"); userLocation.setLatitude(lat); userLocation.setLongitude(lon); DecimalFormat df = new DecimalFormat("0.00"); String distance = df.format(mCurrentLocation.distanceTo(userLocation)); return distance; } //Log out user form facebook, delete user data from API and remove user profile pic private void logOut(){ //Remove user from api deleteUserFromApi(false); //Remove user profile pic profilePictureView.setProfileId(""); //Clear cards UserAdapter userAdapter = new UserAdapter(new ArrayList()); if(recList != null){ Log.d(TAG, "Clearing Cards"); recList.setAdapter(userAdapter); userAdapter.notifyDataSetChanged(); } else { Log.d(TAG, "recList is NULL"); } //Logout user LoginManager.getInstance().logOut(); profile = null; } private void deleteUserFromApi(final boolean postUser){ //Delete user data from api AsyncHttpClient client = new AsyncHttpClient(); client.delete(locatorApi + mongoID, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if(postUser){ preparePostUser(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(System.out); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mCallbackManager.onActivityResult(requestCode, resultCode, data); } }
UTF-8
Java
14,449
java
MainActivity.java
Java
[ { "context": " profile;\n private String locatorApi = \"http://107.170.234.15:3000/api/users/\";\n\n @Override\n protected vo", "end": 2912, "score": 0.9997031092643738, "start": 2898, "tag": "IP_ADDRESS", "value": "107.170.234.15" } ]
null
[]
package ca.shahnewazkhan.locator; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.facebook.AccessToken; import com.facebook.AccessTokenTracker; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.Profile; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.facebook.login.widget.ProfilePictureView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.apache.http.Header; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private static final String TAG = "LOCATOR-APP"; public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 6000; public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. private final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key"; private final static String LOCATION_KEY = "location-key"; private final static String LAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key"; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private Location mCurrentLocation; private Boolean mRequestingLocationUpdates; private String mLastUpdateTime; private String mongoID; private CallbackManager mCallbackManager; private Context context; private ProfilePictureView profilePictureView; private RecyclerView recList; private Profile profile; private String locatorApi = "http://172.16.58.3:3000/api/users/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); mCallbackManager = CallbackManager.Factory.create(); context = getApplicationContext(); profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture); profilePictureView.isInEditMode(); mRequestingLocationUpdates = true; mLastUpdateTime = ""; recList = (RecyclerView) findViewById(R.id.cardList); recList.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recList.setLayoutManager(llm); LoginButton loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.isInEditMode(); LoginManager.getInstance().registerCallback(mCallbackManager, mCallback); AccessTokenTracker tracker = new AccessTokenTracker() { @Override protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) { if(newToken == null){ logOut(); } } }; Intent intent = getIntent(); String url = intent.getExtras().getString("url"); if( !url.equals("pass") ){ locatorApi = url + "/api/users/" ; Toast.makeText(context, "Updated: " + locatorApi, Toast.LENGTH_SHORT ).show(); } updateValuesFromBundle(savedInstanceState); buildGoogleApiClient(); } private void updateValuesFromBundle(Bundle savedInstanceState) { Log.i(TAG, "Updating values from bundle"); if (savedInstanceState != null) { if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( REQUESTING_LOCATION_UPDATES_KEY); } if (savedInstanceState.keySet().contains(LOCATION_KEY)) { mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY); } if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) { mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY); } } } protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); createLocationRequest(); } protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { mGoogleApiClient.disconnect(); logOut(); super.onStop(); } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); } if (mRequestingLocationUpdates) { startLocationUpdates(); } } @Override public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); /* Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();*/ if(profile != null){ deleteUserFromApi(true); } } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates); savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation); savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } //After successful facebook login Store user fb id, name & location to api & load cards with //current users logged in from api private FacebookCallback<LoginResult> mCallback= new FacebookCallback<LoginResult>(){ @Override public void onSuccess(LoginResult loginResult) { profile = Profile.getCurrentProfile(); if(profile != null){ preparePostUser(); } } @Override public void onCancel() {} @Override public void onError(FacebookException e) {} }; private void preparePostUser(){ //Set fb profile picture profilePictureView.setProfileId(profile.getId()); //Prepare params for api post call RequestParams params = new RequestParams(); params.put("name", profile.getName()); params.put("fb_id", profile.getId()); params.put("lat", mCurrentLocation.getLatitude()); params.put("lon", mCurrentLocation.getLongitude()); //Post to api postNewUser(params); //Populate user cards populateCards(); } //Post user data (fb id, name & location) to api private void postNewUser(RequestParams params){ LocatorRestClient.post(locatorApi, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { //Get mongo id from response try { mongoID = response.getString("_id"); } catch (Exception e) { e.printStackTrace(); } } }); } private void populateCards(){ Log.d("GETTING", "USERS"); AsyncHttpClient client = new AsyncHttpClient(); client.get(locatorApi, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { try { JSONArray res = new JSONArray(new String(response)); updateUI(res); } catch (Exception e) { } } @Override public void onFailure(int sc, Header[] h, byte[] errorRes, Throwable e) { } }); } private void updateUI(JSONArray res){ List users = new ArrayList(); try{ for (int i = 0; i < res.length(); i++) { JSONObject jsonObj = (JSONObject) res.get(i); //Current user loged into app if( mongoID != null && mongoID.equals(jsonObj.getString("_id"))) continue; UserCardInfo uci = new UserCardInfo(); uci.name = (String) jsonObj.get("name"); uci.fb_id = String.valueOf(jsonObj.get("fb_id")); uci.distance = getDistance(jsonObj.getDouble("lat"), jsonObj.getDouble("lon")); users.add(uci); } Collections.sort(users, compDistance()); }catch(Exception e){ e.printStackTrace();} UserAdapter userAdapter = new UserAdapter(users); if(recList != null){ Log.d(TAG, "Updating UI"); recList.setAdapter(userAdapter); userAdapter.notifyDataSetChanged(); //mSwipeRefreshLayout.setRefreshing(false); } else { Log.d(TAG, "recList is NULL"); } } public static Comparator<UserCardInfo> compDistance() { Comparator comp = new Comparator<UserCardInfo>(){ @Override public int compare(UserCardInfo u1, UserCardInfo u2) { return Double.compare(Double.parseDouble(u1.distance), Double.parseDouble(u2.distance)); } }; return comp; } private String getDistance( double lat, double lon ){ Location userLocation = new Location("User location"); userLocation.setLatitude(lat); userLocation.setLongitude(lon); DecimalFormat df = new DecimalFormat("0.00"); String distance = df.format(mCurrentLocation.distanceTo(userLocation)); return distance; } //Log out user form facebook, delete user data from API and remove user profile pic private void logOut(){ //Remove user from api deleteUserFromApi(false); //Remove user profile pic profilePictureView.setProfileId(""); //Clear cards UserAdapter userAdapter = new UserAdapter(new ArrayList()); if(recList != null){ Log.d(TAG, "Clearing Cards"); recList.setAdapter(userAdapter); userAdapter.notifyDataSetChanged(); } else { Log.d(TAG, "recList is NULL"); } //Logout user LoginManager.getInstance().logOut(); profile = null; } private void deleteUserFromApi(final boolean postUser){ //Delete user data from api AsyncHttpClient client = new AsyncHttpClient(); client.delete(locatorApi + mongoID, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if(postUser){ preparePostUser(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(System.out); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mCallbackManager.onActivityResult(requestCode, resultCode, data); } }
14,446
0.643989
0.641844
440
31.838636
27.01252
104
false
false
0
0
0
0
0
0
0.552273
false
false
13
3b34d752ec1be41ccf67b8f8c7eb022348d322b4
31,104,153,172,997
95f098d72ff9001ce52b98ed5f5c487f2c566213
/kidneyMatching/src/inputOutput/node/unosExchangeUnit/UnosPatientInputAttributes.java
f5a7e99101d281015d9d1d0fa98838fc4d4deaa6
[ "Apache-2.0" ]
permissive
juvenn/kidneyExchange
https://github.com/juvenn/kidneyExchange
08af73e0aae6d0f903cbcf053a231e678af0bb50
cce52e7a5f5ca60ab8f44349097b719673b996b9
refs/heads/master
2021-01-15T10:31:10.209000
2017-08-07T15:00:21
2017-08-07T15:00:21
99,586,051
0
0
null
true
2017-08-07T14:21:31
2017-08-07T14:21:31
2016-05-08T18:14:22
2014-08-17T22:12:59
50,240
0
0
0
null
null
null
package inputOutput.node.unosExchangeUnit; import inputOutput.core.Attribute; import protoModeler.UnosPredicateBuilder.UnosHistoricData; import unosData.UnosPatient; import data.BloodType; import data.Race; public class UnosPatientInputAttributes { private final UnosHistoricData unosHistoricalData; private final Attribute<UnosPatient, Long> id; private final Attribute<UnosPatient, BloodType> bloodType; private final Attribute<UnosPatient, Race> race; private final Attribute<UnosPatient, Integer> ageYears; private final Attribute<UnosPatient, Integer> maxDonorAgeYr; public final Attribute<UnosPatient, Integer> centerId; private final Attribute<UnosPatient, Double> pra; private final Attribute<UnosPatient, Double> derivedPra; public UnosPatientInputAttributes(final UnosHistoricData unosHistoricalData) { this.unosHistoricalData = unosHistoricalData; id = new Attribute<UnosPatient, Long>() { @Override public Long apply(UnosPatient patient) { return patient.getId(); } }; bloodType = new Attribute<UnosPatient, BloodType>() { @Override public BloodType apply(UnosPatient patient) { return patient.getBloodType(); } }; race = new Attribute<UnosPatient, Race>() { @Override public Race apply(UnosPatient patient) { return patient.getRace(); } }; ageYears = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getAgeYears(); } }; maxDonorAgeYr = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getMaxDonorAgeYears(); } }; pra = new Attribute<UnosPatient, Double>() { @Override public Double apply(UnosPatient patient) { return patient.getcPra(); } }; derivedPra = new Attribute<UnosPatient, Double>() { @Override public Double apply(UnosPatient patient) { return unosHistoricalData.historicPatientPra(patient); } }; centerId = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getCenter(); } }; } public UnosHistoricData getUnosHistoricalData() { return unosHistoricalData; } public Attribute<UnosPatient, Long> getId() { return id; } public Attribute<UnosPatient, BloodType> getBloodType() { return bloodType; } public Attribute<UnosPatient, Race> getRace() { return race; } public Attribute<UnosPatient, Integer> getAgeYears() { return ageYears; } public Attribute<UnosPatient, Integer> getMaxDonorAgeYr() { return maxDonorAgeYr; } public Attribute<UnosPatient, Double> getPra() { return pra; } public Attribute<UnosPatient, Double> getDerivedPra() { return derivedPra; } public Attribute<UnosPatient, Integer> getCenterId() { return centerId; } }
UTF-8
Java
3,019
java
UnosPatientInputAttributes.java
Java
[]
null
[]
package inputOutput.node.unosExchangeUnit; import inputOutput.core.Attribute; import protoModeler.UnosPredicateBuilder.UnosHistoricData; import unosData.UnosPatient; import data.BloodType; import data.Race; public class UnosPatientInputAttributes { private final UnosHistoricData unosHistoricalData; private final Attribute<UnosPatient, Long> id; private final Attribute<UnosPatient, BloodType> bloodType; private final Attribute<UnosPatient, Race> race; private final Attribute<UnosPatient, Integer> ageYears; private final Attribute<UnosPatient, Integer> maxDonorAgeYr; public final Attribute<UnosPatient, Integer> centerId; private final Attribute<UnosPatient, Double> pra; private final Attribute<UnosPatient, Double> derivedPra; public UnosPatientInputAttributes(final UnosHistoricData unosHistoricalData) { this.unosHistoricalData = unosHistoricalData; id = new Attribute<UnosPatient, Long>() { @Override public Long apply(UnosPatient patient) { return patient.getId(); } }; bloodType = new Attribute<UnosPatient, BloodType>() { @Override public BloodType apply(UnosPatient patient) { return patient.getBloodType(); } }; race = new Attribute<UnosPatient, Race>() { @Override public Race apply(UnosPatient patient) { return patient.getRace(); } }; ageYears = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getAgeYears(); } }; maxDonorAgeYr = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getMaxDonorAgeYears(); } }; pra = new Attribute<UnosPatient, Double>() { @Override public Double apply(UnosPatient patient) { return patient.getcPra(); } }; derivedPra = new Attribute<UnosPatient, Double>() { @Override public Double apply(UnosPatient patient) { return unosHistoricalData.historicPatientPra(patient); } }; centerId = new Attribute<UnosPatient, Integer>() { @Override public Integer apply(UnosPatient patient) { return patient.getCenter(); } }; } public UnosHistoricData getUnosHistoricalData() { return unosHistoricalData; } public Attribute<UnosPatient, Long> getId() { return id; } public Attribute<UnosPatient, BloodType> getBloodType() { return bloodType; } public Attribute<UnosPatient, Race> getRace() { return race; } public Attribute<UnosPatient, Integer> getAgeYears() { return ageYears; } public Attribute<UnosPatient, Integer> getMaxDonorAgeYr() { return maxDonorAgeYr; } public Attribute<UnosPatient, Double> getPra() { return pra; } public Attribute<UnosPatient, Double> getDerivedPra() { return derivedPra; } public Attribute<UnosPatient, Integer> getCenterId() { return centerId; } }
3,019
0.693607
0.693607
111
26.198198
22.498777
80
false
false
0
0
0
0
0
0
0.585586
false
false
13
e926a59941755d1d7a4a6d51179cfd3088b8bb48
3,264,175,168,112
40021ccd580a0a63ff74de5c1d0f7c41773e349a
/guns-gateway/src/main/java/com/stylefeng/guns/rest/modular/user/vo/TokenAndRandomkey.java
7173b8a730623f851ede23a0757b38fa06695e59
[ "Apache-2.0" ]
permissive
pmixq/project_guns
https://github.com/pmixq/project_guns
d815f3eb8e84d70b589154520b8d83916603e468
d7f15d9f0b87b4d5071b61bfed5405c4f593f5e9
refs/heads/master
2022-10-17T05:22:59.221000
2019-07-23T13:05:21
2019-07-23T13:05:21
197,003,883
0
0
NOASSERTION
false
2022-10-12T20:29:19
2019-07-15T13:26:40
2019-07-23T13:06:15
2022-10-12T20:29:16
4,239
0
0
6
Java
false
false
package com.stylefeng.guns.rest.modular.user.vo; import lombok.Data; @Data public class TokenAndRandomkey { String randomKey; String token; }
UTF-8
Java
152
java
TokenAndRandomkey.java
Java
[]
null
[]
package com.stylefeng.guns.rest.modular.user.vo; import lombok.Data; @Data public class TokenAndRandomkey { String randomKey; String token; }
152
0.75
0.75
9
15.888889
15.538085
48
false
false
0
0
0
0
0
0
0.444444
false
false
13
93885993a7a200785313a02da80383e0e3a4166c
9,569,187,156,871
3142ad1075cc2caea798c46e4724549f6a9fb716
/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java
b85b2ca8c7079436c6ddce1eb2cd059268126ba5
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
Azure/azure-cosmosdb-java
https://github.com/Azure/azure-cosmosdb-java
2b4013cf8ac65be4e5333163729d867eb7a41d4c
bacc1b15cbc13bd036e905b44da9eaa7aaa5ff5e
refs/heads/master
2023-06-27T04:29:32.788000
2022-09-13T22:50:02
2022-09-13T22:50:02
85,361,423
70
63
MIT
false
2023-06-14T22:23:28
2017-03-17T22:59:18
2023-02-07T16:34:35
2023-06-14T22:23:24
10,221
54
64
65
Java
false
false
/** * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.azure.cosmosdb.rx.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.DataType; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.IncludedPath; import com.microsoft.azure.cosmosdb.Index; import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.SpyClientBuilder; import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import com.microsoft.azure.cosmosdb.rx.Utils; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import rx.Observable; public class DocumentQuerySpyWireContentTest extends TestSuiteBase { private Database createdDatabase; private DocumentCollection createdSinglePartitionCollection; private DocumentCollection createdMultiPartitionCollection; private List<Document> createdDocumentsInSinglePartitionCollection = new ArrayList<>(); private List<Document> createdDocumentsInMultiPartitionCollection = new ArrayList<>(); private SpyClientUnderTestFactory.ClientUnderTest client; public String getSinglePartitionCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdSinglePartitionCollection.getId()); } public String getMultiPartitionCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdMultiPartitionCollection.getId()); } @Factory(dataProvider = "clientBuilders") public DocumentQuerySpyWireContentTest(Builder clientBuilder) { super(clientBuilder); } @DataProvider(name = "responseContinuationTokenLimitParamProvider") public static Object[][] responseContinuationTokenLimitParamProvider() { FeedOptions options1 = new FeedOptions(); options1.setMaxItemCount(1); options1.setResponseContinuationTokenLimitInKb(5); options1.setPartitionKey(new PartitionKey("99")); String query1 = "Select * from r"; boolean multiPartitionCollection1 = true; FeedOptions options2 = new FeedOptions(); options2.setMaxItemCount(1); options2.setResponseContinuationTokenLimitInKb(5); options2.setPartitionKey(new PartitionKey("99")); String query2 = "Select * from r order by r.prop"; boolean multiPartitionCollection2 = false; FeedOptions options3 = new FeedOptions(); options3.setMaxItemCount(1); options3.setResponseContinuationTokenLimitInKb(5); options3.setPartitionKey(new PartitionKey("99")); String query3 = "Select * from r"; boolean multiPartitionCollection3 = false; FeedOptions options4 = new FeedOptions(); options4.setPartitionKey(new PartitionKey("99")); String query4 = "Select * from r order by r.prop"; boolean multiPartitionCollection4 = false; return new Object[][]{ {options1, query1, multiPartitionCollection1}, {options2, query2, multiPartitionCollection2}, {options3, query3, multiPartitionCollection3}, {options4, query4, multiPartitionCollection4}, }; } @Test(dataProvider = "responseContinuationTokenLimitParamProvider", groups = { "simple" }, timeOut = TIMEOUT) public void queryWithContinuationTokenLimit(FeedOptions options, String query, boolean isMultiParitionCollection) throws Exception { String collectionLink; if (isMultiParitionCollection) { collectionLink = getMultiPartitionCollectionLink(); } else { collectionLink = getSinglePartitionCollectionLink(); } client.clearCapturedRequests(); Observable<FeedResponse<Document>> queryObservable = client .queryDocuments(collectionLink, query, options); List<Document> results = queryObservable.flatMap(p -> Observable.from(p.getResults())) .toList().toBlocking().single(); assertThat(results.size()).describedAs("total results").isGreaterThanOrEqualTo(1); List<HttpClientRequest<ByteBuf>> requests = client.getCapturedRequests(); for(HttpClientRequest<ByteBuf> req: requests) { validateRequestHasContinuationTokenLimit(req, options.getResponseContinuationTokenLimitInKb()); } } private void validateRequestHasContinuationTokenLimit(HttpClientRequest<ByteBuf> request, Integer expectedValue) { // query plan request does'nt have this header so checking only for queries if(request.getHeaders().get(HttpConstants.HttpHeaders.IS_QUERY) != null ){ if (expectedValue != null && expectedValue > 0) { assertThat(request.getHeaders() .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isTrue(); assertThat(request.getHeaders() .get("x-ms-documentdb-responsecontinuationtokenlimitinkb")) .isEqualTo(Integer.toString(expectedValue)); } else { assertThat(request.getHeaders() .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isFalse(); } } } public Document createDocument(AsyncDocumentClient client, String collectionLink, int cnt) { Document docDefinition = getDocumentDefinition(cnt); return client .createDocument(collectionLink, docDefinition, null, false).toBlocking().single().getResource(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = new SpyClientBuilder(this.clientBuilder()).build(); createdDatabase = SHARED_DATABASE; createdSinglePartitionCollection = SHARED_SINGLE_PARTITION_COLLECTION; truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION); createdMultiPartitionCollection = SHARED_MULTI_PARTITION_COLLECTION; truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); for(int i = 0; i < 3; i++) { createdDocumentsInSinglePartitionCollection.add(createDocument(client, getCollectionLink(createdSinglePartitionCollection), i)); createdDocumentsInMultiPartitionCollection.add(createDocument(client, getCollectionLink(createdMultiPartitionCollection), i)); } for(int i = 0; i < 5; i++) { createdDocumentsInSinglePartitionCollection.add(createDocument(client, getCollectionLink(createdSinglePartitionCollection), 99)); createdDocumentsInMultiPartitionCollection.add(createDocument(client, getCollectionLink(createdMultiPartitionCollection), 99)); } // wait for catch up TimeUnit.SECONDS.sleep(1); FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); // do the query once to ensure the collection is cached. client.queryDocuments(getMultiPartitionCollectionLink(), "select * from root", options) .toCompletable().await(); // do the query once to ensure the collection is cached. client.queryDocuments(getSinglePartitionCollectionLink(), "select * from root", options) .toCompletable().await(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private static Document getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, cnt, cnt)); return doc; } }
UTF-8
Java
10,078
java
DocumentQuerySpyWireContentTest.java
Java
[ { "context": " options1.setPartitionKey(new PartitionKey(\"99\"));\n String query1 = \"Select * from r\";\n ", "end": 4066, "score": 0.8978179693222046, "start": 4065, "tag": "KEY", "value": "9" }, { "context": " options3.setPartitionKey(new PartitionKey(\"99\"));\n String query3 = \"Select * from r\";\n ", "end": 4679, "score": 0.969737708568573, "start": 4677, "tag": "KEY", "value": "99" }, { "context": " options4.setPartitionKey(new PartitionKey(\"99\"));\n String query4 = \"Select * from r orde", "end": 4882, "score": 0.7923235893249512, "start": 4880, "tag": "KEY", "value": "99" } ]
null
[]
/** * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.azure.cosmosdb.rx.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.DataType; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.IncludedPath; import com.microsoft.azure.cosmosdb.Index; import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.SpyClientBuilder; import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import com.microsoft.azure.cosmosdb.rx.Utils; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import rx.Observable; public class DocumentQuerySpyWireContentTest extends TestSuiteBase { private Database createdDatabase; private DocumentCollection createdSinglePartitionCollection; private DocumentCollection createdMultiPartitionCollection; private List<Document> createdDocumentsInSinglePartitionCollection = new ArrayList<>(); private List<Document> createdDocumentsInMultiPartitionCollection = new ArrayList<>(); private SpyClientUnderTestFactory.ClientUnderTest client; public String getSinglePartitionCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdSinglePartitionCollection.getId()); } public String getMultiPartitionCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdMultiPartitionCollection.getId()); } @Factory(dataProvider = "clientBuilders") public DocumentQuerySpyWireContentTest(Builder clientBuilder) { super(clientBuilder); } @DataProvider(name = "responseContinuationTokenLimitParamProvider") public static Object[][] responseContinuationTokenLimitParamProvider() { FeedOptions options1 = new FeedOptions(); options1.setMaxItemCount(1); options1.setResponseContinuationTokenLimitInKb(5); options1.setPartitionKey(new PartitionKey("99")); String query1 = "Select * from r"; boolean multiPartitionCollection1 = true; FeedOptions options2 = new FeedOptions(); options2.setMaxItemCount(1); options2.setResponseContinuationTokenLimitInKb(5); options2.setPartitionKey(new PartitionKey("99")); String query2 = "Select * from r order by r.prop"; boolean multiPartitionCollection2 = false; FeedOptions options3 = new FeedOptions(); options3.setMaxItemCount(1); options3.setResponseContinuationTokenLimitInKb(5); options3.setPartitionKey(new PartitionKey("99")); String query3 = "Select * from r"; boolean multiPartitionCollection3 = false; FeedOptions options4 = new FeedOptions(); options4.setPartitionKey(new PartitionKey("99")); String query4 = "Select * from r order by r.prop"; boolean multiPartitionCollection4 = false; return new Object[][]{ {options1, query1, multiPartitionCollection1}, {options2, query2, multiPartitionCollection2}, {options3, query3, multiPartitionCollection3}, {options4, query4, multiPartitionCollection4}, }; } @Test(dataProvider = "responseContinuationTokenLimitParamProvider", groups = { "simple" }, timeOut = TIMEOUT) public void queryWithContinuationTokenLimit(FeedOptions options, String query, boolean isMultiParitionCollection) throws Exception { String collectionLink; if (isMultiParitionCollection) { collectionLink = getMultiPartitionCollectionLink(); } else { collectionLink = getSinglePartitionCollectionLink(); } client.clearCapturedRequests(); Observable<FeedResponse<Document>> queryObservable = client .queryDocuments(collectionLink, query, options); List<Document> results = queryObservable.flatMap(p -> Observable.from(p.getResults())) .toList().toBlocking().single(); assertThat(results.size()).describedAs("total results").isGreaterThanOrEqualTo(1); List<HttpClientRequest<ByteBuf>> requests = client.getCapturedRequests(); for(HttpClientRequest<ByteBuf> req: requests) { validateRequestHasContinuationTokenLimit(req, options.getResponseContinuationTokenLimitInKb()); } } private void validateRequestHasContinuationTokenLimit(HttpClientRequest<ByteBuf> request, Integer expectedValue) { // query plan request does'nt have this header so checking only for queries if(request.getHeaders().get(HttpConstants.HttpHeaders.IS_QUERY) != null ){ if (expectedValue != null && expectedValue > 0) { assertThat(request.getHeaders() .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isTrue(); assertThat(request.getHeaders() .get("x-ms-documentdb-responsecontinuationtokenlimitinkb")) .isEqualTo(Integer.toString(expectedValue)); } else { assertThat(request.getHeaders() .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isFalse(); } } } public Document createDocument(AsyncDocumentClient client, String collectionLink, int cnt) { Document docDefinition = getDocumentDefinition(cnt); return client .createDocument(collectionLink, docDefinition, null, false).toBlocking().single().getResource(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = new SpyClientBuilder(this.clientBuilder()).build(); createdDatabase = SHARED_DATABASE; createdSinglePartitionCollection = SHARED_SINGLE_PARTITION_COLLECTION; truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION); createdMultiPartitionCollection = SHARED_MULTI_PARTITION_COLLECTION; truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); for(int i = 0; i < 3; i++) { createdDocumentsInSinglePartitionCollection.add(createDocument(client, getCollectionLink(createdSinglePartitionCollection), i)); createdDocumentsInMultiPartitionCollection.add(createDocument(client, getCollectionLink(createdMultiPartitionCollection), i)); } for(int i = 0; i < 5; i++) { createdDocumentsInSinglePartitionCollection.add(createDocument(client, getCollectionLink(createdSinglePartitionCollection), 99)); createdDocumentsInMultiPartitionCollection.add(createDocument(client, getCollectionLink(createdMultiPartitionCollection), 99)); } // wait for catch up TimeUnit.SECONDS.sleep(1); FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); // do the query once to ensure the collection is cached. client.queryDocuments(getMultiPartitionCollectionLink(), "select * from root", options) .toCompletable().await(); // do the query once to ensure the collection is cached. client.queryDocuments(getSinglePartitionCollectionLink(), "select * from root", options) .toCompletable().await(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private static Document getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , uuid, cnt, cnt)); return doc; } }
10,078
0.709565
0.69994
227
43.396477
33.423351
141
false
false
0
0
0
0
0
0
0.77533
false
false
13
ec465798af6272972125015708de452c84e2ee3c
24,799,141,190,337
d4e1173e428d07d5e05b3442645e7feb42c24715
/src/Filesplit.java
e3bfc6d33bc76a6d4fe33676f4cb1fd2cb5f82cf
[]
no_license
xKk2016/datapipeline
https://github.com/xKk2016/datapipeline
8e2b07588ee90b3239b925ff10011706f9545913
7e03f3d6e83ffd95b1e08c67ff0989f0ed34354a
refs/heads/master
2020-04-29T04:19:46.351000
2019-03-15T15:14:29
2019-03-15T15:14:29
175,843,500
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; public class Filesplit { public static void main(String[] args) throws IOException { String root = System.getProperty("user.dir"); FileReader fileReader = new FileReader(root+"\\src"+"\\chenfei.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String str=bufferedReader.readLine(); int index = 0; while (str !=null){ FileWriter fileWriter = new FileWriter("C:\\Users\\KK\\IdeaProjects\\datapipeline\\src\\chenfei\\chenfei"+index+".txt"); for (int i=0;i<10;i++){ fileWriter.append(str.replace("b", "") .replace("'", "") .replace("(","") .replace(")","")); fileWriter.append("\n"); str = bufferedReader.readLine(); if (str==null) break; } index++; fileWriter.close(); } fileReader.close(); } }
UTF-8
Java
1,008
java
Filesplit.java
Java
[]
null
[]
import java.io.*; public class Filesplit { public static void main(String[] args) throws IOException { String root = System.getProperty("user.dir"); FileReader fileReader = new FileReader(root+"\\src"+"\\chenfei.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String str=bufferedReader.readLine(); int index = 0; while (str !=null){ FileWriter fileWriter = new FileWriter("C:\\Users\\KK\\IdeaProjects\\datapipeline\\src\\chenfei\\chenfei"+index+".txt"); for (int i=0;i<10;i++){ fileWriter.append(str.replace("b", "") .replace("'", "") .replace("(","") .replace(")","")); fileWriter.append("\n"); str = bufferedReader.readLine(); if (str==null) break; } index++; fileWriter.close(); } fileReader.close(); } }
1,008
0.506944
0.502976
33
29.545454
28.898035
133
false
false
0
0
0
0
0
0
0.606061
false
false
13
da4f345f79c3454468da1428410fca01db19e3b4
12,756,052,896,649
be0a878a56747606e87d3198def98252f029d610
/src/main/java/com/example/NameSelect/CustomUserRepository.java
c1616485fb2e6e25c39f83fc4cee30b6cd24f941
[]
no_license
lasur/NameSelect
https://github.com/lasur/NameSelect
4206a49e94e342ab8a4695d2553d3b0efae1b428
bcda5aad621d91338a8298e4ceb0194d2a548a0c
refs/heads/master
2022-11-23T06:36:48.841000
2020-07-29T15:05:18
2020-07-29T15:05:18
283,529,287
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.NameSelect; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; @Repository public class CustomUserRepository { @PersistenceContext private EntityManager entityManager; @Transactional public void insert(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("INSERT INTO id_table(id_im,id_username) VALUES (?,?)") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void delete(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("delete from id_table where id_im= ? and id_username= ?") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void insert2(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("insert into id_table2(id_im2,id_username2) values(?,? )") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void delete2(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("delete from id_table2 where id_im2= ? and id_username2= ?") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void update(int note, Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("update id_table2 set note= ? where id_im2= ? and id_username2= ?") .setParameter(1, note) .setParameter(2,id_im ) .setParameter(3,id_username) .executeUpdate(); } }
UTF-8
Java
2,084
java
CustomUserRepository.java
Java
[]
null
[]
package com.example.NameSelect; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; @Repository public class CustomUserRepository { @PersistenceContext private EntityManager entityManager; @Transactional public void insert(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("INSERT INTO id_table(id_im,id_username) VALUES (?,?)") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void delete(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("delete from id_table where id_im= ? and id_username= ?") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void insert2(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("insert into id_table2(id_im2,id_username2) values(?,? )") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void delete2(Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("delete from id_table2 where id_im2= ? and id_username2= ?") .setParameter(1, id_im) .setParameter(2, id_username) .executeUpdate(); } @Transactional public void update(int note, Long id_im, Long id_username) { entityManager.joinTransaction(); entityManager.createNativeQuery("update id_table2 set note= ? where id_im2= ? and id_username2= ?") .setParameter(1, note) .setParameter(2,id_im ) .setParameter(3,id_username) .executeUpdate(); } }
2,084
0.629559
0.619002
66
30.59091
26.722467
107
false
false
0
0
0
0
0
0
0.560606
false
false
13
cd5cd4625eb17b502eb50bb1d38fd604101865b7
4,518,305,622,654
a92f6b3a0949f58b662e0db87a4568708d578a04
/src/main/java/com/data/dashboard/dao/FansTargetMapper.java
16e7be7038637ed781ef85ccbb2551cfea452d10
[]
no_license
nick-cwb/DataDashboard
https://github.com/nick-cwb/DataDashboard
6def1b4324a07084524f167d3d160e41896ad7fe
fa994b98d16c95671e9f5ef14cd3050f6a15e3ad
refs/heads/master
2020-03-13T05:04:48.582000
2018-04-25T08:31:18
2018-04-25T08:31:18
130,975,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.data.dashboard.dao; import java.util.List; import com.data.dashboard.entity.FansTarget; /** * @author Nick * * @Description * * @version 2018年4月14日 下午3:02:26 * */ public interface FansTargetMapper { List<FansTarget> queryFansTarget(String regionId); List<FansTarget> queryFansTrendDay(); List<FansTarget> queryFansTrendMon(); }
UTF-8
Java
379
java
FansTargetMapper.java
Java
[ { "context": ".data.dashboard.entity.FansTarget;\n\n/**\n * @author Nick\n * \n * @Description\n *\n * @version 2018年4月14日 下午3", "end": 134, "score": 0.9958109259605408, "start": 130, "tag": "NAME", "value": "Nick" } ]
null
[]
/** * */ package com.data.dashboard.dao; import java.util.List; import com.data.dashboard.entity.FansTarget; /** * @author Nick * * @Description * * @version 2018年4月14日 下午3:02:26 * */ public interface FansTargetMapper { List<FansTarget> queryFansTarget(String regionId); List<FansTarget> queryFansTrendDay(); List<FansTarget> queryFansTrendMon(); }
379
0.712737
0.680217
24
14.375
16.675362
51
false
false
0
0
0
0
0
0
0.416667
false
false
13
9ce4195e264cbe7c804ab7c2b6feb6a9ade009f1
32,057,635,923,654
fa1ad2e2ac7e376fc7cb3b3a6e1bb88eed3e80be
/studio/modules/quartz-service-parent/quartz-service-api/src/main/java/cn/datax/service/quartz/api/dto/QrtzJobDto.java
70842f12c04fa7a2bd5efd57c8461bc9a6cdccd7
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
alldatacenter/alldata
https://github.com/alldatacenter/alldata
7bc7713c9f1d56ad6b8e59ea03206d1073b7e047
8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6
refs/heads/master
2023-08-05T07:32:25.442000
2023-08-03T13:17:24
2023-08-03T13:17:24
213,321,771
774
250
Apache-2.0
false
2023-09-06T17:35:32
2019-10-07T07:36:18
2023-09-06T07:35:48
2023-09-06T17:35:30
1,610,032
1,898
711
14
null
false
false
package cn.datax.service.quartz.api.dto; import cn.datax.common.validate.ValidationGroups; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * <p> * 定时任务信息表 实体DTO * </p> * * @author AllDataDC * @date 2022-11-14 */ @ApiModel(value = "定时任务信息表Model") @Data public class QrtzJobDto implements Serializable { private static final long serialVersionUID=1L; @ApiModelProperty(value = "主键ID") @NotBlank(message = "主键ID不能为空", groups = {ValidationGroups.Update.class}) private String id; @ApiModelProperty(value = "任务名称") @NotBlank(message = "任务名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String jobName; @ApiModelProperty(value = "Spring Bean名称") @NotBlank(message = "Spring Bean名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String beanName; @ApiModelProperty(value = "方法名称") @NotBlank(message = "方法名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String methodName; @ApiModelProperty(value = "方法参数") private String methodParams; @ApiModelProperty(value = "cron表达式") @NotBlank(message = "cron表达式不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String cronExpression; @ApiModelProperty(value = "状态") @NotNull(message = "状态不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String status; @ApiModelProperty(value = "备注") private String remark; }
UTF-8
Java
1,934
java
QrtzJobDto.java
Java
[ { "context": "\n * <p>\r\n * 定时任务信息表 实体DTO\r\n * </p>\r\n *\r\n * @author AllDataDC\r\n * @date 2022-11-14\r\n */\r\n@ApiModel(value = \"定时任", "end": 395, "score": 0.9995477199554443, "start": 386, "tag": "USERNAME", "value": "AllDataDC" } ]
null
[]
package cn.datax.service.quartz.api.dto; import cn.datax.common.validate.ValidationGroups; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * <p> * 定时任务信息表 实体DTO * </p> * * @author AllDataDC * @date 2022-11-14 */ @ApiModel(value = "定时任务信息表Model") @Data public class QrtzJobDto implements Serializable { private static final long serialVersionUID=1L; @ApiModelProperty(value = "主键ID") @NotBlank(message = "主键ID不能为空", groups = {ValidationGroups.Update.class}) private String id; @ApiModelProperty(value = "任务名称") @NotBlank(message = "任务名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String jobName; @ApiModelProperty(value = "Spring Bean名称") @NotBlank(message = "Spring Bean名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String beanName; @ApiModelProperty(value = "方法名称") @NotBlank(message = "方法名称不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String methodName; @ApiModelProperty(value = "方法参数") private String methodParams; @ApiModelProperty(value = "cron表达式") @NotBlank(message = "cron表达式不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String cronExpression; @ApiModelProperty(value = "状态") @NotNull(message = "状态不能为空", groups = {ValidationGroups.Insert.class, ValidationGroups.Update.class}) private String status; @ApiModelProperty(value = "备注") private String remark; }
1,934
0.72097
0.715896
47
35.744682
30.697195
117
false
false
0
0
0
0
0
0
0.595745
false
false
13
ddcd4753c10fabde1638b65ab7ba2a28b196d436
32,160,715,140,330
f2c33683703189b1fc96e8cd5591222c615c5ccc
/latihan/sesi-06/src/belajar/oop/Tunai.java
87db3026219112c68a724feb2e42661f2f811d39
[]
no_license
endymuhardin/materi-java-fundamental
https://github.com/endymuhardin/materi-java-fundamental
511d7e4633df18a85dae54f1bc0664848e3867bb
579e0359fb9920e47161cddfd39e6a6405e9244e
refs/heads/master
2021-01-11T11:01:19.034000
2013-09-13T04:25:24
2013-09-13T04:25:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package belajar.oop; import java.math.BigDecimal; public class Tunai extends Pembayaran { private BigDecimal dibayar; public BigDecimal kembalian(Pembelian p){ return dibayar.subtract(p.total()); } public void proses(){ System.out.println("Memproses pembayaran tunai"); } public BigDecimal getDibayar(){ return this.dibayar; } public void setDibayar(BigDecimal d){ this.dibayar = d; } }
UTF-8
Java
409
java
Tunai.java
Java
[]
null
[]
package belajar.oop; import java.math.BigDecimal; public class Tunai extends Pembayaran { private BigDecimal dibayar; public BigDecimal kembalian(Pembelian p){ return dibayar.subtract(p.total()); } public void proses(){ System.out.println("Memproses pembayaran tunai"); } public BigDecimal getDibayar(){ return this.dibayar; } public void setDibayar(BigDecimal d){ this.dibayar = d; } }
409
0.738386
0.738386
23
16.826086
16.84366
51
false
false
0
0
0
0
0
0
1.043478
false
false
13
e47763d7849de39c765c7e78913b98cf1aa98d78
4,982,162,091,244
8fbffb4dd0adb309c8c1f005b0f64d37451c9d60
/web/src/main/java/com/athleticspot/training/infrastracture/dto/in/BaseInformationInDtoAssembler.java
8c37d66d4aa852121e6e231dde9bf08ab1ca16f5
[]
no_license
athleticspot/athleticspot
https://github.com/athleticspot/athleticspot
1465237f345c9fb4d847f0b10cd2a8b0242de959
d533e6061e1a6b9dbbfa2657db68b94978bfee45
refs/heads/master
2023-01-05T06:14:56.042000
2020-03-13T15:27:42
2020-03-13T15:27:42
97,162,460
0
2
null
false
2022-12-10T06:35:26
2017-07-13T20:30:45
2020-03-13T15:28:33
2022-12-10T06:35:25
177,354
0
2
14
JavaScript
false
false
package com.athleticspot.training.infrastracture.dto.in; import com.athleticspot.training.domain.trainingsurvey.BaseInformation; import org.springframework.stereotype.Component; /** * @author Tomasz Kasprzycki */ @Component public class BaseInformationInDtoAssembler { public BaseInformation assemble(BaseInformationInDto baseInformationInDto) { return new BaseInformation(baseInformationInDto.getBirthDay(), baseInformationInDto.getBodyMass(), baseInformationInDto.getHeight() ); } }
UTF-8
Java
538
java
BaseInformationInDtoAssembler.java
Java
[ { "context": "ingframework.stereotype.Component;\n\n/**\n * @author Tomasz Kasprzycki\n */\n@Component\npublic class BaseInformationInDtoA", "end": 212, "score": 0.9997265934944153, "start": 195, "tag": "NAME", "value": "Tomasz Kasprzycki" } ]
null
[]
package com.athleticspot.training.infrastracture.dto.in; import com.athleticspot.training.domain.trainingsurvey.BaseInformation; import org.springframework.stereotype.Component; /** * @author <NAME> */ @Component public class BaseInformationInDtoAssembler { public BaseInformation assemble(BaseInformationInDto baseInformationInDto) { return new BaseInformation(baseInformationInDto.getBirthDay(), baseInformationInDto.getBodyMass(), baseInformationInDto.getHeight() ); } }
527
0.763941
0.763941
18
28.888889
27.756659
80
false
false
0
0
0
0
0
0
0.333333
false
false
13
cd46208c04cd800195825eaf46f631d7fd20332d
19,619,410,635,775
7d7d3c898b8ffd8826ace9228ec7a5c00f76108e
/kefirUtil/src/test/java/su/opencode/kefir/util/test/objectUtils/SampleEnum.java
d10d4d62ec508d2c5ba788d9a2a80847021d4afe
[]
no_license
dmitry-weirdo/pda-kefir
https://github.com/dmitry-weirdo/pda-kefir
887fa83970853a80bfa40bdc69d2492476a1a003
cf600aa6cff7c83f4b7c8144237f222b5138214f
refs/heads/master
2022-07-08T08:21:45.466000
2020-12-02T02:56:36
2020-12-02T02:56:36
55,863,695
0
0
null
false
2022-06-29T16:51:35
2016-04-09T19:44:53
2020-12-02T02:56:35
2022-06-29T16:51:32
33,371
0
0
7
Java
false
false
/** Copyright 2013 LLC "Open Code" http://www.o-code.ru $HeadURL$ $Author$ $Revision$ $Date:: $ */ package su.opencode.kefir.util.test.objectUtils; public enum SampleEnum { firstEnumValue, secondEnumValue, thirdEnumValue }
UTF-8
Java
252
java
SampleEnum.java
Java
[]
null
[]
/** Copyright 2013 LLC "Open Code" http://www.o-code.ru $HeadURL$ $Author$ $Revision$ $Date:: $ */ package su.opencode.kefir.util.test.objectUtils; public enum SampleEnum { firstEnumValue, secondEnumValue, thirdEnumValue }
252
0.662698
0.646825
14
17.071428
16.250118
48
false
false
0
0
0
0
0
0
0.285714
false
false
13
caafe3d9de689737001e6aa60a722c251c602f13
23,940,147,735,021
5b422b84fea467e9ccbe1b90eddd70ec1d531301
/java/_coursera/_oop_java_spec_duke/C1/W2/src/com/iuriio/oop/strings_first_assignment/Part2.java
0218dfbe4bfe958814f1115782c29f882d8d4689
[ "MIT" ]
permissive
iuriioapps/experiments
https://github.com/iuriioapps/experiments
da944a57e051d0deeea0e18e10e3da8e2805cd61
decff8dd5f0371a406ecfa859f5b0b3e5802d00d
refs/heads/master
2018-10-22T13:33:10.116000
2018-08-21T15:23:36
2018-08-21T15:23:36
118,864,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iuriio.oop.strings_first_assignment; import java.util.Locale; public class Part2 { private String findSimpleGene(final String dna, final String startCodon, final String endCodon) { final int startCodonIndex = dna.indexOf(startCodon); if (startCodonIndex < 0) { return null; } final int endCodonIndex = dna.indexOf(endCodon, startCodonIndex + 3); if (endCodonIndex < 0) { return null; } final boolean lengthCheck = (endCodonIndex - startCodonIndex) % 3 == 0; if (!lengthCheck) { return null; } return dna.substring(startCodonIndex, endCodonIndex + 3); } public void testSimpleGene(final String dna) { System.out.println("Looking for gene in: " + dna); final String gene = this.findSimpleGene( dna.toUpperCase(Locale.US), "ATG", "TAA"); System.out.println(gene == null ? "Gene not found" : "Gene: " + gene); } public static void main(String[] args) { final Part2 p1 = new Part2(); p1.testSimpleGene("ATGTAA"); p1.testSimpleGene("ATGCCTAA"); p1.testSimpleGene("ATGCCCTAA"); } }
UTF-8
Java
1,270
java
Part2.java
Java
[]
null
[]
package com.iuriio.oop.strings_first_assignment; import java.util.Locale; public class Part2 { private String findSimpleGene(final String dna, final String startCodon, final String endCodon) { final int startCodonIndex = dna.indexOf(startCodon); if (startCodonIndex < 0) { return null; } final int endCodonIndex = dna.indexOf(endCodon, startCodonIndex + 3); if (endCodonIndex < 0) { return null; } final boolean lengthCheck = (endCodonIndex - startCodonIndex) % 3 == 0; if (!lengthCheck) { return null; } return dna.substring(startCodonIndex, endCodonIndex + 3); } public void testSimpleGene(final String dna) { System.out.println("Looking for gene in: " + dna); final String gene = this.findSimpleGene( dna.toUpperCase(Locale.US), "ATG", "TAA"); System.out.println(gene == null ? "Gene not found" : "Gene: " + gene); } public static void main(String[] args) { final Part2 p1 = new Part2(); p1.testSimpleGene("ATGTAA"); p1.testSimpleGene("ATGCCTAA"); p1.testSimpleGene("ATGCCCTAA"); } }
1,270
0.576378
0.566142
42
29.238094
24.423651
101
false
false
0
0
0
0
0
0
0.52381
false
false
13
3eaf4acc9a4de4567c22e1d874fe4689b89ea2f3
33,389,075,788,355
7d5dadb3ae24e74a8c738902191e1e69bc6859c2
/order_backend_springboot/src/test/java/com/order/repository/CategoryRepositoryTest.java
9abc194fc0187dfe9ec589eb6184b9130561c9a0
[]
no_license
kala2c/order
https://github.com/kala2c/order
958da0b021e4e77cff1b5593f3072f4f9e8e94ec
fedc4746435cc07c79740ae6aef54140b82349b8
refs/heads/master
2023-01-10T23:18:28.893000
2020-03-21T14:28:15
2020-03-21T14:28:15
248,742,789
0
0
null
false
2023-01-05T10:29:44
2020-03-20T11:50:28
2020-03-21T14:28:39
2023-01-05T10:29:43
3,461
0
0
26
Java
false
false
package com.order.repository; import com.order.domain.entity.Category; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class CategoryRepositoryTest { @Autowired CategoryRepository categoryRepository; @Test public void findTest() { List<Category> rlt = categoryRepository.findAll(); Assert.assertNotEquals(0 , rlt.size()); } }
UTF-8
Java
711
java
CategoryRepositoryTest.java
Java
[]
null
[]
package com.order.repository; import com.order.domain.entity.Category; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class CategoryRepositoryTest { @Autowired CategoryRepository categoryRepository; @Test public void findTest() { List<Category> rlt = categoryRepository.findAll(); Assert.assertNotEquals(0 , rlt.size()); } }
711
0.763713
0.756681
30
22.700001
20.375067
62
false
false
0
0
0
0
0
0
0.466667
false
false
13
61f8f0b8782c87a11579e10804fe175516501456
20,727,512,196,063
32fd0a92293e1f28c3acc0d66f82f9e74b37d357
/app/src/main/java/com/matrix/myapplication/view/LoadingDialog.java
38fb415fab1a25885d7de36eb09e94ffda07cf2a
[]
no_license
Clyr/TestList
https://github.com/Clyr/TestList
bba28d62ffb50420b171a73f524f9680b6977b62
3af631927075dea14dcdfef04c82bcf19f7f6e08
refs/heads/master
2021-07-10T13:03:19.494000
2020-08-18T12:13:12
2020-08-18T12:13:12
185,518,920
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.matrix.myapplication.view; import android.app.Activity; import android.app.Dialog; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.matrix.myapplication.R; /** * description:弹窗浮动加载进度条 */ public class LoadingDialog { /** * 加载数据对话框 */ private static Dialog mLoadingDialog; /** * 显示加载对话框 * * @param context 上下文 * @param msg 对话框显示内容 * @param cancelable 对话框是否可以取消 */ public static Dialog showLoading(Activity context, String msg, boolean cancelable) { View view = LayoutInflater.from(context).inflate(R.layout.dialog, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText(msg); return getDialog(context, view); } public static Dialog showLoading(Activity context) { View view = LayoutInflater.from(context).inflate(R.layout.dialog, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); mLoadingDialog = new Dialog(context, R.style.ProgressDialog); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); //lp.x = 100; // 新位置X坐标 //lp.y = 100; // 新位置Y坐标 lp.width = 240; // 宽度 lp.height = 240; // 高度 //lp.alpha = 0.7f; // 透明度 // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes // dialog.onWindowAttributesChanged(lp); dialogWindow.setAttributes(lp); /* * 将对话框的大小按屏幕大小的百分比设置 */ // WindowManager m = getWindowManager(); // Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用 // WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值 // p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6 // p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.95 // dialogWindow.setAttributes(p); mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); // mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } public static Dialog showLoadingBall(Activity context) { View view = LayoutInflater.from(context).inflate(R.layout.dialogball, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); return getDialog(context, view); } public static Dialog showLoadingBall(Activity context, String msg) { View view = LayoutInflater.from(context).inflate(R.layout.dialogball, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); if (msg != null && msg != "") { loadingText.setText(msg); } else { loadingText.setText("加载中..."); } return getDialog(context, view); } public static Dialog showLoadingBall(Activity context, int style) { View view = LayoutInflater.from(context).inflate(R.layout.dialogballtrans, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); return getDialog(context, view, style); } public static Dialog showLoadingBall(Activity context, String msg, int style) { View view = LayoutInflater.from(context).inflate(R.layout.dialogballtrans, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); if (msg != null && msg != "") { loadingText.setText(msg); } else { loadingText.setText("加载中..."); } return getDialog(context, view, style); } private static Dialog getDialog(Activity context, View view) { mLoadingDialog = new Dialog(context, R.style.ProgressDialog); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.width = 240; // 宽度 lp.height = 240; // 高度 mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } private static Dialog getDialog(Activity context, View view, int style) { mLoadingDialog = new Dialog(context, style); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.width = 240; // 宽度 lp.height = 240; // 高度 mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } /** * 关闭加载对话框 */ public static void cancelLoading() { if (mLoadingDialog != null) { mLoadingDialog.cancel(); } } }
UTF-8
Java
5,719
java
LoadingDialog.java
Java
[]
null
[]
package com.matrix.myapplication.view; import android.app.Activity; import android.app.Dialog; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.matrix.myapplication.R; /** * description:弹窗浮动加载进度条 */ public class LoadingDialog { /** * 加载数据对话框 */ private static Dialog mLoadingDialog; /** * 显示加载对话框 * * @param context 上下文 * @param msg 对话框显示内容 * @param cancelable 对话框是否可以取消 */ public static Dialog showLoading(Activity context, String msg, boolean cancelable) { View view = LayoutInflater.from(context).inflate(R.layout.dialog, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText(msg); return getDialog(context, view); } public static Dialog showLoading(Activity context) { View view = LayoutInflater.from(context).inflate(R.layout.dialog, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); mLoadingDialog = new Dialog(context, R.style.ProgressDialog); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); //lp.x = 100; // 新位置X坐标 //lp.y = 100; // 新位置Y坐标 lp.width = 240; // 宽度 lp.height = 240; // 高度 //lp.alpha = 0.7f; // 透明度 // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes // dialog.onWindowAttributesChanged(lp); dialogWindow.setAttributes(lp); /* * 将对话框的大小按屏幕大小的百分比设置 */ // WindowManager m = getWindowManager(); // Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用 // WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值 // p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6 // p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.95 // dialogWindow.setAttributes(p); mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); // mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } public static Dialog showLoadingBall(Activity context) { View view = LayoutInflater.from(context).inflate(R.layout.dialogball, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); return getDialog(context, view); } public static Dialog showLoadingBall(Activity context, String msg) { View view = LayoutInflater.from(context).inflate(R.layout.dialogball, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); if (msg != null && msg != "") { loadingText.setText(msg); } else { loadingText.setText("加载中..."); } return getDialog(context, view); } public static Dialog showLoadingBall(Activity context, int style) { View view = LayoutInflater.from(context).inflate(R.layout.dialogballtrans, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); loadingText.setText("加载中..."); return getDialog(context, view, style); } public static Dialog showLoadingBall(Activity context, String msg, int style) { View view = LayoutInflater.from(context).inflate(R.layout.dialogballtrans, null); TextView loadingText = (TextView) view.findViewById(R.id.tv_reminder); if (msg != null && msg != "") { loadingText.setText(msg); } else { loadingText.setText("加载中..."); } return getDialog(context, view, style); } private static Dialog getDialog(Activity context, View view) { mLoadingDialog = new Dialog(context, R.style.ProgressDialog); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.width = 240; // 宽度 lp.height = 240; // 高度 mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } private static Dialog getDialog(Activity context, View view, int style) { mLoadingDialog = new Dialog(context, style); Window dialogWindow = mLoadingDialog.getWindow(); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); dialogWindow.setGravity(Gravity.CENTER); lp.width = 240; // 宽度 lp.height = 240; // 高度 mLoadingDialog.setCancelable(true); mLoadingDialog.setCanceledOnTouchOutside(false); mLoadingDialog.setContentView(view); mLoadingDialog.show(); return mLoadingDialog; } /** * 关闭加载对话框 */ public static void cancelLoading() { if (mLoadingDialog != null) { mLoadingDialog.cancel(); } } }
5,719
0.658027
0.651315
152
34.282894
27.667294
155
false
false
0
0
0
0
0
0
0.730263
false
false
13
da2beeb8b18f8f5376ed1720609b4c62f7793458
11,046,655,922,592
d6446f286dcabd590dc009cb1c493ed6af86dc6a
/src/main/java/com/tico/tico/entities/Comment2Peripheral.java
43518707842fb91eab59fc03b10f4b8ac72780d4
[]
no_license
wuhan2019/nico
https://github.com/wuhan2019/nico
aa95379165939ce217aeabb7263544040b649793
7955e37bad5d144941c11d022ba682deca9e1507
refs/heads/master
2020-05-03T09:48:10.461000
2019-05-13T13:27:13
2019-05-13T13:27:13
178,563,632
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tico.tico.entities; import java.util.Date; public class Comment2Peripheral { public Comment2Peripheral(String comment_peripheral_commentor, String comment_peripheral_commentby, Date comment_peripheral_time, String comment_peripheral_context, double comment_peripheral_mark) { this.comment_peripheral_commentor = comment_peripheral_commentor; this.comment_peripheral_commentby = comment_peripheral_commentby; this.comment_peripheral_time = comment_peripheral_time; this.comment_peripheral_context = comment_peripheral_context; this.comment_peripheral_mark = comment_peripheral_mark; } private String comment_peripheral_commentor; private String comment_peripheral_commentby; private Date comment_peripheral_time; private String comment_peripheral_context; private String comment_peripheral_replyto_name; private double comment_peripheral_mark; public String getComment_peripheral_commentor() { return comment_peripheral_commentor; } public void setComment_peripheral_commentor(String comment_peripheral_commentor) { this.comment_peripheral_commentor = comment_peripheral_commentor; } public String getComment_peripheral_commentby() { return comment_peripheral_commentby; } public void setComment_peripheral_commentby(String comment_peripheral_commentby) { this.comment_peripheral_commentby = comment_peripheral_commentby; } public Date getComment_peripheral_time() { return comment_peripheral_time; } public void setComment_peripheral_time(Date comment_peripheral_time) { this.comment_peripheral_time = comment_peripheral_time; } public String getComment_peripheral_context() { return comment_peripheral_context; } public void setComment_peripheral_context(String comment_peripheral_context) { this.comment_peripheral_context = comment_peripheral_context; } public String getComment_peripheral_replyto_name() { return comment_peripheral_replyto_name; } public void setComment_peripheral_replyto_name(String comment_peripheral_replyto_name) { this.comment_peripheral_replyto_name = comment_peripheral_replyto_name; } public double getComment_peripheral_mark() { return comment_peripheral_mark; } public void setComment_peripheral_mark(int comment_peripheral_mark) { this.comment_peripheral_mark = comment_peripheral_mark; } }
UTF-8
Java
2,516
java
Comment2Peripheral.java
Java
[]
null
[]
package com.tico.tico.entities; import java.util.Date; public class Comment2Peripheral { public Comment2Peripheral(String comment_peripheral_commentor, String comment_peripheral_commentby, Date comment_peripheral_time, String comment_peripheral_context, double comment_peripheral_mark) { this.comment_peripheral_commentor = comment_peripheral_commentor; this.comment_peripheral_commentby = comment_peripheral_commentby; this.comment_peripheral_time = comment_peripheral_time; this.comment_peripheral_context = comment_peripheral_context; this.comment_peripheral_mark = comment_peripheral_mark; } private String comment_peripheral_commentor; private String comment_peripheral_commentby; private Date comment_peripheral_time; private String comment_peripheral_context; private String comment_peripheral_replyto_name; private double comment_peripheral_mark; public String getComment_peripheral_commentor() { return comment_peripheral_commentor; } public void setComment_peripheral_commentor(String comment_peripheral_commentor) { this.comment_peripheral_commentor = comment_peripheral_commentor; } public String getComment_peripheral_commentby() { return comment_peripheral_commentby; } public void setComment_peripheral_commentby(String comment_peripheral_commentby) { this.comment_peripheral_commentby = comment_peripheral_commentby; } public Date getComment_peripheral_time() { return comment_peripheral_time; } public void setComment_peripheral_time(Date comment_peripheral_time) { this.comment_peripheral_time = comment_peripheral_time; } public String getComment_peripheral_context() { return comment_peripheral_context; } public void setComment_peripheral_context(String comment_peripheral_context) { this.comment_peripheral_context = comment_peripheral_context; } public String getComment_peripheral_replyto_name() { return comment_peripheral_replyto_name; } public void setComment_peripheral_replyto_name(String comment_peripheral_replyto_name) { this.comment_peripheral_replyto_name = comment_peripheral_replyto_name; } public double getComment_peripheral_mark() { return comment_peripheral_mark; } public void setComment_peripheral_mark(int comment_peripheral_mark) { this.comment_peripheral_mark = comment_peripheral_mark; } }
2,516
0.736884
0.736089
68
36
36.217888
203
false
false
0
0
0
0
0
0
0.426471
false
false
13
62b5d78edf56fd20c376e84fefb8841de4079690
9,268,539,433,370
4ba291307588bc3522a6117d632ea8cb7b2cc1ba
/liangliang/app/src/main/java/cn/chono/yopper/baidu/overlay/BaiDuOverLay.java
d5a3d18a00d5c447a054e23219855272dfef7485
[]
no_license
439ED537979D8E831561964DBBBD7413/LiaLia
https://github.com/439ED537979D8E831561964DBBBD7413/LiaLia
838cf98c5a737d63ec1d0be7023c0e9750bb232b
6b4f0ad1dbfd4e85240cf51ac1402a5bc6b35bd4
refs/heads/master
2020-04-03T12:58:16.317000
2016-09-12T02:50:21
2016-09-12T02:50:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.chono.yopper.baidu.overlay; import android.app.Dialog; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.InfoWindow; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import cn.chono.yopper.R; import cn.chono.yopper.common.YpSettings; import cn.chono.yopper.data.BubblingList; import cn.chono.yopper.glide.CropCircleTransformation; import cn.chono.yopper.utils.DialogUtil; import cn.chono.yopper.utils.ImgUtils; import cn.chono.yopper.utils.UnitUtil; public class BaiDuOverLay { private LayoutInflater inflater; private Context context; private MapView mapView; private int wigth; private int height; private Dialog dailog; private ImageView typeIcon; private TextView content; private InfoWindow infoWindow; private Marker marKer; private BaiduMap mBaiduMap; private MapStatus mapStatus; private LinearLayout markerView; private BitmapDescriptor bd; private BitmapPool mPool; private CropCircleTransformation transformation; public BaiDuOverLay(Context context) { if (dailog != null) { dailog = null; } recycle(); clearOverlay(); onDestroy(); mPool = null; transformation = null; mPool = Glide.get(context).getBitmapPool(); transformation = new CropCircleTransformation(mPool); this.context = context; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); initView(); initMarkerView(); } @SuppressWarnings("unchecked") public void setBaiDuData(final BubblingList.Location location) { if (location != null) { String typeUrl = location.getTypeImgUrl(); String typeIcoUrl = ImgUtils.DealImageUrl(typeUrl, YpSettings.IMG_SIZE_150, YpSettings.IMG_SIZE_150); Integer locationID = location.getId(); if (locationID == null || locationID <= 0) { typeIcon.setBackgroundResource(R.drawable.discover_type_icon_no); Glide.with(context).load(typeIcoUrl) .into(typeIcon); } else { typeIcon.setBackgroundResource(R.drawable.discover_type_icon); Glide.with(context).load(typeIcoUrl) .bitmapTransform(transformation).into(typeIcon); } content.setText(location.getName()); setBaiDuData(location.getLat(), location.getLng()); } } public void setBaiDuData(double lat, double loc) { LatLng llA = new LatLng(lat, loc); OverlayOptions ooA = new MarkerOptions().position(llA).icon(bd) .zIndex(5).draggable(true); marKer = (Marker) (mBaiduMap.addOverlay(ooA)); LatLng ll = marKer.getPosition(); infoWindow = new InfoWindow( BitmapDescriptorFactory.fromView(markerView), ll, -100, null); mBaiduMap.showInfoWindow(infoWindow); MapStatusUpdate mu = MapStatusUpdateFactory.newLatLng(llA); // 改变地图状态 mBaiduMap.setMapStatus(mu); // // 刷新 // mapView.invalidate(); } /** * 清除所有Overlay * */ public void clearOverlay() { if (mBaiduMap != null) { mBaiduMap.clear(); } } public void showBaiDuOverLay() { if (dailog != null) { dailog.show(); } } public void dismissBaiDuOverLay() { clearOverlay(); if (dailog != null) { dailog.dismiss(); } } /** * MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause() */ public void onPause() { if (mapView != null) { mapView.onPause(); } } /** * MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume() */ public void onResume() { if (mapView != null) { mapView.onResume(); } } /** * MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy() */ public void onDestroy() { if (mapView != null) { mapView.onDestroy(); } recycle(); } public void recycle() { if (bd != null) { bd.recycle(); } } private void initView() { RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate( R.layout.baidu_overlay_layout, null); relativeLayout.getBackground().setAlpha(100); dailog = DialogUtil.hineDialog(context, R.style.MyDialog_NOBG, relativeLayout, Gravity.BOTTOM, R.style.dialogBOT_style); dailog.setCancelable(true); dailog.setCanceledOnTouchOutside(true); mapView = (MapView) relativeLayout.findViewById(R.id.mapView); // 删除百度地图logo mapView.removeViewAt(1); mapView.showScaleControl(false); mapView.showZoomControls(false); wigth = UnitUtil.getScreenWidthPixels(context); height = UnitUtil.getScreenHeightPixels(context); FrameLayout.LayoutParams layoutparams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); layoutparams.width = wigth; layoutparams.height = height; relativeLayout.setLayoutParams(layoutparams); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); int h = height / 3; params.width = wigth; params.height = height - h; params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1); mapView.setLayoutParams(params); mBaiduMap = mapView.getMap(); mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f); mBaiduMap.setMapStatus(msu); bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding); mBaiduMap.getUiSettings().setScrollGesturesEnabled(false); mBaiduMap.getUiSettings().setRotateGesturesEnabled(false); mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false); mBaiduMap.getUiSettings().setAllGesturesEnabled(false); mBaiduMap.getUiSettings().setCompassEnabled(false); mBaiduMap.getUiSettings().setZoomGesturesEnabled(false); relativeLayout.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { dismissBaiDuOverLay(); return false; } }); } private void initMarkerView() { markerView = (LinearLayout) inflater.inflate( R.layout.baidu_overlay_marker_layout, null); typeIcon = (ImageView) markerView.findViewById(R.id.icon); content = (TextView) markerView.findViewById(R.id.content); } }
UTF-8
Java
6,955
java
BaiDuOverLay.java
Java
[]
null
[]
package cn.chono.yopper.baidu.overlay; import android.app.Dialog; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.InfoWindow; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool; import cn.chono.yopper.R; import cn.chono.yopper.common.YpSettings; import cn.chono.yopper.data.BubblingList; import cn.chono.yopper.glide.CropCircleTransformation; import cn.chono.yopper.utils.DialogUtil; import cn.chono.yopper.utils.ImgUtils; import cn.chono.yopper.utils.UnitUtil; public class BaiDuOverLay { private LayoutInflater inflater; private Context context; private MapView mapView; private int wigth; private int height; private Dialog dailog; private ImageView typeIcon; private TextView content; private InfoWindow infoWindow; private Marker marKer; private BaiduMap mBaiduMap; private MapStatus mapStatus; private LinearLayout markerView; private BitmapDescriptor bd; private BitmapPool mPool; private CropCircleTransformation transformation; public BaiDuOverLay(Context context) { if (dailog != null) { dailog = null; } recycle(); clearOverlay(); onDestroy(); mPool = null; transformation = null; mPool = Glide.get(context).getBitmapPool(); transformation = new CropCircleTransformation(mPool); this.context = context; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); initView(); initMarkerView(); } @SuppressWarnings("unchecked") public void setBaiDuData(final BubblingList.Location location) { if (location != null) { String typeUrl = location.getTypeImgUrl(); String typeIcoUrl = ImgUtils.DealImageUrl(typeUrl, YpSettings.IMG_SIZE_150, YpSettings.IMG_SIZE_150); Integer locationID = location.getId(); if (locationID == null || locationID <= 0) { typeIcon.setBackgroundResource(R.drawable.discover_type_icon_no); Glide.with(context).load(typeIcoUrl) .into(typeIcon); } else { typeIcon.setBackgroundResource(R.drawable.discover_type_icon); Glide.with(context).load(typeIcoUrl) .bitmapTransform(transformation).into(typeIcon); } content.setText(location.getName()); setBaiDuData(location.getLat(), location.getLng()); } } public void setBaiDuData(double lat, double loc) { LatLng llA = new LatLng(lat, loc); OverlayOptions ooA = new MarkerOptions().position(llA).icon(bd) .zIndex(5).draggable(true); marKer = (Marker) (mBaiduMap.addOverlay(ooA)); LatLng ll = marKer.getPosition(); infoWindow = new InfoWindow( BitmapDescriptorFactory.fromView(markerView), ll, -100, null); mBaiduMap.showInfoWindow(infoWindow); MapStatusUpdate mu = MapStatusUpdateFactory.newLatLng(llA); // 改变地图状态 mBaiduMap.setMapStatus(mu); // // 刷新 // mapView.invalidate(); } /** * 清除所有Overlay * */ public void clearOverlay() { if (mBaiduMap != null) { mBaiduMap.clear(); } } public void showBaiDuOverLay() { if (dailog != null) { dailog.show(); } } public void dismissBaiDuOverLay() { clearOverlay(); if (dailog != null) { dailog.dismiss(); } } /** * MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause() */ public void onPause() { if (mapView != null) { mapView.onPause(); } } /** * MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume() */ public void onResume() { if (mapView != null) { mapView.onResume(); } } /** * MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy() */ public void onDestroy() { if (mapView != null) { mapView.onDestroy(); } recycle(); } public void recycle() { if (bd != null) { bd.recycle(); } } private void initView() { RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate( R.layout.baidu_overlay_layout, null); relativeLayout.getBackground().setAlpha(100); dailog = DialogUtil.hineDialog(context, R.style.MyDialog_NOBG, relativeLayout, Gravity.BOTTOM, R.style.dialogBOT_style); dailog.setCancelable(true); dailog.setCanceledOnTouchOutside(true); mapView = (MapView) relativeLayout.findViewById(R.id.mapView); // 删除百度地图logo mapView.removeViewAt(1); mapView.showScaleControl(false); mapView.showZoomControls(false); wigth = UnitUtil.getScreenWidthPixels(context); height = UnitUtil.getScreenHeightPixels(context); FrameLayout.LayoutParams layoutparams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); layoutparams.width = wigth; layoutparams.height = height; relativeLayout.setLayoutParams(layoutparams); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); int h = height / 3; params.width = wigth; params.height = height - h; params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1); mapView.setLayoutParams(params); mBaiduMap = mapView.getMap(); mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f); mBaiduMap.setMapStatus(msu); bd = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding); mBaiduMap.getUiSettings().setScrollGesturesEnabled(false); mBaiduMap.getUiSettings().setRotateGesturesEnabled(false); mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false); mBaiduMap.getUiSettings().setAllGesturesEnabled(false); mBaiduMap.getUiSettings().setCompassEnabled(false); mBaiduMap.getUiSettings().setZoomGesturesEnabled(false); relativeLayout.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { dismissBaiDuOverLay(); return false; } }); } private void initMarkerView() { markerView = (LinearLayout) inflater.inflate( R.layout.baidu_overlay_marker_layout, null); typeIcon = (ImageView) markerView.findViewById(R.id.icon); content = (TextView) markerView.findViewById(R.id.content); } }
6,955
0.746592
0.743661
273
23.992674
21.288012
71
false
false
0
0
0
0
0
0
1.827839
false
false
13
28100255cf8a8649d3516335a58d6119e5637fd9
7,971,459,335,581
b4db2a108ff0322956d336a87a385c0560089ca9
/cloud24/cloud24-sage-servicecomb/omega-order-service/src/main/java/com/el/cloud/dao/OrderDao.java
dc44a80d2e865683cb50c3052dfedc0138ad1551
[]
no_license
rmzf9192/spring-cloud-code
https://github.com/rmzf9192/spring-cloud-code
26345472631a8d80ff9ea3c77444b87d0d43d277
aa9118ad8ce91d490d30642b84ed18c672435cf0
refs/heads/master
2021-01-04T11:01:05.668000
2020-03-06T07:46:55
2020-03-06T07:46:55
240,516,318
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.el.cloud.dao; import com.el.cloud.domain.UserOrder; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Roman.Zhang * @date 2020/3/6 * @description: */ public interface OrderDao extends JpaRepository<UserOrder, Integer> { UserOrder findByTxId(String txId); }
UTF-8
Java
305
java
OrderDao.java
Java
[ { "context": "data.jpa.repository.JpaRepository;\n\n/**\n * @author Roman.Zhang\n * @date 2020/3/6\n * @description:\n */\npublic int", "end": 154, "score": 0.9997755289077759, "start": 143, "tag": "NAME", "value": "Roman.Zhang" } ]
null
[]
package com.el.cloud.dao; import com.el.cloud.domain.UserOrder; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Roman.Zhang * @date 2020/3/6 * @description: */ public interface OrderDao extends JpaRepository<UserOrder, Integer> { UserOrder findByTxId(String txId); }
305
0.754098
0.734426
13
22.461538
22.204002
69
false
false
0
0
0
0
0
0
0.384615
false
false
13
69c96e791dd537d06446b05a12107f3ccd89a232
15,642,270,931,851
09045386f5a89a7da48787b9a32fe7bfc7149686
/src/Tirta_Maju_Abadi/View/PO_penjualan.java
8960c69ac05797a32f174393a1c4d632281eab16
[]
no_license
bangdolla08/Tirta_Maju_Abadi
https://github.com/bangdolla08/Tirta_Maju_Abadi
41b517997ecd605c7a876f139e41adf37b436e5a
376d5da77fc2b0ac82d584ec02d013f68e75ffaf
refs/heads/master
2021-01-23T08:38:36.323000
2015-12-09T18:07:20
2015-12-09T18:07:20
42,907,277
0
1
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 Tirta_Maju_Abadi.View; import Tirta_Maju_Abadi.DataModel.MD_Full_Bo_barang; import Tirta_Maju_Abadi.DataModel.MD_Full_penjualan; import Tirta_Maju_Abadi.DataModel.MD_Pelanggan; import Tirta_Maju_Abadi.DataModel.MD_Penjualan_po; import Tirta_Maju_Abadi.DataModel.MD_Produk; import Tirta_Maju_Abadi.DataModel.list2Values; import Tirta_Maju_Abadi.DataModel.listMD_Penjualan_po; import Tirta_Maju_Abadi.View.ModelSwing.ModelChuser; import Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt; import Tirta_Maju_Abadi.View.evetView.View_penjualan_po; import Tirta_Maju_Abadi.toll.database; import Tirta_Maju_Abadi.toll.loadAllData; import java.awt.Dimension; import java.awt.Toolkit; import java.util.ArrayList; import java.util.Date; import java.util.List; import Tirta_Maju_Abadi.View.Pencarian_pelanggan; import Tirta_Maju_Abadi.DataModel.listMD_Pegawai; import Tirta_Maju_Abadi.DataModel.MD_Pegawai; import static Tirta_Maju_Abadi.View.Penjualan_depo.convertUtilDateToSqlDate; import Tirta_Maju_Abadi.View.evetView.view_penjualan_depo; /** * * @author NEEZAR */ public class PO_penjualan extends javax.swing.JInternalFrame { private MD_Penjualan_po mpel=new MD_Penjualan_po(); private View_penjualan_po vpp; private database db; private listMD_Penjualan_po lppo; private MD_Pelanggan pelanggan=new MD_Pelanggan(); private Date date=new Date(); private loadAllData ld; private MD_Full_penjualan m_depo; private MD_Pegawai m_pegawai; /** * Creates new form PO_penjualan */ public PO_penjualan(database db,loadAllData ld) { initComponents(); this.m_depo=m_depo; f_total.setText(0); this.db=db; this.ld=ld; vpp=new View_penjualan_po(t_penjualan.getModel(), m_depo, db,ld,pelanggan,mpel ); reset(); t_penjualan.setModel(vpp.getdtm()); } public void setlist(){ for(MD_Produk mp:ld.getListMD_Produk().getAll()){ c_nm_produk.addItem(mp); } } public void setlistMarketing(){ for(MD_Pegawai m_pegawai:ld.getListMD_Pegawai().getListMarketing()){ c_id_marketing.addItem(m_pegawai); } } public void reset(){ setlistMarketing(); setlist(); vpp.reset_notadanpo(); f_no_po.setText(vpp.getReset_po()); f_nm_pelanggan.setText(""); d_tanggal_po.setDate(null); f_banyak.setText(""); f_total.setText(""); ngesetTgl(); } public void ngesetTgl(){ Date date = new Date(); d_tanggal_po.setDate(date); } private void panggil_pelanggan(){ Pencarian_pelanggan pen=new Pencarian_pelanggan(this); pen.setVisible(true); pen.requestFocus(true); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - pen.getWidth()) / 2); int y = (int) ((dimension.getHeight() - pen.getHeight()) / 2); pen.setLocation(x, y); getParent().add(pen); pen.moveToFront(); } public void list(modelTextFilt mtf){ List<list2Values> list=new ArrayList<>(); for(MD_Pelanggan mp:ld.getListMD_Pelanggan().getAll()){ list.add(new list2Values(mp.getNama(), mp.getId_Pelanggan())); } mtf.setText(list); } public MD_Full_penjualan setPenjualan_depo(){ String no_po=f_no_po.getText(); int bnyk=f_banyak.getInteger(); MD_Produk tmpMP=(MD_Produk)c_nm_produk.getSelectedItem(); return new MD_Full_penjualan(tmpMP, bnyk, no_po, ld); } private void setMpel(){ MD_Pegawai mppeg=(MD_Pegawai)c_id_marketing.getSelectedItem(); //mpel.setId_marketing(mppeg); mpel.setNo_nota(f_no_po.getText()); mpel.setNo_po(f_no_po.getText()); mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); mpel.setId_marketing(c_id_marketing.getSelectedIndex()); mpel.setTanggalpesan(convertUtilDateToSqlDate(d_tanggal_po.getDate())); } // private MD_Penjualan_po setMpelpo(){ // MD_Pegawai mppeg=(MD_Pegawai)c_id_marketing.getSelectedItem(); // //mpel.setId_marketing(mppeg); //// mpel.setNo_nota(f_no_po.getText()); //// mpel.setNo_po(f_no_po.getText()); //// mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); // mpel.setTanggalpesan(convertUtilDateToSqlDate(d_tanggal_po.getDate())); // MD_Pegawai mdpeg=(MD_Pegawai) c_id_marketing.getSelectedItem(); // String no_po=f_no_po.getText(); // String no_nota=f_no_po.getText(); // return new MD_Penjualan_po(HIDE_ON_CLOSE, no_nota, no_po, date, HIDE_ON_CLOSE, db, ld); // } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); l_nm_pelanggan = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); d_tanggal_po = new com.toedter.calendar.JDateChooser(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); l_banyak = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); t_penjualan = new javax.swing.JTable(); jLabel6 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); f_total = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); c_nm_produk = new Tirta_Maju_Abadi.View.ModelSwing.ModelChuser(); f_banyak = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); jLabel2 = new javax.swing.JLabel(); f_no_po = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); f_nm_pelanggan = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); c_id_marketing = new Tirta_Maju_Abadi.View.ModelSwing.ModelChuser(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4), "PO Penjualan", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 0))); // NOI18N jLabel1.setText("No PO"); l_nm_pelanggan.setText("Nama Pelanggan"); jLabel3.setText("Tanggal PO"); d_tanggal_po.setDate(date); d_tanggal_po.setDateFormatString("dd-MM-yyyy"); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4), "Tabel Penjualan", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 0))); // NOI18N jLabel4.setText("Nama Produk"); l_banyak.setText("Banyak"); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/tambah.png"))); // NOI18N jButton1.setText("Tambah"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); t_penjualan.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "No", "Nama Produk", "Banyak", "Harga", "Total" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); t_penjualan.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(t_penjualan); if (t_penjualan.getColumnModel().getColumnCount() > 0) { t_penjualan.getColumnModel().getColumn(0).setResizable(false); t_penjualan.getColumnModel().getColumn(0).setPreferredWidth(1); t_penjualan.getColumnModel().getColumn(1).setResizable(false); t_penjualan.getColumnModel().getColumn(1).setPreferredWidth(150); t_penjualan.getColumnModel().getColumn(2).setResizable(false); t_penjualan.getColumnModel().getColumn(3).setResizable(false); t_penjualan.getColumnModel().getColumn(4).setResizable(false); } jLabel6.setText("Total"); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/pesan.png"))); // NOI18N jButton2.setText("Pesan"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/Reset.png"))); // NOI18N jButton3.setText("Reset"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(c_nm_produk, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(l_banyak) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(f_banyak, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE) .addComponent(f_total, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(l_banyak) .addComponent(jButton1) .addComponent(c_nm_produk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(f_banyak, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(f_total, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel2.setText("Id Marketing"); f_nm_pelanggan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { f_nm_pelangganMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(l_nm_pelanggan) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(d_tanggal_po, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addComponent(f_no_po, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(f_nm_pelanggan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(c_id_marketing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(c_id_marketing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(f_no_po, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(l_nm_pelanggan) .addComponent(f_nm_pelanggan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(d_tanggal_po, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: setPenjualan_depo(); setMpel(); vpp.simpanpenjulanpo(); reset(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: tambahno(); }//GEN-LAST:event_jButton1ActionPerformed private void f_nm_pelangganMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_f_nm_pelangganMouseClicked // TODO add your handling code here: panggil_pelanggan(); }//GEN-LAST:event_f_nm_pelangganMouseClicked public void tambahno(){ MD_Produk tmpMP=(MD_Produk)c_nm_produk.getSelectedItem(); int bannyak=f_banyak.getInteger(); int harga=ld.getListMD_Harga_pelanggan().getByIDAndProduk(mpel.getId_pelanggan(),tmpMP.getId_produk()).getHarga(); MD_Full_penjualan mfp=new MD_Full_penjualan(tmpMP, bannyak,f_no_po.getString(), ld); vpp.set_TableBawah(mfp,pelanggan.getId_Pelanggan()); f_total.setText(harga*bannyak); } // Variables declaration - do not modify//GEN-BEGIN:variables private Tirta_Maju_Abadi.View.ModelSwing.ModelChuser c_id_marketing; private Tirta_Maju_Abadi.View.ModelSwing.ModelChuser c_nm_produk; private com.toedter.calendar.JDateChooser d_tanggal_po; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_banyak; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_nm_pelanggan; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_no_po; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_total; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel l_banyak; private javax.swing.JLabel l_nm_pelanggan; private javax.swing.JTable t_penjualan; // End of variables declaration//GEN-END:variables void tttt(MD_Pelanggan msdp) { pelanggan=msdp; //System.out.println(lad.getListMD_Harga_pelanggan().getByIDAndProduk(mp.getId_Pelanggan(),3).getHarga()); mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); mpel.setPel(pelanggan); pelanggan=msdp; f_nm_pelanggan.setText(msdp); } }
UTF-8
Java
21,640
java
PO_penjualan.java
Java
[ { "context": "w.evetView.view_penjualan_depo;\n\n/**\n *\n * @author NEEZAR\n */\npublic class PO_penjualan extends javax.swing", "end": 1248, "score": 0.8106660842895508, "start": 1242, "tag": "NAME", "value": "NEEZAR" } ]
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 Tirta_Maju_Abadi.View; import Tirta_Maju_Abadi.DataModel.MD_Full_Bo_barang; import Tirta_Maju_Abadi.DataModel.MD_Full_penjualan; import Tirta_Maju_Abadi.DataModel.MD_Pelanggan; import Tirta_Maju_Abadi.DataModel.MD_Penjualan_po; import Tirta_Maju_Abadi.DataModel.MD_Produk; import Tirta_Maju_Abadi.DataModel.list2Values; import Tirta_Maju_Abadi.DataModel.listMD_Penjualan_po; import Tirta_Maju_Abadi.View.ModelSwing.ModelChuser; import Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt; import Tirta_Maju_Abadi.View.evetView.View_penjualan_po; import Tirta_Maju_Abadi.toll.database; import Tirta_Maju_Abadi.toll.loadAllData; import java.awt.Dimension; import java.awt.Toolkit; import java.util.ArrayList; import java.util.Date; import java.util.List; import Tirta_Maju_Abadi.View.Pencarian_pelanggan; import Tirta_Maju_Abadi.DataModel.listMD_Pegawai; import Tirta_Maju_Abadi.DataModel.MD_Pegawai; import static Tirta_Maju_Abadi.View.Penjualan_depo.convertUtilDateToSqlDate; import Tirta_Maju_Abadi.View.evetView.view_penjualan_depo; /** * * @author NEEZAR */ public class PO_penjualan extends javax.swing.JInternalFrame { private MD_Penjualan_po mpel=new MD_Penjualan_po(); private View_penjualan_po vpp; private database db; private listMD_Penjualan_po lppo; private MD_Pelanggan pelanggan=new MD_Pelanggan(); private Date date=new Date(); private loadAllData ld; private MD_Full_penjualan m_depo; private MD_Pegawai m_pegawai; /** * Creates new form PO_penjualan */ public PO_penjualan(database db,loadAllData ld) { initComponents(); this.m_depo=m_depo; f_total.setText(0); this.db=db; this.ld=ld; vpp=new View_penjualan_po(t_penjualan.getModel(), m_depo, db,ld,pelanggan,mpel ); reset(); t_penjualan.setModel(vpp.getdtm()); } public void setlist(){ for(MD_Produk mp:ld.getListMD_Produk().getAll()){ c_nm_produk.addItem(mp); } } public void setlistMarketing(){ for(MD_Pegawai m_pegawai:ld.getListMD_Pegawai().getListMarketing()){ c_id_marketing.addItem(m_pegawai); } } public void reset(){ setlistMarketing(); setlist(); vpp.reset_notadanpo(); f_no_po.setText(vpp.getReset_po()); f_nm_pelanggan.setText(""); d_tanggal_po.setDate(null); f_banyak.setText(""); f_total.setText(""); ngesetTgl(); } public void ngesetTgl(){ Date date = new Date(); d_tanggal_po.setDate(date); } private void panggil_pelanggan(){ Pencarian_pelanggan pen=new Pencarian_pelanggan(this); pen.setVisible(true); pen.requestFocus(true); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - pen.getWidth()) / 2); int y = (int) ((dimension.getHeight() - pen.getHeight()) / 2); pen.setLocation(x, y); getParent().add(pen); pen.moveToFront(); } public void list(modelTextFilt mtf){ List<list2Values> list=new ArrayList<>(); for(MD_Pelanggan mp:ld.getListMD_Pelanggan().getAll()){ list.add(new list2Values(mp.getNama(), mp.getId_Pelanggan())); } mtf.setText(list); } public MD_Full_penjualan setPenjualan_depo(){ String no_po=f_no_po.getText(); int bnyk=f_banyak.getInteger(); MD_Produk tmpMP=(MD_Produk)c_nm_produk.getSelectedItem(); return new MD_Full_penjualan(tmpMP, bnyk, no_po, ld); } private void setMpel(){ MD_Pegawai mppeg=(MD_Pegawai)c_id_marketing.getSelectedItem(); //mpel.setId_marketing(mppeg); mpel.setNo_nota(f_no_po.getText()); mpel.setNo_po(f_no_po.getText()); mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); mpel.setId_marketing(c_id_marketing.getSelectedIndex()); mpel.setTanggalpesan(convertUtilDateToSqlDate(d_tanggal_po.getDate())); } // private MD_Penjualan_po setMpelpo(){ // MD_Pegawai mppeg=(MD_Pegawai)c_id_marketing.getSelectedItem(); // //mpel.setId_marketing(mppeg); //// mpel.setNo_nota(f_no_po.getText()); //// mpel.setNo_po(f_no_po.getText()); //// mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); // mpel.setTanggalpesan(convertUtilDateToSqlDate(d_tanggal_po.getDate())); // MD_Pegawai mdpeg=(MD_Pegawai) c_id_marketing.getSelectedItem(); // String no_po=f_no_po.getText(); // String no_nota=f_no_po.getText(); // return new MD_Penjualan_po(HIDE_ON_CLOSE, no_nota, no_po, date, HIDE_ON_CLOSE, db, ld); // } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); l_nm_pelanggan = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); d_tanggal_po = new com.toedter.calendar.JDateChooser(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); l_banyak = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); t_penjualan = new javax.swing.JTable(); jLabel6 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); f_total = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); c_nm_produk = new Tirta_Maju_Abadi.View.ModelSwing.ModelChuser(); f_banyak = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); jLabel2 = new javax.swing.JLabel(); f_no_po = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); f_nm_pelanggan = new Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt(); c_id_marketing = new Tirta_Maju_Abadi.View.ModelSwing.ModelChuser(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4), "PO Penjualan", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 0))); // NOI18N jLabel1.setText("No PO"); l_nm_pelanggan.setText("Nama Pelanggan"); jLabel3.setText("Tanggal PO"); d_tanggal_po.setDate(date); d_tanggal_po.setDateFormatString("dd-MM-yyyy"); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4), "Tabel Penjualan", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(153, 0, 0))); // NOI18N jLabel4.setText("Nama Produk"); l_banyak.setText("Banyak"); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/tambah.png"))); // NOI18N jButton1.setText("Tambah"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); t_penjualan.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "No", "Nama Produk", "Banyak", "Harga", "Total" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); t_penjualan.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(t_penjualan); if (t_penjualan.getColumnModel().getColumnCount() > 0) { t_penjualan.getColumnModel().getColumn(0).setResizable(false); t_penjualan.getColumnModel().getColumn(0).setPreferredWidth(1); t_penjualan.getColumnModel().getColumn(1).setResizable(false); t_penjualan.getColumnModel().getColumn(1).setPreferredWidth(150); t_penjualan.getColumnModel().getColumn(2).setResizable(false); t_penjualan.getColumnModel().getColumn(3).setResizable(false); t_penjualan.getColumnModel().getColumn(4).setResizable(false); } jLabel6.setText("Total"); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/pesan.png"))); // NOI18N jButton2.setText("Pesan"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Tirta_Maju_Abadi/Images/Reset.png"))); // NOI18N jButton3.setText("Reset"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(c_nm_produk, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(l_banyak) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(f_banyak, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE) .addComponent(f_total, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(l_banyak) .addComponent(jButton1) .addComponent(c_nm_produk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(f_banyak, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(f_total, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel2.setText("Id Marketing"); f_nm_pelanggan.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { f_nm_pelangganMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(l_nm_pelanggan) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(d_tanggal_po, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE) .addComponent(f_no_po, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(f_nm_pelanggan, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(c_id_marketing, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(6, 6, 6) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(c_id_marketing, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(f_no_po, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(l_nm_pelanggan) .addComponent(f_nm_pelanggan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(d_tanggal_po, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: setPenjualan_depo(); setMpel(); vpp.simpanpenjulanpo(); reset(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: tambahno(); }//GEN-LAST:event_jButton1ActionPerformed private void f_nm_pelangganMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_f_nm_pelangganMouseClicked // TODO add your handling code here: panggil_pelanggan(); }//GEN-LAST:event_f_nm_pelangganMouseClicked public void tambahno(){ MD_Produk tmpMP=(MD_Produk)c_nm_produk.getSelectedItem(); int bannyak=f_banyak.getInteger(); int harga=ld.getListMD_Harga_pelanggan().getByIDAndProduk(mpel.getId_pelanggan(),tmpMP.getId_produk()).getHarga(); MD_Full_penjualan mfp=new MD_Full_penjualan(tmpMP, bannyak,f_no_po.getString(), ld); vpp.set_TableBawah(mfp,pelanggan.getId_Pelanggan()); f_total.setText(harga*bannyak); } // Variables declaration - do not modify//GEN-BEGIN:variables private Tirta_Maju_Abadi.View.ModelSwing.ModelChuser c_id_marketing; private Tirta_Maju_Abadi.View.ModelSwing.ModelChuser c_nm_produk; private com.toedter.calendar.JDateChooser d_tanggal_po; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_banyak; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_nm_pelanggan; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_no_po; private Tirta_Maju_Abadi.View.ModelSwing.modelTextFilt f_total; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel l_banyak; private javax.swing.JLabel l_nm_pelanggan; private javax.swing.JTable t_penjualan; // End of variables declaration//GEN-END:variables void tttt(MD_Pelanggan msdp) { pelanggan=msdp; //System.out.println(lad.getListMD_Harga_pelanggan().getByIDAndProduk(mp.getId_Pelanggan(),3).getHarga()); mpel.setId_pelanggan(pelanggan.getId_Pelanggan()); mpel.setPel(pelanggan); pelanggan=msdp; f_nm_pelanggan.setText(msdp); } }
21,640
0.655545
0.646303
419
50.646778
41.848793
349
false
false
0
0
0
0
0
0
0.854415
false
false
13
0187de8c9f671bbcba06bc255b510ad4296f71f4
7,060,926,259,791
d84b75004fb0118a393f567b272c1ee445866e26
/代码包/速运快递第十五天/完整可运行速运快递项目/bos_parent/bos_web/src/main/java/com/itheima/action/RoleAction.java
4ee65a2704559915ef1e07325cf1c7ea7160fe12
[]
no_license
yourbigbro/sshsrepository
https://github.com/yourbigbro/sshsrepository
840fc7ecddc75a76228ef37184fce5503ef20f96
ddb461b608c3eb39b58a5cc000205ef960a6d9a9
refs/heads/master
2021-08-22T16:28:10.931000
2017-11-30T17:05:17
2017-11-30T17:05:26
109,405,119
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itheima.action; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.itheima.service.PermissionService; import com.itheima.service.RoleService; import com.itheima.system.Permission; import com.itheima.system.Role; import com.itheima.utils.action.common.CommonAction; public class RoleAction extends CommonAction<Role>{ @Autowired private RoleService roleService; //该方法用于展示所有的角色role。他是不用跳转页面的,因为就是回到原来的页面 @Action("listAllRole") public String listAllRole(){ List<Role> list=roleService.findAll(); this.java2json(list, new String[]{"users","permissions","menus"}); return NONE; } //用属性驱动的方式获得前台传来的复选框选中项。前台可以传递数组或字符串 //注意,属性内部是Integer,不用写成String。前台原来是String,估计是后台可以自动转换 private Integer[] permissionIds; private String functionIds; public void setPermissionIds(Integer[] permissionIds) { this.permissionIds = permissionIds; } public void setFunctionIds(String functionIds) { this.functionIds = functionIds; } @Autowired private PermissionService permissionService; //该方法用于保存新添加的角色(保存完之后返回原来的页面以便进行重新展示更新之后的数据库) @Action(value="saveRole",results={@Result(name="success",type="redirect",location="/pages/system/role.html")}) //虽然saveRole()方法里面包含的方法有参数,但是saveRole()方法是不能有参数的 public String saveRole(){ //业务逻辑必须交由service层来处理,因为涉及到事务。在action层处理既不合逻辑又无法进行事务操作 roleService.saveRole(model,permissionIds,functionIds); return SUCCESS; } }
UTF-8
Java
1,964
java
RoleAction.java
Java
[]
null
[]
package com.itheima.action; import java.util.List; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import com.itheima.service.PermissionService; import com.itheima.service.RoleService; import com.itheima.system.Permission; import com.itheima.system.Role; import com.itheima.utils.action.common.CommonAction; public class RoleAction extends CommonAction<Role>{ @Autowired private RoleService roleService; //该方法用于展示所有的角色role。他是不用跳转页面的,因为就是回到原来的页面 @Action("listAllRole") public String listAllRole(){ List<Role> list=roleService.findAll(); this.java2json(list, new String[]{"users","permissions","menus"}); return NONE; } //用属性驱动的方式获得前台传来的复选框选中项。前台可以传递数组或字符串 //注意,属性内部是Integer,不用写成String。前台原来是String,估计是后台可以自动转换 private Integer[] permissionIds; private String functionIds; public void setPermissionIds(Integer[] permissionIds) { this.permissionIds = permissionIds; } public void setFunctionIds(String functionIds) { this.functionIds = functionIds; } @Autowired private PermissionService permissionService; //该方法用于保存新添加的角色(保存完之后返回原来的页面以便进行重新展示更新之后的数据库) @Action(value="saveRole",results={@Result(name="success",type="redirect",location="/pages/system/role.html")}) //虽然saveRole()方法里面包含的方法有参数,但是saveRole()方法是不能有参数的 public String saveRole(){ //业务逻辑必须交由service层来处理,因为涉及到事务。在action层处理既不合逻辑又无法进行事务操作 roleService.saveRole(model,permissionIds,functionIds); return SUCCESS; } }
1,964
0.792793
0.790862
56
26.75
24.348108
111
false
false
0
0
0
0
0
0
1.375
false
false
13
e37afedf6a887974c1866fa58ba19ddddd7c8664
17,454,747,123,417
ca2b72ad4c5a853ab519cc590204260002c83381
/java/FinalProject/src/com/lec/report/ReportDao.java
baf612acfbb45a240db0be007962224639aa49b9
[]
no_license
nvmr6/BIGDATA
https://github.com/nvmr6/BIGDATA
b431100b3969c53d5f9438380bce00ec27172e01
79ec5389cec876353956f9623444a710857b34d9
refs/heads/main
2023-04-23T06:22:21.872000
2021-05-09T03:33:13
2021-05-09T03:33:13
317,541,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lec.report; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; public class ReportDao { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; public static final int SUCCESS = 1; public static final int FAIL = 0; private static ReportDao INSTANCE; public static ReportDao getInstance() { if (INSTANCE == null) { INSTANCE = new ReportDao(); } return INSTANCE; } private ReportDao() { try { Class.forName(driver); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } } // 1번 public ReportDto selectSno(String sno) { ReportDto person = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT SNO, SNAME, MNAME, SCORE FROM STUDENT S, MAJOR M WHERE S.MNO=M.MNO AND SNO= ?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sno); rs = pstmt.executeQuery(); while (rs.next()) { String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); person = new ReportDto(sno, sname, mname, score); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return person; } // 2번 public ArrayList<ReportDto> selectSname(String sname) { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT SNO, SNAME, MNAME, SCORE FROM STUDENT S, MAJOR M WHERE S.MNO=M.MNO AND SNAME=?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sname); rs = pstmt.executeQuery(); while (rs.next()) { String sno = rs.getString("sno"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(sno, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 3번 public ArrayList<ReportDto> selectMname(String mname) { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND M.MNAME = ? ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, mname); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 4번 public int insertReport(ReportDto dto) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "INSERT INTO STUDENT VALUES ( TO_CHAR(SYSDATE, 'YYYY')||" + "TRIM(TO_CHAR(SEQ_STUDENT.NEXTVAL,'000')), ?, (SELECT MNO FROM MAJOR WHERE MNAME = ?), ?, ?)"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, dto.getSname()); pstmt.setString(2, dto.getMname()); pstmt.setInt(3, dto.getScore()); pstmt.setInt(4, dto.getSexpel()); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } // 5번 public int updateReport(String sno, String sname, String mname, int score) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "UPDATE STUDENT SET SNAME=?, MNO=(SELECT MNO FROM MAJOR WHERE MNAME=?), "+ "SCORE = ? WHERE SNO=?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sname); pstmt.setString(2, mname); pstmt.setInt(3, score); pstmt.setString(4, sno); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } // 6번 public ArrayList<ReportDto> selectUnexpel() { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND SEXPEL = 0 ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 7번 public ArrayList<ReportDto> selectExpel() { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND SEXPEL = 1 ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 8번 public int updateExpel(String sno) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "UPDATE STUDENT SET SEXPEL = 1 WHERE SNO= ?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sno); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } public Vector<String> mnameList() { Vector<String> mnames = new Vector<String>(); mnames.add(""); // 학과 리스트 add String sql = "SELECT MNAME FROM MAJOR"; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { mnames.add(rs.getString("mname")); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return mnames; } }
UHC
Java
9,438
java
ReportDao.java
Java
[ { "context": ".OracleDriver\";\r\n\tString url = \"jdbc:oracle:thin:@127.0.0.1:1521:xe\";\r\n\tpublic static final int SUCCESS = 1;\r", "end": 361, "score": 0.9996951222419739, "start": 352, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ry {\r\n\t\t\tconn = DriverManager.getConnection(url, \"scott\", \"tiger\");\r\n\t\t\tpstmt = conn.prepareStatement(sql", "end": 3281, "score": 0.6555965542793274, "start": 3276, "tag": "NAME", "value": "scott" }, { "context": "ry {\r\n\t\t\tconn = DriverManager.getConnection(url, \"scott\", \"tiger\");\r\n\t\t\tpstmt = conn.prepareStatement(sql", "end": 4295, "score": 0.5958139896392822, "start": 4290, "tag": "NAME", "value": "scott" } ]
null
[]
package com.lec.report; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Vector; public class ReportDao { String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe"; public static final int SUCCESS = 1; public static final int FAIL = 0; private static ReportDao INSTANCE; public static ReportDao getInstance() { if (INSTANCE == null) { INSTANCE = new ReportDao(); } return INSTANCE; } private ReportDao() { try { Class.forName(driver); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } } // 1번 public ReportDto selectSno(String sno) { ReportDto person = null; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT SNO, SNAME, MNAME, SCORE FROM STUDENT S, MAJOR M WHERE S.MNO=M.MNO AND SNO= ?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sno); rs = pstmt.executeQuery(); while (rs.next()) { String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); person = new ReportDto(sno, sname, mname, score); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return person; } // 2번 public ArrayList<ReportDto> selectSname(String sname) { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT SNO, SNAME, MNAME, SCORE FROM STUDENT S, MAJOR M WHERE S.MNO=M.MNO AND SNAME=?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sname); rs = pstmt.executeQuery(); while (rs.next()) { String sno = rs.getString("sno"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(sno, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 3번 public ArrayList<ReportDto> selectMname(String mname) { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND M.MNAME = ? ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, mname); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 4번 public int insertReport(ReportDto dto) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "INSERT INTO STUDENT VALUES ( TO_CHAR(SYSDATE, 'YYYY')||" + "TRIM(TO_CHAR(SEQ_STUDENT.NEXTVAL,'000')), ?, (SELECT MNO FROM MAJOR WHERE MNAME = ?), ?, ?)"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, dto.getSname()); pstmt.setString(2, dto.getMname()); pstmt.setInt(3, dto.getScore()); pstmt.setInt(4, dto.getSexpel()); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } // 5번 public int updateReport(String sno, String sname, String mname, int score) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "UPDATE STUDENT SET SNAME=?, MNO=(SELECT MNO FROM MAJOR WHERE MNAME=?), "+ "SCORE = ? WHERE SNO=?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sname); pstmt.setString(2, mname); pstmt.setInt(3, score); pstmt.setString(4, sno); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } // 6번 public ArrayList<ReportDto> selectUnexpel() { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND SEXPEL = 0 ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 7번 public ArrayList<ReportDto> selectExpel() { ArrayList<ReportDto> dtos = new ArrayList<ReportDto>(); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = "SELECT ROWNUM RANK, T.* FROM(SELECT SNAME||'('||SNO||')' SNAME, MNAME||'('||S.MNO||')' MNAME, SCORE FROM STUDENT S, MAJOR M " + "WHERE S.MNO = M.MNO AND SEXPEL = 1 ORDER BY SCORE DESC) T"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { int rank = rs.getInt("rank"); String sname = rs.getString("sname"); String mname = rs.getString("mname"); int score = rs.getInt("score"); dtos.add(new ReportDto(rank, sname, mname, score)); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return dtos; } // 8번 public int updateExpel(String sno) { int result = FAIL; Connection conn = null; PreparedStatement pstmt = null; String sql = "UPDATE STUDENT SET SEXPEL = 1 WHERE SNO= ?"; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); pstmt.setString(1, sno); result = pstmt.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return result; } public Vector<String> mnameList() { Vector<String> mnames = new Vector<String>(); mnames.add(""); // 학과 리스트 add String sql = "SELECT MNAME FROM MAJOR"; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection(url, "scott", "tiger"); pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { mnames.add(rs.getString("mname")); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } return mnames; } }
9,438
0.601997
0.59796
325
26.959999
21.254103
141
false
false
0
0
0
0
0
0
3.707692
false
false
13
5ae06e0f199ad3621bbab0a234e9431ed4334195
12,635,793,833,383
835d1a4f1c721450d9072fe5afd9f3b2079d4752
/src/main/java/com/baidu/phoenix/alibaba/PaymentRemoteService.java
2cf799986e549a05b698b9dac2d66104d7eeb3d6
[]
no_license
phoenixJu/summer
https://github.com/phoenixJu/summer
00ee902d34d2efedeb715b903facaa99f9906ff7
995c751790cc20cf04042c2dfa1770c8ffbdc06a
refs/heads/master
2021-01-20T07:51:13.996000
2019-09-25T06:54:33
2019-09-25T06:54:33
39,489,255
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.baidu.phoenix.alibaba; import com.baidu.phoenix.alibaba.bean.ConsultResult; /** * PaymentRemoteService * * @author sprzhing * @date 2018/7/25 * @description payment available query service */ public interface PaymentRemoteService { // 这是一个远程可被调用的接口 ConsultResult isEnabled(Long ucId, String paymentType); }
UTF-8
Java
360
java
PaymentRemoteService.java
Java
[ { "context": "Result;\n\n/**\n * PaymentRemoteService\n *\n * @author sprzhing\n * @date 2018/7/25\n * @description payment availa", "end": 140, "score": 0.9995954036712646, "start": 132, "tag": "USERNAME", "value": "sprzhing" } ]
null
[]
package com.baidu.phoenix.alibaba; import com.baidu.phoenix.alibaba.bean.ConsultResult; /** * PaymentRemoteService * * @author sprzhing * @date 2018/7/25 * @description payment available query service */ public interface PaymentRemoteService { // 这是一个远程可被调用的接口 ConsultResult isEnabled(Long ucId, String paymentType); }
360
0.757485
0.736527
15
21.333334
19.801235
59
false
false
0
0
0
0
0
0
0.266667
false
false
13
a0befdc92efb4a3a122b87a697cbd5a915fe0101
17,798,344,515,267
6efb636686257daeeffc5767f3b0a7352bedf681
/filter_listener/src/cn/itcast/web/servlet/ServletDemo1.java
66610116a01735f60bedac74d6283e2a8cd54b54
[]
no_license
DAZHAdazha/JavaWeb-learning-path
https://github.com/DAZHAdazha/JavaWeb-learning-path
e48baa2408efeef10d0d785d65126ca9923a42c3
fa852e598eee9f673fb655016ad038e2382fa5d4
refs/heads/master
2023-03-31T03:41:11.600000
2021-03-31T14:33:41
2021-03-31T14:33:41
336,293,576
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.itcast.web.servlet; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/user/findAllServlet") public class ServletDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("findServlet..."); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
UTF-8
Java
606
java
ServletDemo1.java
Java
[]
null
[]
package cn.itcast.web.servlet; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/user/findAllServlet") public class ServletDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("findServlet..."); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
606
0.757426
0.755776
19
30.894737
34.62566
122
false
false
0
0
0
0
0
0
0.631579
false
false
13
0f2ec0635eb8d8cec351436207dce2a87c3f367f
7,430,293,464,834
1226e71eb0341765a2fddf6e00b9239095d44ad9
/src/main/java/com/guo/test/uuid/UUIDTest.java
bf36473005376f288aa18017765457dc37ab0485
[]
no_license
zichunguo/java-test
https://github.com/zichunguo/java-test
e406cc29f5dc84f93d78301a90de27cd95ce2124
4a2cd6aaf0880980a5d32118f6b65d313351b892
refs/heads/master
2023-03-10T08:06:18.176000
2021-02-21T14:09:42
2021-02-21T14:09:42
340,864,587
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guo.test.uuid; import java.util.UUID; /** * @author guo * @date 2021/2/21 */ public class UUIDTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { UUID uuid = UUID.randomUUID(); System.out.println(uuid); UUID uuid2 = UUID.fromString(uuid.toString()); System.out.println(uuid2); System.out.println("************************"); } } }
UTF-8
Java
396
java
UUIDTest.java
Java
[ { "context": "test.uuid;\n\nimport java.util.UUID;\n\n/**\n * @author guo\n * @date 2021/2/21\n */\npublic class UUIDTest {\n\tp", "end": 70, "score": 0.9985548257827759, "start": 67, "tag": "USERNAME", "value": "guo" } ]
null
[]
package com.guo.test.uuid; import java.util.UUID; /** * @author guo * @date 2021/2/21 */ public class UUIDTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { UUID uuid = UUID.randomUUID(); System.out.println(uuid); UUID uuid2 = UUID.fromString(uuid.toString()); System.out.println(uuid2); System.out.println("************************"); } } }
396
0.590909
0.560606
19
19.842106
16.352251
50
false
false
0
0
0
0
0
0
1.578947
false
false
13
1fe7e03db2dd72253eefe7f23bd5309d8329cf87
22,892,175,725,718
291b85f3ac0e960957954e7fbf20eb6cc1745ca2
/PLASMA/tags/Archive/PAJ_PDDL_2_NDDL_06_10_02/DSA/base/dsa/Violation.java
f5ef2db6276e3ba7a2e804d0a6d6a272ee7e2b27
[]
no_license
oscar-lima/europa-pso
https://github.com/oscar-lima/europa-pso
25998b240ae42ebc79df5fce2ee76b80ab983475
4a884a216ad31eafcf97129071f86d418676bada
refs/heads/master
2016-09-08T18:13:56.189000
2014-09-23T20:05:09
2014-09-23T20:05:09
35,764,873
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dsa; public class Violation { public Violation(){} }
UTF-8
Java
67
java
Violation.java
Java
[]
null
[]
package dsa; public class Violation { public Violation(){} }
67
0.671642
0.671642
6
10.166667
10.253726
24
false
false
0
0
0
0
0
0
0.166667
false
false
13
fa0085e3fdca1a6507a7e4065ed464b0624a81a4
1,726,576,900,001
948464e137aabf1905f09212de0394999cc1e998
/scientific-repository/src/main/java/com/project/scientificrepository/camunda/delegate/SendSuccessMail.java
7ecf3d1a615404f7e5f2c7c77d09a50bb709d076
[]
no_license
markoKrajinovic/upp
https://github.com/markoKrajinovic/upp
268a5d78d9a816a0433e8469fd7447d0d6dbd136
c7058c5f995375e6e00c908b936336ed8460a78c
refs/heads/master
2020-04-23T12:52:23.433000
2019-03-17T09:02:45
2019-03-17T09:02:45
171,182,422
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.scientificrepository.camunda.delegate; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.camunda.bpm.engine.identity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SendSuccessMail implements JavaDelegate { @Autowired private EmailService emailService; @Override public void execute(DelegateExecution execution) throws Exception { // TODO Auto-generated method stub System.out.println("SEND SUCCESS MAIL"); User user = (User) execution.getVariable("loggedAuthor"); emailService.sendMail(user.getEmail(), "Prihvacen rad", "Vas rad je prihvacen, gj."); } }
UTF-8
Java
764
java
SendSuccessMail.java
Java
[]
null
[]
package com.project.scientificrepository.camunda.delegate; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.camunda.bpm.engine.identity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SendSuccessMail implements JavaDelegate { @Autowired private EmailService emailService; @Override public void execute(DelegateExecution execution) throws Exception { // TODO Auto-generated method stub System.out.println("SEND SUCCESS MAIL"); User user = (User) execution.getVariable("loggedAuthor"); emailService.sendMail(user.getEmail(), "Prihvacen rad", "Vas rad je prihvacen, gj."); } }
764
0.793194
0.793194
27
27.296297
27.399399
87
false
false
0
0
0
0
0
0
1.148148
false
false
13
399de0db0c1ca4ebbf9f825ce951226ea71c8203
28,484,223,150,784
bafe39cad5504f738a4d28f107578a42a7649c69
/Reminder/src/com/sc/reminder/ui/calendar/year/YearViewPagerFragment.java
eca1bbd09b8019a2c7362854582b8f6a8d2e2553
[ "Apache-2.0" ]
permissive
rapeflower/Android-Reminder
https://github.com/rapeflower/Android-Reminder
8c613526e14f55b2f8d78801580d70c6904ba017
171f39d4506e8c43bc7ebb41c680735c174fd779
refs/heads/master
2021-01-13T13:20:01.182000
2016-11-03T02:15:45
2016-11-03T02:15:45
72,650,534
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sc.reminder.ui.calendar.year; import com.sc.reminder.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class YearViewPagerFragment extends Fragment{ public static final int MIN_CALENDAR_YEAR = 1949; public static final int MAX_CALENDAR_YEAR = 2049; private ViewPager viewPager; @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View v = inflater.inflate(R.layout.year_viewpager, container, false); viewPager = (ViewPager) v.findViewById(R.id.year_pager); viewPager.setAdapter(new YearPagerAdapter(getActivity())); viewPager.setCurrentItem(65); //viewPager.setCurrentItem(new Time().year - MIN_CALENDAR_YEAR ); return v; } }
UTF-8
Java
1,627
java
YearViewPagerFragment.java
Java
[]
null
[]
package com.sc.reminder.ui.calendar.year; import com.sc.reminder.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class YearViewPagerFragment extends Fragment{ public static final int MIN_CALENDAR_YEAR = 1949; public static final int MAX_CALENDAR_YEAR = 2049; private ViewPager viewPager; @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View v = inflater.inflate(R.layout.year_viewpager, container, false); viewPager = (ViewPager) v.findViewById(R.id.year_pager); viewPager.setAdapter(new YearPagerAdapter(getActivity())); viewPager.setCurrentItem(65); //viewPager.setCurrentItem(new Time().year - MIN_CALENDAR_YEAR ); return v; } }
1,627
0.763983
0.756607
63
24.825397
21.262934
71
false
false
0
0
0
0
0
0
1.507936
false
false
13
e9900a2d548915230ccf51f6b44205d8e5f4ff2a
14,018,773,295,814
2b64829490a4869a4bcfa574841772835366904f
/src/main/java/org/shaderblowex/filter/PixelArt/PixelArtFilter.java
3b673d2a7642babe5326ef26b512f0db2f05671d
[ "MIT" ]
permissive
polincdev/ShaderBlowEx
https://github.com/polincdev/ShaderBlowEx
d2b4d3599bc5594aa22c9c93e392e4196471798d
7c2e19320e71a36c5f8858b8d701b1c3c3b05daa
refs/heads/master
2020-09-22T00:32:30.201000
2020-02-05T08:35:16
2020-02-05T08:35:16
224,987,563
6
6
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.shaderblowex.filter.PixelArt; import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.post.Filter; import com.jme3.post.Filter.Pass; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.texture.Image.Format; public class PixelArtFilter extends Filter { public static int PALETTE_TYPE_LINEAR=0; public static int PALETTE_TYPE_C64=1; public static int PALETTE_TYPE_CGA=2; public static int PALETTE_TYPE_CC=3; public static int PALETTE_TYPE_ANSI=4; public static int PALETTE_TYPE_STRIPE=5; public static int PALETTE_TYPE_GRAYSCALE=6; public static int PALETTE_TYPE_HEATMAP=7; public static int PALETTE_TYPE_RAINBOW=8; public static int PALETTE_TYPE_BRIGHTNESS=9; public static int PALETTE_TYPE_DESERT=10; public static int PALETTE_TYPE_ELECTRICAL=11; public static int PALETTE_TYPE_NEON=12; public static int PALETTE_TYPE_FIRE=13; public static int PALETTE_TYPE_TECH=14; public static int PALETTE_TYPE_HUE=15; public static int PALETTE_TYPE_POSTERIZATION=16; public static int PALETTE_TYPE_TOONIFICATION=17; private Pass normalPass; private float edgeWidth = 1.0f; private float edgeIntensity = 1.0f; private float normalThreshold = 0.5f; private float depthThreshold = 0.1f; private float normalSensitivity = 1.0f; private float depthSensitivity = 10.0f; private ColorRGBA edgeColor = new ColorRGBA(0, 0, 0, 1); private RenderManager renderManager; private ViewPort viewPort; private int paletteType=PALETTE_TYPE_LINEAR; private float colorSize= 4.0f; private float colorCount=5.0f; private float pixelResolution=250; /** * Creates a PixelArtFilter */ public PixelArtFilter() { super("PixelArtFilter"); } @Override protected boolean isRequiresDepthTexture() { return true; } @Override protected void postQueue(RenderQueue queue) { Renderer r = renderManager.getRenderer(); r.setFrameBuffer(normalPass.getRenderFrameBuffer()); renderManager.getRenderer().clearBuffers(true, true, true); renderManager.setForcedTechnique("PreNormalPass"); renderManager.renderViewPortQueues(viewPort, false); renderManager.setForcedTechnique(null); renderManager.getRenderer().setFrameBuffer(viewPort.getOutputFrameBuffer()); } @Override protected Material getMaterial() { material.setTexture("NormalsTexture", normalPass.getRenderedTexture()); return material; } @Override protected void initFilter(AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) { this.renderManager = renderManager; this.viewPort = vp; normalPass = new Pass(); normalPass.init(renderManager.getRenderer(), w, h, Format.RGBA8, Format.Depth); material = new Material(manager, "ShaderBlowEx/MatDefs/PixelArt/PixelArt.j3md"); material.setFloat("EdgeWidth", edgeWidth); material.setFloat("EdgeIntensity", edgeIntensity); material.setFloat("NormalThreshold", normalThreshold); material.setFloat("DepthThreshold", depthThreshold); material.setFloat("NormalSensitivity", normalSensitivity); material.setFloat("DepthSensitivity", depthSensitivity); material.setColor("EdgeColor", edgeColor); material.setInt("PaletteType", paletteType); material.setFloat("ColorSize", colorSize); material.setFloat("ColorCount", colorCount); material.setFloat("PixelResolution", pixelResolution); } @Override protected void cleanUpFilter(Renderer r) { normalPass.cleanup(r); } /** * Return the depth sensitivity<br> * for more details see {@link #setDepthSensitivity(float depthSensitivity)} * @return the depth sensitivity */ public float getDepthSensitivity() { return depthSensitivity; } /** * sets the depth sensitivity<br> * defines how much depth will influence edges, default is 10 * @param depthSensitivity */ public void setDepthSensitivity(float depthSensitivity) { this.depthSensitivity = depthSensitivity; if (material != null) { material.setFloat("DepthSensitivity", depthSensitivity); } } /** * returns the depth threshold<br> * for more details see {@link #setDepthThreshold(float depthThreshold)} * @return the threshold */ public float getDepthThreshold() { return depthThreshold; } /** * sets the depth threshold<br> * Defines at what threshold of difference of depth an edge is outlined default is 0.1f * @param depthThreshold */ public void setDepthThreshold(float depthThreshold) { this.depthThreshold = depthThreshold; if (material != null) { material.setFloat("DepthThreshold", depthThreshold); } } /** * returns the edge intensity<br> * for more details see {@link #setEdgeIntensity(float edgeIntensity) } * @return the intensity */ public float getEdgeIntensity() { return edgeIntensity; } /** * sets the edge intensity<br> * Defineshow visible will be the outlined edges * @param edgeIntensity */ public void setEdgeIntensity(float edgeIntensity) { this.edgeIntensity = edgeIntensity; if (material != null) { material.setFloat("EdgeIntensity", edgeIntensity); } } /** * returns the width of the edges * @return the width */ public float getEdgeWidth() { return edgeWidth; } /** * sets the witdh of the edge in pixels default is 1 * @param edgeWidth */ public void setEdgeWidth(float edgeWidth) { this.edgeWidth = edgeWidth; if (material != null) { material.setFloat("EdgeWidth", edgeWidth); } } /** * returns the normals sensitivity<br> * form more details see {@link #setNormalSensitivity(float normalSensitivity)} * @return the sensitivity */ public float getNormalSensitivity() { return normalSensitivity; } /** * sets the normals sensitivity default is 1 * @param normalSensitivity */ public void setNormalSensitivity(float normalSensitivity) { this.normalSensitivity = normalSensitivity; if (material != null) { material.setFloat("NormalSensitivity", normalSensitivity); } } /** * returns the normal threshold<br> * for more details see {@link #setNormalThreshold(float normalThreshold)} * * @return the threshold */ public float getNormalThreshold() { return normalThreshold; } /** * sets the normal threshold default is 0.5 * @param normalThreshold */ public void setNormalThreshold(float normalThreshold) { this.normalThreshold = normalThreshold; if (material != null) { material.setFloat("NormalThreshold", normalThreshold); } } /** * returns the edge color * @return the pre-existing instance */ public ColorRGBA getEdgeColor() { return edgeColor; } /** * Sets the edge color, default is black * @param edgeColor */ public void setEdgeColor(ColorRGBA edgeColor) { this.edgeColor = edgeColor; if (material != null) { material.setColor("EdgeColor", edgeColor); } } public int getPaletteType() { return paletteType; } public void setPaletteType(int paletteType) { this.paletteType = paletteType; if (material != null) material.setInt("PaletteType", paletteType); } public float getColorSize() { return colorSize; } public void setColorSize(float colorSize) { this.colorSize = colorSize; if (material != null) material.setFloat("ColorSize", colorSize); } public float getColorCount() { return colorCount; } public void setColorCount(float colorCount) { this.colorCount = colorCount; if (material != null) material.setFloat("ColorCount", colorCount); } public float getPixelResolution() { return pixelResolution; } public void setPixelResolution(float pixelResolution) { this.pixelResolution = pixelResolution; if (material != null) material.setFloat("PixelResolution", pixelResolution); } }
UTF-8
Java
8,857
java
PixelArtFilter.java
Java
[]
null
[]
package org.shaderblowex.filter.PixelArt; import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.post.Filter; import com.jme3.post.Filter.Pass; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.texture.Image.Format; public class PixelArtFilter extends Filter { public static int PALETTE_TYPE_LINEAR=0; public static int PALETTE_TYPE_C64=1; public static int PALETTE_TYPE_CGA=2; public static int PALETTE_TYPE_CC=3; public static int PALETTE_TYPE_ANSI=4; public static int PALETTE_TYPE_STRIPE=5; public static int PALETTE_TYPE_GRAYSCALE=6; public static int PALETTE_TYPE_HEATMAP=7; public static int PALETTE_TYPE_RAINBOW=8; public static int PALETTE_TYPE_BRIGHTNESS=9; public static int PALETTE_TYPE_DESERT=10; public static int PALETTE_TYPE_ELECTRICAL=11; public static int PALETTE_TYPE_NEON=12; public static int PALETTE_TYPE_FIRE=13; public static int PALETTE_TYPE_TECH=14; public static int PALETTE_TYPE_HUE=15; public static int PALETTE_TYPE_POSTERIZATION=16; public static int PALETTE_TYPE_TOONIFICATION=17; private Pass normalPass; private float edgeWidth = 1.0f; private float edgeIntensity = 1.0f; private float normalThreshold = 0.5f; private float depthThreshold = 0.1f; private float normalSensitivity = 1.0f; private float depthSensitivity = 10.0f; private ColorRGBA edgeColor = new ColorRGBA(0, 0, 0, 1); private RenderManager renderManager; private ViewPort viewPort; private int paletteType=PALETTE_TYPE_LINEAR; private float colorSize= 4.0f; private float colorCount=5.0f; private float pixelResolution=250; /** * Creates a PixelArtFilter */ public PixelArtFilter() { super("PixelArtFilter"); } @Override protected boolean isRequiresDepthTexture() { return true; } @Override protected void postQueue(RenderQueue queue) { Renderer r = renderManager.getRenderer(); r.setFrameBuffer(normalPass.getRenderFrameBuffer()); renderManager.getRenderer().clearBuffers(true, true, true); renderManager.setForcedTechnique("PreNormalPass"); renderManager.renderViewPortQueues(viewPort, false); renderManager.setForcedTechnique(null); renderManager.getRenderer().setFrameBuffer(viewPort.getOutputFrameBuffer()); } @Override protected Material getMaterial() { material.setTexture("NormalsTexture", normalPass.getRenderedTexture()); return material; } @Override protected void initFilter(AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) { this.renderManager = renderManager; this.viewPort = vp; normalPass = new Pass(); normalPass.init(renderManager.getRenderer(), w, h, Format.RGBA8, Format.Depth); material = new Material(manager, "ShaderBlowEx/MatDefs/PixelArt/PixelArt.j3md"); material.setFloat("EdgeWidth", edgeWidth); material.setFloat("EdgeIntensity", edgeIntensity); material.setFloat("NormalThreshold", normalThreshold); material.setFloat("DepthThreshold", depthThreshold); material.setFloat("NormalSensitivity", normalSensitivity); material.setFloat("DepthSensitivity", depthSensitivity); material.setColor("EdgeColor", edgeColor); material.setInt("PaletteType", paletteType); material.setFloat("ColorSize", colorSize); material.setFloat("ColorCount", colorCount); material.setFloat("PixelResolution", pixelResolution); } @Override protected void cleanUpFilter(Renderer r) { normalPass.cleanup(r); } /** * Return the depth sensitivity<br> * for more details see {@link #setDepthSensitivity(float depthSensitivity)} * @return the depth sensitivity */ public float getDepthSensitivity() { return depthSensitivity; } /** * sets the depth sensitivity<br> * defines how much depth will influence edges, default is 10 * @param depthSensitivity */ public void setDepthSensitivity(float depthSensitivity) { this.depthSensitivity = depthSensitivity; if (material != null) { material.setFloat("DepthSensitivity", depthSensitivity); } } /** * returns the depth threshold<br> * for more details see {@link #setDepthThreshold(float depthThreshold)} * @return the threshold */ public float getDepthThreshold() { return depthThreshold; } /** * sets the depth threshold<br> * Defines at what threshold of difference of depth an edge is outlined default is 0.1f * @param depthThreshold */ public void setDepthThreshold(float depthThreshold) { this.depthThreshold = depthThreshold; if (material != null) { material.setFloat("DepthThreshold", depthThreshold); } } /** * returns the edge intensity<br> * for more details see {@link #setEdgeIntensity(float edgeIntensity) } * @return the intensity */ public float getEdgeIntensity() { return edgeIntensity; } /** * sets the edge intensity<br> * Defineshow visible will be the outlined edges * @param edgeIntensity */ public void setEdgeIntensity(float edgeIntensity) { this.edgeIntensity = edgeIntensity; if (material != null) { material.setFloat("EdgeIntensity", edgeIntensity); } } /** * returns the width of the edges * @return the width */ public float getEdgeWidth() { return edgeWidth; } /** * sets the witdh of the edge in pixels default is 1 * @param edgeWidth */ public void setEdgeWidth(float edgeWidth) { this.edgeWidth = edgeWidth; if (material != null) { material.setFloat("EdgeWidth", edgeWidth); } } /** * returns the normals sensitivity<br> * form more details see {@link #setNormalSensitivity(float normalSensitivity)} * @return the sensitivity */ public float getNormalSensitivity() { return normalSensitivity; } /** * sets the normals sensitivity default is 1 * @param normalSensitivity */ public void setNormalSensitivity(float normalSensitivity) { this.normalSensitivity = normalSensitivity; if (material != null) { material.setFloat("NormalSensitivity", normalSensitivity); } } /** * returns the normal threshold<br> * for more details see {@link #setNormalThreshold(float normalThreshold)} * * @return the threshold */ public float getNormalThreshold() { return normalThreshold; } /** * sets the normal threshold default is 0.5 * @param normalThreshold */ public void setNormalThreshold(float normalThreshold) { this.normalThreshold = normalThreshold; if (material != null) { material.setFloat("NormalThreshold", normalThreshold); } } /** * returns the edge color * @return the pre-existing instance */ public ColorRGBA getEdgeColor() { return edgeColor; } /** * Sets the edge color, default is black * @param edgeColor */ public void setEdgeColor(ColorRGBA edgeColor) { this.edgeColor = edgeColor; if (material != null) { material.setColor("EdgeColor", edgeColor); } } public int getPaletteType() { return paletteType; } public void setPaletteType(int paletteType) { this.paletteType = paletteType; if (material != null) material.setInt("PaletteType", paletteType); } public float getColorSize() { return colorSize; } public void setColorSize(float colorSize) { this.colorSize = colorSize; if (material != null) material.setFloat("ColorSize", colorSize); } public float getColorCount() { return colorCount; } public void setColorCount(float colorCount) { this.colorCount = colorCount; if (material != null) material.setFloat("ColorCount", colorCount); } public float getPixelResolution() { return pixelResolution; } public void setPixelResolution(float pixelResolution) { this.pixelResolution = pixelResolution; if (material != null) material.setFloat("PixelResolution", pixelResolution); } }
8,857
0.652027
0.643897
298
28.724833
22.875021
109
false
false
0
0
0
0
0
0
0.483221
false
false
13
653536a095bc83cf3e56c7004e6d85f55ac806c7
22,857,815,993,607
09b9f8e124cdc20b74d2edd22b81f8c7acfffac6
/src/main/java/io/github/com/pages/inputs/CheckboxPage.java
110bfba193a8731fa4668ef470aa872173174594
[]
no_license
Fwerfad/diplom-test-framework
https://github.com/Fwerfad/diplom-test-framework
070367fe3fdd265e054a7f3dfde6cb5793d35314
78a830a903ec6d61f52200d731699ae9e42cd160
refs/heads/master
2023-04-12T16:48:18.705000
2021-05-20T23:24:49
2021-05-20T23:24:49
369,361,333
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.com.pages.inputs; import com.epam.jdi.light.elements.composite.WebPage; import com.epam.jdi.light.elements.pageobjects.annotations.locators.UI; import com.epam.jdi.light.ui.html.elements.common.Text; import material.elements.inputs.Checkbox; import java.util.List; public class CheckboxPage extends WebPage { @UI("//h2[text()='Basic checkboxes']/following-sibling::div[1]/span") public List<Checkbox> basicCheckbox; @UI("//h2[text()='Checkbox with FormControlLabel']/following-sibling::div[1]/label/span[1]") public List<Checkbox> formControlLabelCheckbox; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/div/label/span[1]") public List<Checkbox> formGroupCheckbox; @UI("//h2[text()='Label placement']/following-sibling::fieldset/div/label/span[1]") public List<Checkbox> labelPlacementCheckbox; @UI("//h2[text()='Checkbox with FormControlLabel']/following-sibling::div[1]/label/span[2]") public List<Text> formControlLabelText; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/div/label/span[2]") public List<Text> formGroupText; @UI("//h2[text()='Label placement']/following-sibling::fieldset/div/label/span[2]") public List<Text> labelPlacementText; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/legend") public List<Text> errorMessage; }
UTF-8
Java
1,436
java
CheckboxPage.java
Java
[]
null
[]
package io.github.com.pages.inputs; import com.epam.jdi.light.elements.composite.WebPage; import com.epam.jdi.light.elements.pageobjects.annotations.locators.UI; import com.epam.jdi.light.ui.html.elements.common.Text; import material.elements.inputs.Checkbox; import java.util.List; public class CheckboxPage extends WebPage { @UI("//h2[text()='Basic checkboxes']/following-sibling::div[1]/span") public List<Checkbox> basicCheckbox; @UI("//h2[text()='Checkbox with FormControlLabel']/following-sibling::div[1]/label/span[1]") public List<Checkbox> formControlLabelCheckbox; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/div/label/span[1]") public List<Checkbox> formGroupCheckbox; @UI("//h2[text()='Label placement']/following-sibling::fieldset/div/label/span[1]") public List<Checkbox> labelPlacementCheckbox; @UI("//h2[text()='Checkbox with FormControlLabel']/following-sibling::div[1]/label/span[2]") public List<Text> formControlLabelText; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/div/label/span[2]") public List<Text> formGroupText; @UI("//h2[text()='Label placement']/following-sibling::fieldset/div/label/span[2]") public List<Text> labelPlacementText; @UI("//h2[text()='Checkboxes with FormGroup']/following-sibling::div[1]/fieldset/legend") public List<Text> errorMessage; }
1,436
0.727019
0.713092
36
38.888889
35.527592
104
false
false
0
0
0
0
0
0
0.388889
false
false
13
1ea92b145a9f202777065a1b3603e60b9b8126d8
22,857,815,992,244
500e98bf13cbb7a1b3963bee46aec56022f5caf5
/src/Registration.java
b07e8d01e113ab4b88123bbe5f102f5cbd67ccea
[]
no_license
Kenneth-del/CSC214
https://github.com/Kenneth-del/CSC214
c1b97d09ea4e8fa1f7179c80c3d87237e28b7d23
e64673554670dd37b0263b8720cc87a8e7bcaed4
refs/heads/master
2021-01-05T19:07:05.576000
2020-04-27T13:25:26
2020-04-27T13:25:26
241,110,892
2
3
null
false
2020-04-10T15:55:35
2020-02-17T13:11:47
2020-04-10T01:50:39
2020-04-10T15:55:34
2,808
2
3
0
Java
false
false
import java.awt.List; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class Registration { //ArrayList of semesters with active registration public static ArrayList < String > semesters = new ArrayList < String > (); //2D ArrayList where each row is different semester and row contains ArrayList of courses in that semester. //The semester of each row is represented by the corresponding index in semesters ArrayList public static ArrayList < ArrayList < Course >> registration = new ArrayList < ArrayList < Course >> (); public Registration(int id) throws SQLException { PreparedStatement ps; String query = "SELECT " + "h.CRN " + ", h.Semester " + "FROM Registration s " + "INNER JOIN Section h " + "on s.Section_CRN = h.CRN " + "WHERE s.Student_id =?";; ps = MyConnection.getConnection().prepareStatement(query); ps.setInt(1, User.getId()); ResultSet rs = ps.executeQuery(); while (rs.next()) { // Tests to see if Semester has already been retrieved if (!(semesters.contains(rs.getString(2)))) { //If semester hasn't been recorded, it is indexed in semesters array list semesters.add(rs.getString(2)); //Adds new row to to store courses from semester registration.add(new ArrayList < Course > ()); //Creates course object and stores it in ArrayList with same index in registration //as corresponding semester does in semester ArrayList registration.get(semesters.indexOf(rs.getString(2))).add(new Course(rs.getInt(1))); } else // Places course in ArrayList with same index as semester ArrayList registration.get(semesters.indexOf(rs.getString(2))).add(new Course(rs.getInt(1))); } rs.close(); } //TODO: Decide how course information is passed to UI public ArrayList<Course> getSemester(String semester){ if(semesters.contains(semester)) return registration.get(semesters.indexOf(semester)); else return null; } //Should return requested course instance public Course getCourse(String semester, int CRN) { for(int i = 1; i <= registration.get(semesters.indexOf(semester)).size(); i++) { if(registration.get(semesters.indexOf(semester)).get(i).getCRN() == CRN) { return registration.get(semesters.indexOf(semester)).get(i); } } return null; } public ArrayList<String> getSemesters(){ return semesters; } } //TODO: Write course registration method. Method must confirm correct changes were made to database // before allowing user to continue. //TODO: Write course drop method.
UTF-8
Java
3,020
java
Registration.java
Java
[]
null
[]
import java.awt.List; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class Registration { //ArrayList of semesters with active registration public static ArrayList < String > semesters = new ArrayList < String > (); //2D ArrayList where each row is different semester and row contains ArrayList of courses in that semester. //The semester of each row is represented by the corresponding index in semesters ArrayList public static ArrayList < ArrayList < Course >> registration = new ArrayList < ArrayList < Course >> (); public Registration(int id) throws SQLException { PreparedStatement ps; String query = "SELECT " + "h.CRN " + ", h.Semester " + "FROM Registration s " + "INNER JOIN Section h " + "on s.Section_CRN = h.CRN " + "WHERE s.Student_id =?";; ps = MyConnection.getConnection().prepareStatement(query); ps.setInt(1, User.getId()); ResultSet rs = ps.executeQuery(); while (rs.next()) { // Tests to see if Semester has already been retrieved if (!(semesters.contains(rs.getString(2)))) { //If semester hasn't been recorded, it is indexed in semesters array list semesters.add(rs.getString(2)); //Adds new row to to store courses from semester registration.add(new ArrayList < Course > ()); //Creates course object and stores it in ArrayList with same index in registration //as corresponding semester does in semester ArrayList registration.get(semesters.indexOf(rs.getString(2))).add(new Course(rs.getInt(1))); } else // Places course in ArrayList with same index as semester ArrayList registration.get(semesters.indexOf(rs.getString(2))).add(new Course(rs.getInt(1))); } rs.close(); } //TODO: Decide how course information is passed to UI public ArrayList<Course> getSemester(String semester){ if(semesters.contains(semester)) return registration.get(semesters.indexOf(semester)); else return null; } //Should return requested course instance public Course getCourse(String semester, int CRN) { for(int i = 1; i <= registration.get(semesters.indexOf(semester)).size(); i++) { if(registration.get(semesters.indexOf(semester)).get(i).getCRN() == CRN) { return registration.get(semesters.indexOf(semester)).get(i); } } return null; } public ArrayList<String> getSemesters(){ return semesters; } } //TODO: Write course registration method. Method must confirm correct changes were made to database // before allowing user to continue. //TODO: Write course drop method.
3,020
0.618212
0.615232
93
30.473118
32.379333
111
false
false
0
0
0
0
0
0
0.55914
false
false
13
b5fe6a4dcc0a1c70c82ae4115b66512c77922f8a
9,096,740,778,444
fb5391ae73c2fdb0f47c6848d7bb587a784e13c1
/src/main/java/com/rainbow/manager/common/MailSender.java
20e99a5e951cea98197134b437e32c6e51924499
[]
no_license
xm0830/service-m
https://github.com/xm0830/service-m
8f946f00fb50064805ee16751c9693a8ee38f3be
265c30e34a28a4826f54ab7e1f8ff7ab0d7e687c
refs/heads/master
2021-01-20T16:16:59.096000
2017-08-11T10:33:33
2017-08-11T10:33:33
90,828,821
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rainbow.manager.common; import com.rainbow.manager.config.EmailConfig; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * Created by xuming on 2017/5/11. */ public class MailSender { private Session session = null; private EmailConfig config = null; public MailSender(EmailConfig config) { Properties props = new Properties(); props.setProperty("mail.transport.protocol", config.getProtocol()); props.setProperty("mail.smtp.host", config.getServer()); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.connectiontimeout", "3000"); props.put("mail.smtp.timeout", "3000"); // props.setProperty("mail.smtp.port", port); // props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // props.setProperty("mail.smtp.socketFactory.fallback", "false"); // props.setProperty("mail.smtp.socketFactory.port", port); this.session = Session.getDefaultInstance(props); this.config = config; } public void send(String content) throws Exception { Transport transport = session.getTransport(); transport.connect(config.getSendEmailUser(), config.getSendEmailPwd()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getSendEmailPwd(), "ServiceManager", "UTF-8")); String[] splits = config.getReceiveEmailUsers().split(",", -1); for (String split : splits) { message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(split, split, "UTF-8")); } message.setSubject("服务运行失败通知", "UTF-8"); message.setContent(content, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }
UTF-8
Java
2,091
java
MailSender.java
Java
[ { "context": "e;\nimport java.util.Properties;\n\n/**\n * Created by xuming on 2017/5/11.\n */\npublic class MailSender {\n\n ", "end": 302, "score": 0.999569296836853, "start": 296, "tag": "USERNAME", "value": "xuming" } ]
null
[]
package com.rainbow.manager.common; import com.rainbow.manager.config.EmailConfig; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.Properties; /** * Created by xuming on 2017/5/11. */ public class MailSender { private Session session = null; private EmailConfig config = null; public MailSender(EmailConfig config) { Properties props = new Properties(); props.setProperty("mail.transport.protocol", config.getProtocol()); props.setProperty("mail.smtp.host", config.getServer()); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.connectiontimeout", "3000"); props.put("mail.smtp.timeout", "3000"); // props.setProperty("mail.smtp.port", port); // props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // props.setProperty("mail.smtp.socketFactory.fallback", "false"); // props.setProperty("mail.smtp.socketFactory.port", port); this.session = Session.getDefaultInstance(props); this.config = config; } public void send(String content) throws Exception { Transport transport = session.getTransport(); transport.connect(config.getSendEmailUser(), config.getSendEmailPwd()); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getSendEmailPwd(), "ServiceManager", "UTF-8")); String[] splits = config.getReceiveEmailUsers().split(",", -1); for (String split : splits) { message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(split, split, "UTF-8")); } message.setSubject("服务运行失败通知", "UTF-8"); message.setContent(content, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } }
2,091
0.68
0.670361
58
34.775864
28.97802
107
false
false
0
0
0
0
0
0
0.948276
false
false
13
3165052b90afdae1b64de9d76ee695e91c1457d9
24,438,363,943,337
462a02e21481aad27a1c2ea776334d8192d013f3
/src/fr/gtm/contacts/entities/Civilite.java
add75995049b79de5d79946cd26f8000540f9ec0
[]
no_license
Jcfag2/Contacts-Webservice-Jboss
https://github.com/Jcfag2/Contacts-Webservice-Jboss
8efabe42a384cee58142c9594bb767806daa65e6
0f3de2ec1e21396b33b850474422e6f9b913b857
refs/heads/master
2020-09-08T19:26:08.387000
2019-11-13T15:27:43
2019-11-13T15:27:43
221,224,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.gtm.contacts.entities; public enum Civilite { M,Mr,Mme,Dr,Me,Pr,Mlle }
UTF-8
Java
88
java
Civilite.java
Java
[]
null
[]
package fr.gtm.contacts.entities; public enum Civilite { M,Mr,Mme,Dr,Me,Pr,Mlle }
88
0.704545
0.704545
5
15.6
12.970737
33
false
false
0
0
0
0
0
0
1.4
false
false
13
035701c48d32638747a765c80ccdecccb9b8141f
9,174,050,186,853
8c8f0fb9c6af43b619aef6f7a123be775022d163
/src/main/java/web/action/accountadmin/LoginCheckAction.java
9ae5a205ffdcb2e32e8cd056725b1c272aa10e43
[]
no_license
hushenglang/webui
https://github.com/hushenglang/webui
128b2d0db73aaa3d35510a1cd6e647f5f2cc3a81
100b39bbda0312fc8ed7d325d9e7ac7f517c6c45
refs/heads/master
2016-08-07T22:43:43.120000
2015-07-24T10:03:55
2015-07-24T10:03:55
39,624,708
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package web.action.accountadmin; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import web.constant.AccountStatus; import web.util.WebUiUtils; import com.gwghk.demo.gold.client.DemoClientManagerFactory; import com.gwghk.demo.gold.client.interfaces.DemoAcManager; import com.gwghk.demo.gold.client.models.DemoApiResult; import com.gwghk.gold.client.ClientManagerFactory; import com.gwghk.gold.client.interfaces.AccountManager; import com.gwghk.gold.client.models.ApiResult; import com.gwghk.gold.client.models.FcustomerInfoParam; import com.opensymphony.xwork2.ActionSupport; public class LoginCheckAction extends ActionSupport implements ServletRequestAware{ private static final Logger logger = Logger.getLogger(LoginAction.class); protected HttpServletRequest request; //将会被Struts2序列化为JSON字符串的对象 private Map<String, Object> dataMap=new HashMap<String, Object>(); private String username; private String password; private String randomNumber;// 验证码 private String usertype; //0:真实 1:模拟 @Override public String execute() throws Exception { dataMap.clear(); JSONObject jsonObject = new JSONObject(); dataMap.put("user", "user"); // 放入一个是否操作成功的标识 dataMap.put("success", true); //1、验证验证码是否正确 String random = (String) request.getSession().getAttribute("random"); if (randomNumber == null || !randomNumber.toLowerCase().equals(random)) { dataMap.put("errorcode", 1); dataMap.put("errormsg", URLEncoder.encode(this.getText("error.captcha.not.correct"),"UTF-8")); request.getSession().removeAttribute("random"); //验证码出错 jsonObject.accumulate("map", dataMap); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); PrintWriter out; out = response.getWriter(); out.println(jsonObject.toString()); return null; } //2、通过api验证,返回相应的code if("0".equalsIgnoreCase(usertype)){ AccountManager accountManager = ClientManagerFactory.getInstance().getAccountManager(); ApiResult apiResult=accountManager.loginUi(username.trim(),password.trim(),request.getRemoteAddr()); if(apiResult!=null && !apiResult.isOk()){ dataMap.put("errorcode", apiResult.getCode()); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error."+apiResult.getCode()),"UTF-8")); request.getSession().removeAttribute("random"); }else{ dataMap.put("errorcode", 0); dataMap.put("errormsg", ""); //after the authentication of account/password, need to be validate the account status boolean isValidatedAccount = validateAccountStatus(username.trim()); if(!isValidatedAccount){ dataMap.put("errorcode", 2); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error.1007"),"UTF-8")); } } }else{ DemoAcManager dmanage=DemoClientManagerFactory.getInstance().getDemoAcManager(); logger.info("dmanage is null : "+(dmanage == null)); DemoApiResult demoApiResult = dmanage.loginUiDemo(username.trim(),password.trim(),request.getRemoteAddr()); ApiResult apiResult = WebUiUtils.convertApiResult(demoApiResult); if(apiResult!=null && !apiResult.isOk()){ dataMap.put("errorcode", apiResult.getCode()); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error."+apiResult.getCode()),"UTF-8")); request.getSession().removeAttribute("random"); }else{ dataMap.put("errorcode", 0); dataMap.put("errormsg", ""); } } jsonObject.accumulate("map", dataMap); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); PrintWriter out; out = response.getWriter(); out.println(jsonObject.toString()); return null; } /** * validate if the account status is available * @param loginname * @return */ public boolean validateAccountStatus(String loginname){ AccountManager accountManager = ClientManagerFactory.getInstance().getAccountManager(); FcustomerInfoParam fcustomerInfoParam=accountManager.getCustomerInfo(loginname); String accountStatus = fcustomerInfoParam.getAccountStatus(); boolean flag = true; if(AccountStatus.M.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.D.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.C.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.I.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.N.getValue().equals(accountStatus)){ flag= false; } if(!flag){ logger.debug("account status is not allowed to login . status:"+accountStatus); }else{ logger.debug("account is allowed to login!"); } return flag; } @Override public void setServletRequest(HttpServletRequest req) { this.request=req; } /** * Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的 * @return */ public Map<String, Object> getDataMap() { return dataMap; } 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 getRandomNumber() { return randomNumber; } public void setRandomNumber(String randomNumber) { this.randomNumber = randomNumber; } public String getUsertype() { return usertype; } public void setUsertype(String usertype) { this.usertype = usertype; } }
UTF-8
Java
5,954
java
LoginCheckAction.java
Java
[ { "context": "ataMap;\n\t}\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\tpublic void setUsername(String username) {\n\t", "end": 5266, "score": 0.741615891456604, "start": 5258, "tag": "USERNAME", "value": "username" }, { "context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\tpublic String getPassword() {\n\t\treturn passw", "end": 5341, "score": 0.8976947665214539, "start": 5333, "tag": "USERNAME", "value": "username" } ]
null
[]
package web.action.accountadmin; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import web.constant.AccountStatus; import web.util.WebUiUtils; import com.gwghk.demo.gold.client.DemoClientManagerFactory; import com.gwghk.demo.gold.client.interfaces.DemoAcManager; import com.gwghk.demo.gold.client.models.DemoApiResult; import com.gwghk.gold.client.ClientManagerFactory; import com.gwghk.gold.client.interfaces.AccountManager; import com.gwghk.gold.client.models.ApiResult; import com.gwghk.gold.client.models.FcustomerInfoParam; import com.opensymphony.xwork2.ActionSupport; public class LoginCheckAction extends ActionSupport implements ServletRequestAware{ private static final Logger logger = Logger.getLogger(LoginAction.class); protected HttpServletRequest request; //将会被Struts2序列化为JSON字符串的对象 private Map<String, Object> dataMap=new HashMap<String, Object>(); private String username; private String password; private String randomNumber;// 验证码 private String usertype; //0:真实 1:模拟 @Override public String execute() throws Exception { dataMap.clear(); JSONObject jsonObject = new JSONObject(); dataMap.put("user", "user"); // 放入一个是否操作成功的标识 dataMap.put("success", true); //1、验证验证码是否正确 String random = (String) request.getSession().getAttribute("random"); if (randomNumber == null || !randomNumber.toLowerCase().equals(random)) { dataMap.put("errorcode", 1); dataMap.put("errormsg", URLEncoder.encode(this.getText("error.captcha.not.correct"),"UTF-8")); request.getSession().removeAttribute("random"); //验证码出错 jsonObject.accumulate("map", dataMap); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); PrintWriter out; out = response.getWriter(); out.println(jsonObject.toString()); return null; } //2、通过api验证,返回相应的code if("0".equalsIgnoreCase(usertype)){ AccountManager accountManager = ClientManagerFactory.getInstance().getAccountManager(); ApiResult apiResult=accountManager.loginUi(username.trim(),password.trim(),request.getRemoteAddr()); if(apiResult!=null && !apiResult.isOk()){ dataMap.put("errorcode", apiResult.getCode()); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error."+apiResult.getCode()),"UTF-8")); request.getSession().removeAttribute("random"); }else{ dataMap.put("errorcode", 0); dataMap.put("errormsg", ""); //after the authentication of account/password, need to be validate the account status boolean isValidatedAccount = validateAccountStatus(username.trim()); if(!isValidatedAccount){ dataMap.put("errorcode", 2); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error.1007"),"UTF-8")); } } }else{ DemoAcManager dmanage=DemoClientManagerFactory.getInstance().getDemoAcManager(); logger.info("dmanage is null : "+(dmanage == null)); DemoApiResult demoApiResult = dmanage.loginUiDemo(username.trim(),password.trim(),request.getRemoteAddr()); ApiResult apiResult = WebUiUtils.convertApiResult(demoApiResult); if(apiResult!=null && !apiResult.isOk()){ dataMap.put("errorcode", apiResult.getCode()); dataMap.put("errormsg", URLEncoder.encode(this.getText("login.error."+apiResult.getCode()),"UTF-8")); request.getSession().removeAttribute("random"); }else{ dataMap.put("errorcode", 0); dataMap.put("errormsg", ""); } } jsonObject.accumulate("map", dataMap); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); PrintWriter out; out = response.getWriter(); out.println(jsonObject.toString()); return null; } /** * validate if the account status is available * @param loginname * @return */ public boolean validateAccountStatus(String loginname){ AccountManager accountManager = ClientManagerFactory.getInstance().getAccountManager(); FcustomerInfoParam fcustomerInfoParam=accountManager.getCustomerInfo(loginname); String accountStatus = fcustomerInfoParam.getAccountStatus(); boolean flag = true; if(AccountStatus.M.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.D.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.C.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.I.getValue().equals(accountStatus)){ flag= false; }else if(AccountStatus.N.getValue().equals(accountStatus)){ flag= false; } if(!flag){ logger.debug("account status is not allowed to login . status:"+accountStatus); }else{ logger.debug("account is allowed to login!"); } return flag; } @Override public void setServletRequest(HttpServletRequest req) { this.request=req; } /** * Struts2序列化指定属性时,必须有该属性的getter方法,实际上,如果没有属性,而只有getter方法也是可以的 * @return */ public Map<String, Object> getDataMap() { return dataMap; } 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 getRandomNumber() { return randomNumber; } public void setRandomNumber(String randomNumber) { this.randomNumber = randomNumber; } public String getUsertype() { return usertype; } public void setUsertype(String usertype) { this.usertype = usertype; } }
5,954
0.743572
0.739576
170
32.858822
26.839458
110
false
false
0
0
0
0
0
0
2.458823
false
false
13
b9f88d2ea75fc9620caa01b99eb5a41627ceb781
16,750,372,472,083
206d15befecdfb67a93c61c935c2d5ae7f6a79e9
/justdoit/SoNingboApp/src/main/test/org/jxstar/test/base/TestInf.java
88bd4a95a736a660e8564acfd608f7dfcc16bc26
[]
no_license
MarkChege/micandroid
https://github.com/MarkChege/micandroid
2e4d2884929548a814aa0a7715727c84dc4dcdab
0b0a6dee39cf7e258b6f54e1103dcac8dbe1c419
refs/heads/master
2021-01-10T19:15:34.994000
2013-05-16T05:56:21
2013-05-16T05:56:21
34,704,029
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package org.jxstar.test.base; /** * @author bingco 2009-6-16 * * 测试用例的通用接口 */ public interface TestInf { /** * 测试用例要测试内容。 * @return boolean */ public boolean execute(); }
UTF-8
Java
253
java
TestInf.java
Java
[ { "context": "\r\npackage org.jxstar.test.base;\r\n\r\n/**\r\n * @author bingco 2009-6-16\r\n *\r\n * 测试用例的通用接口\r\n */\r\npublic interfac", "end": 70, "score": 0.9995338320732117, "start": 64, "tag": "USERNAME", "value": "bingco" } ]
null
[]
/** * */ package org.jxstar.test.base; /** * @author bingco 2009-6-16 * * 测试用例的通用接口 */ public interface TestInf { /** * 测试用例要测试内容。 * @return boolean */ public boolean execute(); }
253
0.539535
0.506977
18
9.944445
10.341246
29
false
false
0
0
0
0
0
0
0.388889
false
false
13
37d3faa30c138a473dcb607b273973ba9c923790
27,865,747,878,217
ae97cbf6b7db817b339d42c8b39b54086ca81833
/src/main/java/com/br/waldir/repository/DisciplinaRepository.java
fa2fd0fc4b3cf2a3c9fd4ee6d0896fa6974e61d5
[]
no_license
waldirmarques/CriandoApiRest
https://github.com/waldirmarques/CriandoApiRest
b5d350cd196f6d91112c0dfa6de8abfa7fca9cd7
c86ce0fbe1a1eebeea5afe39216279369fe38e44
refs/heads/master
2020-10-01T06:59:53.991000
2019-12-12T14:35:08
2019-12-12T14:35:08
227,483,030
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.br.waldir.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.br.waldir.domain.Disciplina; public interface DisciplinaRepository extends JpaRepository<Disciplina, Integer> { }
UTF-8
Java
225
java
DisciplinaRepository.java
Java
[]
null
[]
package com.br.waldir.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.br.waldir.domain.Disciplina; public interface DisciplinaRepository extends JpaRepository<Disciplina, Integer> { }
225
0.831111
0.831111
9
24
29.574764
82
false
false
0
0
0
0
0
0
0.444444
false
false
13
d93a6b976a0a76331944c2b8b4b92475d98ccef8
21,131,239,147,028
0c9e770519bbbf5d5f0d55955ae5163e33b6a39d
/app/src/main/java/com/zgld/mall/beans/YMessageClassMatch.java
bf776430f7735aa47fbf78872fcc2474791ab3e8
[]
no_license
longliuping/ZgldStore
https://github.com/longliuping/ZgldStore
6c4b3ee05b0b8db9739fb66154be2b1001219c88
8ba94ff4c5cb1a9f6436f7008f0bca0bb4868ac6
refs/heads/master
2021-01-21T13:48:06.839000
2016-05-12T09:41:38
2016-05-12T09:41:38
55,341,712
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zgld.mall.beans; import java.sql.Date; /** * YMessageClassMatch entity. @author MyEclipse Persistence Tools */ public class YMessageClassMatch extends AbstractYMessageClassMatch implements java.io.Serializable { // Constructors /** default constructor */ public YMessageClassMatch() { } /** minimal constructor */ public YMessageClassMatch(String msgClassMatchTime) { super(msgClassMatchTime); } /** full constructor */ public YMessageClassMatch(Integer msgClassSetId, Integer unitSetId, String msgClassMatchTime) { super(msgClassSetId, unitSetId, msgClassMatchTime); } }
UTF-8
Java
607
java
YMessageClassMatch.java
Java
[]
null
[]
package com.zgld.mall.beans; import java.sql.Date; /** * YMessageClassMatch entity. @author MyEclipse Persistence Tools */ public class YMessageClassMatch extends AbstractYMessageClassMatch implements java.io.Serializable { // Constructors /** default constructor */ public YMessageClassMatch() { } /** minimal constructor */ public YMessageClassMatch(String msgClassMatchTime) { super(msgClassMatchTime); } /** full constructor */ public YMessageClassMatch(Integer msgClassSetId, Integer unitSetId, String msgClassMatchTime) { super(msgClassSetId, unitSetId, msgClassMatchTime); } }
607
0.771005
0.771005
26
22.346153
28.661074
100
false
false
0
0
0
0
0
0
0.846154
false
false
13
17c75101fc50dbaea9af8d89e1c6f66669238788
24,446,953,881,184
ded8fc46653bd4d393db48139149752a10bed59e
/backend/src/main/java/org/polsl/backend/repository/AffiliationRepository.java
335f68c34cca3850d773005e9f5278dc5fa90922
[ "MIT" ]
permissive
Samograje/co-gdzie-kiedy
https://github.com/Samograje/co-gdzie-kiedy
c032a9f13a36ffa72e78defc6d222f5f39b8505d
b594e17417889dbe7c5fcad60926325aa80e1564
refs/heads/master
2022-09-29T02:46:39.396000
2020-01-28T22:11:30
2020-01-28T22:11:30
212,629,080
0
0
MIT
false
2022-09-08T01:02:54
2019-10-03T16:41:23
2020-02-11T17:06:58
2022-09-08T01:02:51
2,900
0
0
17
Java
false
false
package org.polsl.backend.repository; import org.polsl.backend.entity.Affiliation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AffiliationRepository extends JpaRepository<Affiliation, Long>, JpaSpecificationExecutor<Affiliation> { List<Affiliation> findAllByIsDeletedIsFalse(); Optional<Affiliation> findByIdAndIsDeletedIsFalse(Long id); long countByIsDeletedIsFalse(); }
UTF-8
Java
604
java
AffiliationRepository.java
Java
[]
null
[]
package org.polsl.backend.repository; import org.polsl.backend.entity.Affiliation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface AffiliationRepository extends JpaRepository<Affiliation, Long>, JpaSpecificationExecutor<Affiliation> { List<Affiliation> findAllByIsDeletedIsFalse(); Optional<Affiliation> findByIdAndIsDeletedIsFalse(Long id); long countByIsDeletedIsFalse(); }
604
0.84106
0.84106
19
30.789474
31.949926
120
false
false
0
0
0
0
0
0
0.631579
false
false
13
d9761c92976bdda19cff650f9aa1aaef90a2d7ec
8,134,668,110,080
a82bc98011f38558d64d93c9d2eb3c5799449d5e
/kafka-spring-boot/src/main/java/com/ndr/kafka/kafkaspringboot/model/KafkaModel.java
1613dd1585fe1efc0b6fd930e32df5b0afbea9f4
[]
no_license
PRACTICE-NDR/KAFKA-SPRING-BOOT
https://github.com/PRACTICE-NDR/KAFKA-SPRING-BOOT
249c8f35457c83396553494aa73dd81f860c3e5c
9d82b8071411372d841f74df545d1b2490eeace8
refs/heads/master
2023-07-16T16:41:58.081000
2021-08-23T08:12:25
2021-08-23T08:12:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ndr.kafka.kafkaspringboot.model; import com.fasterxml.jackson.annotation.JsonAnySetter; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * @author dinakar on 29/07/21 */ @Setter @Getter @Entity @Table(name = "kafka_model_t") public class KafkaModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "name") private String name; @Column(name = "job_name") private String jobName; public KafkaModel() { } public KafkaModel(String name, int id, String jobName) { this.name = name; this.id = id; this.jobName = jobName; } @Override public String toString() { return "KafkaModel{" + "name='" + name + '\'' + ", id=" + id + ", jobName='" + jobName + '\'' + '}'; } }
UTF-8
Java
1,106
java
KafkaModel.java
Java
[ { "context": "d;\nimport javax.persistence.Table;\n\n/**\n * @author dinakar on 29/07/21\n */\n@Setter\n@Getter\n@Entity\n@Table(na", "end": 378, "score": 0.9996836185455322, "start": 371, "tag": "USERNAME", "value": "dinakar" } ]
null
[]
package com.ndr.kafka.kafkaspringboot.model; import com.fasterxml.jackson.annotation.JsonAnySetter; import lombok.Getter; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * @author dinakar on 29/07/21 */ @Setter @Getter @Entity @Table(name = "kafka_model_t") public class KafkaModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "name") private String name; @Column(name = "job_name") private String jobName; public KafkaModel() { } public KafkaModel(String name, int id, String jobName) { this.name = name; this.id = id; this.jobName = jobName; } @Override public String toString() { return "KafkaModel{" + "name='" + name + '\'' + ", id=" + id + ", jobName='" + jobName + '\'' + '}'; } }
1,106
0.621157
0.615732
50
21.120001
16.375153
60
false
false
0
0
0
0
0
0
0.42
false
false
13
fb470353e6806629f8897976ea47005795b2b951
28,552,942,640,465
cbe591fc69ce7333ce256f2b6204edc90dbcbeb2
/src/com/smart/mis/shared/sale/DeliveryStatus.java
3e346457300a8db8d48dd77898fcd510307011bf
[]
no_license
paktoon/smartmis
https://github.com/paktoon/smartmis
5aa60bdee4544647f0a98a97f3a83bed0c411ed8
332e40274b60591a7c25aba9827892b8b54026a8
refs/heads/master
2020-06-08T06:07:24.703000
2014-02-16T13:07:07
2014-02-16T13:07:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smart.mis.shared.sale; import java.util.LinkedHashMap; public class DeliveryStatus { static LinkedHashMap<String, String> valueMap, issuedValueMap; static { valueMap = new LinkedHashMap<String, String>(); valueMap.put("0_product_request", "กำลังเบิกสินค้า"); valueMap.put("1_on_delivery", "กำลังนำส่ง"); valueMap.put("2_delivery_completed", "นำส่งแล้ว"); issuedValueMap = new LinkedHashMap<String, String>(); issuedValueMap.put("0_product_request", "ขอเบิกสินค้า"); issuedValueMap.put("1_product_issued", "จ่ายสินค้าแล้ว"); } public static LinkedHashMap<String, String> getValueMap() { return valueMap; } public static LinkedHashMap<String, String> getIssueValueMap() { return issuedValueMap; } public static String getDisplay(String value) { return valueMap.get(value); } public static String getIssueDisplay(String value) { return issuedValueMap.get(value); } }
UTF-8
Java
1,146
java
DeliveryStatus.java
Java
[]
null
[]
package com.smart.mis.shared.sale; import java.util.LinkedHashMap; public class DeliveryStatus { static LinkedHashMap<String, String> valueMap, issuedValueMap; static { valueMap = new LinkedHashMap<String, String>(); valueMap.put("0_product_request", "กำลังเบิกสินค้า"); valueMap.put("1_on_delivery", "กำลังนำส่ง"); valueMap.put("2_delivery_completed", "นำส่งแล้ว"); issuedValueMap = new LinkedHashMap<String, String>(); issuedValueMap.put("0_product_request", "ขอเบิกสินค้า"); issuedValueMap.put("1_product_issued", "จ่ายสินค้าแล้ว"); } public static LinkedHashMap<String, String> getValueMap() { return valueMap; } public static LinkedHashMap<String, String> getIssueValueMap() { return issuedValueMap; } public static String getDisplay(String value) { return valueMap.get(value); } public static String getIssueDisplay(String value) { return issuedValueMap.get(value); } }
1,146
0.653021
0.648148
34
28.17647
25.370747
67
false
false
0
0
0
0
0
0
1.323529
false
false
13
4b400614781e8b7656de39629f84b1f16e1d3668
28,552,942,637,219
02023da19a10a9ea42e5bbe0e29a83dc884fa971
/FindingJobs/src/leetCode/Candy.java
fac86bde3112452cd34fe8329ea707c54744fc1a
[]
no_license
liuwei1991/FindingJobs
https://github.com/liuwei1991/FindingJobs
b5127f4f9c354ff9c86f45a79da5073abfa0b257
42eb2bbd83dab43d2499e6c9080e3c4878395fae
refs/heads/master
2021-01-01T06:05:44.260000
2017-05-25T13:06:15
2017-05-25T13:06:15
22,870,456
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetCode; public class Candy { public int candy(int[] ratings) { int result = ratings.length; int record[] = new int[ratings.length]; int num = 1; for(int i=1;i<ratings.length;i++){ if(ratings[i]>ratings[i-1]){ record[i]=num; result += num; num ++; }else{ record[i] = 0; num = 1; } } num = 1; for(int i=ratings.length-2;i>=0;i--){ if(ratings[i]>ratings[i+1]){ result += num; num++; }else{ result-= Math.min(record[i+1], num-1); num = 1; } } return result; } public static void main(String[] args){ Candy c = new Candy(); int[] r = {3,2,1}; // int[] r = {1,2,2}; // int[] r = {1,2,3,4,5,4,3,6}; System.out.println(c.candy(r)); } }
UTF-8
Java
728
java
Candy.java
Java
[]
null
[]
package leetCode; public class Candy { public int candy(int[] ratings) { int result = ratings.length; int record[] = new int[ratings.length]; int num = 1; for(int i=1;i<ratings.length;i++){ if(ratings[i]>ratings[i-1]){ record[i]=num; result += num; num ++; }else{ record[i] = 0; num = 1; } } num = 1; for(int i=ratings.length-2;i>=0;i--){ if(ratings[i]>ratings[i+1]){ result += num; num++; }else{ result-= Math.min(record[i+1], num-1); num = 1; } } return result; } public static void main(String[] args){ Candy c = new Candy(); int[] r = {3,2,1}; // int[] r = {1,2,2}; // int[] r = {1,2,3,4,5,4,3,6}; System.out.println(c.candy(r)); } }
728
0.534341
0.498626
38
18.157894
12.745539
42
false
false
0
0
0
0
0
0
3.210526
false
false
13
cb00f7a21cc4191b4c88f3e97874e0c1c6692f84
31,172,872,638,131
3c0c8986490b2671e50b789ec6a283b7175e2d0f
/src/main/java/algorithmsdecision/bankaccounts/BankAccountDecisionMaker.java
42c62d3041c89249adab82818d3c933225878e65
[]
no_license
dallara81/training-solutions
https://github.com/dallara81/training-solutions
c02d37d9f2a52c1708403b15403f50a7418fd761
434ec91be23fd7ee2f069694ad11d9077b0e3847
refs/heads/master
2023-03-25T02:59:18.782000
2021-03-19T21:54:44
2021-03-19T21:54:44
312,081,560
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithmsdecision.bankaccounts; import java.util.List; public class BankAccountDecisionMaker { public boolean containsBalanceGreaterThan(List<BankAccount> accounts, int limit) { boolean isGreaterThanLimit = false; for (BankAccount account:accounts) { if (account.getBalance() > limit) { isGreaterThanLimit = true; break; } } return isGreaterThanLimit; } }
UTF-8
Java
463
java
BankAccountDecisionMaker.java
Java
[]
null
[]
package algorithmsdecision.bankaccounts; import java.util.List; public class BankAccountDecisionMaker { public boolean containsBalanceGreaterThan(List<BankAccount> accounts, int limit) { boolean isGreaterThanLimit = false; for (BankAccount account:accounts) { if (account.getBalance() > limit) { isGreaterThanLimit = true; break; } } return isGreaterThanLimit; } }
463
0.634989
0.634989
17
26.294117
22.908422
86
false
false
0
0
0
0
0
0
0.411765
false
false
13
875e60dda259d4fd77ea92d5fb4d2867be4152fe
31,172,872,636,894
3db3bb0e454c6c26a6d94da6c0624da409f1275b
/src/main/java/com/chcit/shop/service/impl/DefaultElasticSearchService.java
668134775ee7ca74adc2ea08293f880a49af8a3b
[]
no_license
mzhy1988/elasticsearch
https://github.com/mzhy1988/elasticsearch
a474f078b7a84d7c97fddb66df27f25857619fb6
ad4b66c80b5154a77eea56d36e7b0ed55f825a41
refs/heads/master
2021-06-26T21:20:45.348000
2017-09-16T01:47:14
2017-09-16T01:47:14
103,715,568
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chcit.shop.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.chcit.shop.model.ProductDoc; import com.chcit.shop.repository.ChcitElasticSearchRepository; import com.chcit.shop.service.ElasticSearchService; @Service public class DefaultElasticSearchService implements ElasticSearchService{ @Autowired ChcitElasticSearchRepository elasticSearchRepository; @Override public ProductDoc queryProductInfoById(String id) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductId(id); } @Override public Iterable<ProductDoc> queryProductInfoByProductName(String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductName(name); } @Override public ProductDoc save(ProductDoc productDoc) { // TODO Auto-generated method stub return elasticSearchRepository.save(productDoc); } @Override public Iterable<ProductDoc> findAll() { // TODO Auto-generated method stub return elasticSearchRepository.findAll(); } @Override public Iterable<ProductDoc> queryProductInfoByProductNameLike(String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductNameLike(name); } @Override public Iterable<ProductDoc> queryProductInfoByProductNameContaining( String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductNameContaining(name); } }
UTF-8
Java
1,491
java
DefaultElasticSearchService.java
Java
[]
null
[]
package com.chcit.shop.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.chcit.shop.model.ProductDoc; import com.chcit.shop.repository.ChcitElasticSearchRepository; import com.chcit.shop.service.ElasticSearchService; @Service public class DefaultElasticSearchService implements ElasticSearchService{ @Autowired ChcitElasticSearchRepository elasticSearchRepository; @Override public ProductDoc queryProductInfoById(String id) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductId(id); } @Override public Iterable<ProductDoc> queryProductInfoByProductName(String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductName(name); } @Override public ProductDoc save(ProductDoc productDoc) { // TODO Auto-generated method stub return elasticSearchRepository.save(productDoc); } @Override public Iterable<ProductDoc> findAll() { // TODO Auto-generated method stub return elasticSearchRepository.findAll(); } @Override public Iterable<ProductDoc> queryProductInfoByProductNameLike(String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductNameLike(name); } @Override public Iterable<ProductDoc> queryProductInfoByProductNameContaining( String name) { // TODO Auto-generated method stub return elasticSearchRepository.findByProductNameContaining(name); } }
1,491
0.812877
0.812877
53
27.132076
25.53949
77
false
false
0
0
0
0
0
0
1.132075
false
false
13
0dc4c0a4c05d0bf0a77e5c8f93c7d75cbf2b478d
4,123,168,656,441
fd896aa67b0a1137abf7ad1bdf779194a0ac7eb9
/app/src/main/java/inventarioreal/com/inventarioreal_admin/pojo/WebServices/requests/SyncRequest.java
434c32ac39a107d1a8e46f16c6a3f3e92115c4ea
[]
no_license
jamper91a/ir-app-admin
https://github.com/jamper91a/ir-app-admin
56b82ffc6218ce7948487c8855bd43ef38ab2138
75128b6005e8ec0593a2270010afa682d70260c1
refs/heads/master
2021-06-30T05:57:45.158000
2020-08-19T22:38:16
2020-08-19T22:38:16
171,799,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package inventarioreal.com.inventarioreal_admin.pojo.WebServices.requests; import com.google.gson.Gson; import java.util.HashMap; import inventarioreal.com.inventarioreal_admin.util.Constants; import inventarioreal.com.inventarioreal_admin.util.WebServices.RequestWebServiceInterface; public class SyncRequest implements RequestWebServiceInterface { private String last_update; public SyncRequest() { } public SyncRequest(String last_update) { this.last_update = last_update; } public String getLast_update() { return last_update; } public void setLast_update(String last_update) { this.last_update = last_update; } public HashMap<String, String> getCampos(){ HashMap<String, String> campos = new HashMap<>(); campos.put(Constants.last_updated, getLast_update()); return campos; } }
UTF-8
Java
889
java
SyncRequest.java
Java
[]
null
[]
package inventarioreal.com.inventarioreal_admin.pojo.WebServices.requests; import com.google.gson.Gson; import java.util.HashMap; import inventarioreal.com.inventarioreal_admin.util.Constants; import inventarioreal.com.inventarioreal_admin.util.WebServices.RequestWebServiceInterface; public class SyncRequest implements RequestWebServiceInterface { private String last_update; public SyncRequest() { } public SyncRequest(String last_update) { this.last_update = last_update; } public String getLast_update() { return last_update; } public void setLast_update(String last_update) { this.last_update = last_update; } public HashMap<String, String> getCampos(){ HashMap<String, String> campos = new HashMap<>(); campos.put(Constants.last_updated, getLast_update()); return campos; } }
889
0.708661
0.708661
36
23.638889
25.885595
91
false
false
0
0
0
0
0
0
0.416667
false
false
13
4cd6d667ae1353a12c0ce4d5914721a8630262c2
18,837,726,618,399
b5ad3e65a5ee22bebe7e5aec006ffa756482dd72
/sp5-chap06/src/main/java/spring/Greeter.java
bcc5cc81ad7b6fffcac6a202353ee23a18ae8eb0
[]
no_license
Seo-Ji-soo/Spring5fs
https://github.com/Seo-Ji-soo/Spring5fs
a67dacf11d4075b2b2095f0fa290661aca7c59d1
b970ff5b21f0ffb4597b0d7971d78a10c8e12560
refs/heads/main
2023-02-24T22:06:57.954000
2021-01-31T14:26:02
2021-01-31T14:26:02
307,324,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package spring; public class Greeter { // 콘솔에 간단한 메시지를 출력하는 자바 클래스 private String format; // format 필드는 setFormat() 메서드로 설정함. public String greet(String guest) { return String.format(format, guest); } public String greet1(String guest) { return String.format(format, guest); } public void setFormat(String format) { this.format = format; } }
UTF-8
Java
428
java
Greeter.java
Java
[]
null
[]
package spring; public class Greeter { // 콘솔에 간단한 메시지를 출력하는 자바 클래스 private String format; // format 필드는 setFormat() 메서드로 설정함. public String greet(String guest) { return String.format(format, guest); } public String greet1(String guest) { return String.format(format, guest); } public void setFormat(String format) { this.format = format; } }
428
0.691892
0.689189
22
15.772727
17.448448
50
false
false
0
0
0
0
0
0
1.181818
false
false
13
c8b3c48e1c5d6e85c9e7410a049eb1155c166b77
17,549,236,436,715
20824d156726ade2572639539dac8e59c2053602
/Hello.java
e058623b1e36d8ba1c5da1f35e7d4417f84acad6
[]
no_license
MamathaShivanna/JavaHello
https://github.com/MamathaShivanna/JavaHello
18f5735c25772c4053824b04011fdbc9a8eca872
d8d8a051e19365c7989fedebf57d4b236f3928d7
refs/heads/master
2020-03-21T02:19:18.318000
2018-06-22T05:48:37
2018-06-22T05:48:37
137,993,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Hello { public static void main(String []args) { System.out.println("hell world"); System.out.println("Brach name -- Master branch " ); } }
UTF-8
Java
160
java
Hello.java
Java
[]
null
[]
public class Hello { public static void main(String []args) { System.out.println("hell world"); System.out.println("Brach name -- Master branch " ); } }
160
0.675
0.675
8
19
19.72942
54
false
false
0
0
0
0
0
0
0.875
false
false
13
df673f5cc534ca4883717f21880931fe05e18671
24,532,853,199,287
7b4b06798bdc94ffc0122ce3aa2b4bd437a8d2b5
/code/hejiaqin/framework/src/main/java/com/customer/framework/utils/cryptor/AES.java
648aef894eb3cde82b3d9d99c0d8a36ff4c32fa5
[]
no_license
showme890/hejiaqin
https://github.com/showme890/hejiaqin
5697871c04bced3757837bbdd9d63ffb5c421fe3
3156f46806783ff98e4da8bb56a9539445766df9
refs/heads/master
2021-06-23T07:44:02.428000
2017-06-26T12:52:29
2017-06-26T12:52:29
267,469,927
0
1
null
true
2020-05-28T02:02:47
2020-05-28T02:02:47
2019-04-08T04:05:22
2017-06-26T12:52:56
93,486
0
0
0
null
false
false
package com.customer.framework.utils.cryptor; import com.customer.framework.utils.LogUtil; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * AES加解密 * 对称加密算法(秘钥一样) * @author Yangjianliang datetime 2009-8-16 */ public final class AES { private static final String TAG = "AES"; /** * 编码 */ static final String ENCODE_TYPE = "UTF8"; /** * DES升级版 */ static final String KEY_TYPE_AES = "AES";//"算法/模式/补码方式" static final String CIPHER_TYPE_AES = "AES/ECB/PKCS5Padding";//"算法/模式/补码方式" /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static String encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance(KEY_TYPE_AES); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_TYPE_AES); Cipher cipher = Cipher.getInstance(CIPHER_TYPE_AES);// 创建密码器 byte[] byteContent = content.getBytes(ENCODE_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); String resultString = parseByte2HexStr(result); return resultString; // 加密 } catch (NoSuchAlgorithmException e) { LogUtil.e(TAG, e); } catch (NoSuchPaddingException e) { LogUtil.e(TAG, e); } catch (InvalidKeyException e) { LogUtil.e(TAG, e); } catch (UnsupportedEncodingException e) { LogUtil.e(TAG, e); } catch (IllegalBlockSizeException e) { LogUtil.e(TAG, e); } catch (BadPaddingException e) { LogUtil.e(TAG, e); } return null; } /** * 解密 * * @param content 待解密内容 * @param password 解密密钥 * @return */ public static String decrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance(KEY_TYPE_AES); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_TYPE_AES); Cipher cipher = Cipher.getInstance(CIPHER_TYPE_AES);// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] cont = parseHexStr2Byte(content); byte[] result = cipher.doFinal(cont); String resultString = new String(result); return resultString; } catch (NoSuchAlgorithmException e) { LogUtil.e(TAG, e); } catch (NoSuchPaddingException e) { LogUtil.e(TAG, e); } catch (InvalidKeyException e) { LogUtil.e(TAG, e); } catch (IllegalBlockSizeException e) { LogUtil.e(TAG, e); } catch (BadPaddingException e) { LogUtil.e(TAG, e); } return null; } /** * 将二进制转换成16进制 * * @param buf * @return */ public static String parseByte2HexStr(byte[] buf) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) { String content = "test"; String password = "12345678"; //加密 System.out.println("加密前:" + content); String encryptResult = encrypt(content, password); System.out.println(encryptResult); //解密 String decryptResult = decrypt(encryptResult, password); System.out.println("解密后:" + decryptResult); } }
UTF-8
Java
5,211
java
AES.java
Java
[ { "context": "KeySpec;\n\n/**\n * AES加解密\n * 对称加密算法(秘钥一样)\n * @author Yangjianliang datetime 2009-8-16\n */\npublic final class AES {\n\n", "end": 583, "score": 0.8970665335655212, "start": 570, "tag": "NAME", "value": "Yangjianliang" }, { "context": " * @param content 需要加密的内容\n * @param password 加密密码\n * @return\n */\n public static String e", "end": 1006, "score": 0.9944541454315186, "start": 1002, "tag": "PASSWORD", "value": "加密密码" }, { "context": "ring content = \"test\";\n String password = \"12345678\";\n //加密\n System.out.println(\"加密前:\" ", "end": 4691, "score": 0.9992241263389587, "start": 4683, "tag": "PASSWORD", "value": "12345678" } ]
null
[]
package com.customer.framework.utils.cryptor; import com.customer.framework.utils.LogUtil; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * AES加解密 * 对称加密算法(秘钥一样) * @author Yangjianliang datetime 2009-8-16 */ public final class AES { private static final String TAG = "AES"; /** * 编码 */ static final String ENCODE_TYPE = "UTF8"; /** * DES升级版 */ static final String KEY_TYPE_AES = "AES";//"算法/模式/补码方式" static final String CIPHER_TYPE_AES = "AES/ECB/PKCS5Padding";//"算法/模式/补码方式" /** * 加密 * * @param content 需要加密的内容 * @param password <PASSWORD> * @return */ public static String encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance(KEY_TYPE_AES); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_TYPE_AES); Cipher cipher = Cipher.getInstance(CIPHER_TYPE_AES);// 创建密码器 byte[] byteContent = content.getBytes(ENCODE_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); String resultString = parseByte2HexStr(result); return resultString; // 加密 } catch (NoSuchAlgorithmException e) { LogUtil.e(TAG, e); } catch (NoSuchPaddingException e) { LogUtil.e(TAG, e); } catch (InvalidKeyException e) { LogUtil.e(TAG, e); } catch (UnsupportedEncodingException e) { LogUtil.e(TAG, e); } catch (IllegalBlockSizeException e) { LogUtil.e(TAG, e); } catch (BadPaddingException e) { LogUtil.e(TAG, e); } return null; } /** * 解密 * * @param content 待解密内容 * @param password 解密密钥 * @return */ public static String decrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance(KEY_TYPE_AES); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_TYPE_AES); Cipher cipher = Cipher.getInstance(CIPHER_TYPE_AES);// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] cont = parseHexStr2Byte(content); byte[] result = cipher.doFinal(cont); String resultString = new String(result); return resultString; } catch (NoSuchAlgorithmException e) { LogUtil.e(TAG, e); } catch (NoSuchPaddingException e) { LogUtil.e(TAG, e); } catch (InvalidKeyException e) { LogUtil.e(TAG, e); } catch (IllegalBlockSizeException e) { LogUtil.e(TAG, e); } catch (BadPaddingException e) { LogUtil.e(TAG, e); } return null; } /** * 将二进制转换成16进制 * * @param buf * @return */ public static String parseByte2HexStr(byte[] buf) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) { String content = "test"; String password = "<PASSWORD>"; //加密 System.out.println("加密前:" + content); String encryptResult = encrypt(content, password); System.out.println(encryptResult); //解密 String decryptResult = decrypt(encryptResult, password); System.out.println("解密后:" + decryptResult); } }
5,211
0.580581
0.57017
160
30.21875
22.613512
83
false
false
0
0
0
0
0
0
0.61875
false
false
13
53b51e91e3a7b671738c23d202517e1a0c49ce0e
30,227,979,896,884
ef0c1514e9af6de3ba4a20e0d01de7cc3a915188
/sdk/maps/azure-maps-timezone/src/main/java/com/azure/maps/timezone/models/TimeZoneOptions.java
1c68ebec3852dc161d566411fc7c02e3d4169265
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
Azure/azure-sdk-for-java
https://github.com/Azure/azure-sdk-for-java
0902d584b42d3654b4ce65b1dad8409f18ddf4bc
789bdc6c065dc44ce9b8b630e2f2e5896b2a7616
refs/heads/main
2023-09-04T09:36:35.821000
2023-09-02T01:53:56
2023-09-02T01:53:56
2,928,948
2,027
2,084
MIT
false
2023-09-14T21:37:15
2011-12-06T23:33:56
2023-09-14T17:19:10
2023-09-14T21:37:14
3,043,660
1,994
1,854
1,435
Java
false
false
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.maps.timezone.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for TimezoneOptions. */ public final class TimeZoneOptions extends ExpandableStringEnum<TimeZoneOptions> { /** Static value none for TimezoneOptions. */ public static final TimeZoneOptions NONE = fromString("none"); /** Static value zoneInfo for TimezoneOptions. */ public static final TimeZoneOptions ZONE_INFO = fromString("zoneInfo"); /** Static value transitions for TimezoneOptions. */ public static final TimeZoneOptions TRANSITIONS = fromString("transitions"); /** Static value all for TimezoneOptions. */ public static final TimeZoneOptions ALL = fromString("all"); /** * Creates or finds a TimezoneOptions from its string representation. * * @param name a name to look for. * @return the corresponding TimezoneOptions. */ @JsonCreator public static TimeZoneOptions fromString(String name) { return fromString(name, TimeZoneOptions.class); } /** * Gets known TimezoneOptions values. * * @return known TimezoneOptions values. */ public static Collection<TimeZoneOptions> values() { return values(TimeZoneOptions.class); } }
UTF-8
Java
1,506
java
TimeZoneOptions.java
Java
[]
null
[]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.maps.timezone.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for TimezoneOptions. */ public final class TimeZoneOptions extends ExpandableStringEnum<TimeZoneOptions> { /** Static value none for TimezoneOptions. */ public static final TimeZoneOptions NONE = fromString("none"); /** Static value zoneInfo for TimezoneOptions. */ public static final TimeZoneOptions ZONE_INFO = fromString("zoneInfo"); /** Static value transitions for TimezoneOptions. */ public static final TimeZoneOptions TRANSITIONS = fromString("transitions"); /** Static value all for TimezoneOptions. */ public static final TimeZoneOptions ALL = fromString("all"); /** * Creates or finds a TimezoneOptions from its string representation. * * @param name a name to look for. * @return the corresponding TimezoneOptions. */ @JsonCreator public static TimeZoneOptions fromString(String name) { return fromString(name, TimeZoneOptions.class); } /** * Gets known TimezoneOptions values. * * @return known TimezoneOptions values. */ public static Collection<TimeZoneOptions> values() { return values(TimeZoneOptions.class); } }
1,506
0.718459
0.718459
44
33.227272
26.807278
82
false
false
0
0
0
0
0
0
0.25
false
false
13
833e18bc08b3874b5316ce9dd6c616feaf324140
28,973,849,381,261
e05a290f18b0ae8089709f4fbe92f3f49042daee
/registration/registration-service/src/main/java/io/mosip/registration/dto/PacketStatusDTO.java
f94844364d812550921ab80b20439d29910070eb
[]
no_license
Aswin-MN/personal
https://github.com/Aswin-MN/personal
25e6d6bf306e61a236d0ea886d33ea621bb7dc56
d096fa6ab16e13a66a82be0325cf4d117d3669f3
refs/heads/master
2021-10-11T16:24:08.604000
2019-01-28T12:52:41
2019-01-28T12:52:41
166,238,628
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.mosip.registration.dto; public class PacketStatusDTO { private String sourcePath; private String fileName; private String uploadStatus; private String uploadTime; private String remarks; public String getSourcePath() { return sourcePath; } public void setSourcePath(String sourcePath) { this.sourcePath = sourcePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUploadStatus() { return uploadStatus; } public void setUploadStatus(String uploadStatus) { this.uploadStatus = uploadStatus; } public String getUploadTime() { return uploadTime; } public void setUploadTime(String uploadTime) { this.uploadTime = uploadTime; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
UTF-8
Java
891
java
PacketStatusDTO.java
Java
[]
null
[]
package io.mosip.registration.dto; public class PacketStatusDTO { private String sourcePath; private String fileName; private String uploadStatus; private String uploadTime; private String remarks; public String getSourcePath() { return sourcePath; } public void setSourcePath(String sourcePath) { this.sourcePath = sourcePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUploadStatus() { return uploadStatus; } public void setUploadStatus(String uploadStatus) { this.uploadStatus = uploadStatus; } public String getUploadTime() { return uploadTime; } public void setUploadTime(String uploadTime) { this.uploadTime = uploadTime; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
891
0.750842
0.750842
41
20.731707
15.513997
51
false
false
0
0
0
0
0
0
1.512195
false
false
13
90700debf6887d3cac528d6998f790a64de32ff7
23,630,910,126,941
00ce5d92e499d43cf0bc29b77e56194fab41d0da
/app/src/main/java/com/ogsteam/ogspy/notification/NotificationProvider.java
9b4e686ba5d9338c3ebde4f69d1ad8ae64a2b3f3
[]
no_license
OGSteam/ogspy-android
https://github.com/OGSteam/ogspy-android
68d6dbeb1427c53034f0e0528d3088ea306dc228
956b405d764305c9cb6640f690cfda073cf80673
refs/heads/master
2021-01-12T04:34:52.331000
2017-02-17T16:22:15
2017-02-17T16:22:15
76,646,370
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ogsteam.ogspy.notification; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.support.v4.app.NotificationCompat; import com.ogsteam.ogspy.OgspyActivity; import com.ogsteam.ogspy.R; import com.ogsteam.ogspy.utils.StringUtils; public class NotificationProvider { public static boolean notifHostilesAlreadyDone = false; private int NOTIFICATION_ID_HOSTILES = 0; private int NOTIFICATION_ID_MESSAGES = 0; private Activity activity; public NotificationProvider(Activity activity) { this.activity = activity; } public final void createNotificationHostile(String details) { final NotificationManager mNotification = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE); final Intent launchNotifiactionIntent = new Intent(activity, OgspyActivity.class); final PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, launchNotifiactionIntent, PendingIntent.FLAG_ONE_SHOT); // Notification Icons Bitmap largeIcon = ((BitmapDrawable) activity.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(); int smallIcon = R.drawable.hostiles_simple_attack; // Notifications details String notificationTitle = "OGSPY"; String notificationContent = activity.getResources().getString(R.string.notification_title_hostiles); Notification notif = new NotificationCompat.Builder(activity) .setWhen(System.currentTimeMillis()) .setLargeIcon(largeIcon) .setSmallIcon(smallIcon) .setTicker(notificationTitle) .setContentTitle(notificationContent) .setContentText(getTextNotificationHostiles(details)) .setContentIntent(pendingIntent) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND) // Play default notification sound .setDefaults(Notification.DEFAULT_VIBRATE) // Vibrate if vibrate is enabled .build(); mNotification.notify(NOTIFICATION_ID_HOSTILES, notif); NOTIFICATION_ID_HOSTILES++; } public final void createNotificationMessage(String details, String sender) { final NotificationManager mNotification = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE); final Intent launchNotifiactionIntent = new Intent(activity, OgspyActivity.class); final PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, launchNotifiactionIntent, PendingIntent.FLAG_ONE_SHOT); // Notification Icons Bitmap largeIcon = ((BitmapDrawable) activity.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(); int smallIcon = R.drawable.notification_message; // Notifications details String notificationTitle = "OGSPY"; String notificationContent = activity.getResources().getString(R.string.notification_title_message); Notification notif = new NotificationCompat.Builder(activity) .setWhen(System.currentTimeMillis()) .setLargeIcon(largeIcon) .setSmallIcon(smallIcon) .setTicker(notificationTitle) .setContentTitle(StringUtils.formatPattern(notificationContent, sender)) .setContentText(details) .setContentIntent(pendingIntent) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND) // Play default notification sound .setDefaults(Notification.DEFAULT_VIBRATE) // Vibrate if vibrate is enabled .build(); mNotification.notify(NOTIFICATION_ID_MESSAGES, notif); NOTIFICATION_ID_MESSAGES++; } public void deleteNotificationHostile() { final NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); //la suppression de la notification se fait grâce a son ID for (int i = 0; i < NOTIFICATION_ID_HOSTILES; i++) { notificationManager.cancel(i); } } private String getTextNotificationHostiles(String details) { return StringUtils.formatPattern(activity.getResources().getString(R.string.notification_desc), details); } }
UTF-8
Java
4,682
java
NotificationProvider.java
Java
[]
null
[]
package com.ogsteam.ogspy.notification; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.support.v4.app.NotificationCompat; import com.ogsteam.ogspy.OgspyActivity; import com.ogsteam.ogspy.R; import com.ogsteam.ogspy.utils.StringUtils; public class NotificationProvider { public static boolean notifHostilesAlreadyDone = false; private int NOTIFICATION_ID_HOSTILES = 0; private int NOTIFICATION_ID_MESSAGES = 0; private Activity activity; public NotificationProvider(Activity activity) { this.activity = activity; } public final void createNotificationHostile(String details) { final NotificationManager mNotification = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE); final Intent launchNotifiactionIntent = new Intent(activity, OgspyActivity.class); final PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, launchNotifiactionIntent, PendingIntent.FLAG_ONE_SHOT); // Notification Icons Bitmap largeIcon = ((BitmapDrawable) activity.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(); int smallIcon = R.drawable.hostiles_simple_attack; // Notifications details String notificationTitle = "OGSPY"; String notificationContent = activity.getResources().getString(R.string.notification_title_hostiles); Notification notif = new NotificationCompat.Builder(activity) .setWhen(System.currentTimeMillis()) .setLargeIcon(largeIcon) .setSmallIcon(smallIcon) .setTicker(notificationTitle) .setContentTitle(notificationContent) .setContentText(getTextNotificationHostiles(details)) .setContentIntent(pendingIntent) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND) // Play default notification sound .setDefaults(Notification.DEFAULT_VIBRATE) // Vibrate if vibrate is enabled .build(); mNotification.notify(NOTIFICATION_ID_HOSTILES, notif); NOTIFICATION_ID_HOSTILES++; } public final void createNotificationMessage(String details, String sender) { final NotificationManager mNotification = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE); final Intent launchNotifiactionIntent = new Intent(activity, OgspyActivity.class); final PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, launchNotifiactionIntent, PendingIntent.FLAG_ONE_SHOT); // Notification Icons Bitmap largeIcon = ((BitmapDrawable) activity.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap(); int smallIcon = R.drawable.notification_message; // Notifications details String notificationTitle = "OGSPY"; String notificationContent = activity.getResources().getString(R.string.notification_title_message); Notification notif = new NotificationCompat.Builder(activity) .setWhen(System.currentTimeMillis()) .setLargeIcon(largeIcon) .setSmallIcon(smallIcon) .setTicker(notificationTitle) .setContentTitle(StringUtils.formatPattern(notificationContent, sender)) .setContentText(details) .setContentIntent(pendingIntent) .setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND) // Play default notification sound .setDefaults(Notification.DEFAULT_VIBRATE) // Vibrate if vibrate is enabled .build(); mNotification.notify(NOTIFICATION_ID_MESSAGES, notif); NOTIFICATION_ID_MESSAGES++; } public void deleteNotificationHostile() { final NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); //la suppression de la notification se fait grâce a son ID for (int i = 0; i < NOTIFICATION_ID_HOSTILES; i++) { notificationManager.cancel(i); } } private String getTextNotificationHostiles(String details) { return StringUtils.formatPattern(activity.getResources().getString(R.string.notification_desc), details); } }
4,682
0.692801
0.691519
101
44.346535
36.7869
138
false
false
0
0
0
0
0
0
0.554455
false
false
13
e7fb567635547b92de7596ec0228d8d5c0232dbc
6,571,300,028,733
c75296ab8eac301cc551ed281a29032fedc84fc1
/ifreebudget/src/com/ifreebudget/fm/utils/ActivityUtils.java
b6c18516ec288636c6446d254783c13648af13d1
[]
no_license
wangji74/ifreebudget-android
https://github.com/wangji74/ifreebudget-android
6c8363166fcbc1840765c9e2056098e37161efce
7cb7a0efdf7629ee8c23f2755d5940e425b5fb6a
refs/heads/master
2021-01-10T01:33:25.212000
2012-02-16T04:05:12
2012-02-16T04:05:12
50,930,940
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ifreebudget.fm.utils; import java.util.ArrayList; import android.util.Log; import com.ifreebudget.fm.constants.AccountTypes; import com.ifreebudget.fm.entity.DBException; import com.ifreebudget.fm.entity.FManEntityManager; import com.ifreebudget.fm.entity.beans.AccountCategory; public class ActivityUtils { private static final String TAG = "ActivityUtils"; public static String getCategoryPath(Long categoryId) { StringBuilder ret = new StringBuilder(); int lim = 100; ArrayList<String> list = new ArrayList<String>(); if (categoryId != AccountTypes.ACCT_TYPE_ROOT) { int i = 0; long lastCategoryId = categoryId; while (i++ < lim) { try { AccountCategory ac = FManEntityManager.getInstance() .getAccountCategory(lastCategoryId); list.add(ac.getCategoryName()); if (ac.getParentCategoryId() == AccountTypes.ACCT_TYPE_ROOT) { break; } lastCategoryId = ac.getParentCategoryId(); } catch (DBException e) { Log.e(TAG + ".getCategoryPath", MiscUtils.stackTrace2String(e)); } } int sz = list.size(); for (i = sz - 1; i >= 0; i--) { ret.append(list.get(i)); if (i > 0) { ret.append(" > "); } } } return ret.toString(); } }
UTF-8
Java
1,613
java
ActivityUtils.java
Java
[]
null
[]
package com.ifreebudget.fm.utils; import java.util.ArrayList; import android.util.Log; import com.ifreebudget.fm.constants.AccountTypes; import com.ifreebudget.fm.entity.DBException; import com.ifreebudget.fm.entity.FManEntityManager; import com.ifreebudget.fm.entity.beans.AccountCategory; public class ActivityUtils { private static final String TAG = "ActivityUtils"; public static String getCategoryPath(Long categoryId) { StringBuilder ret = new StringBuilder(); int lim = 100; ArrayList<String> list = new ArrayList<String>(); if (categoryId != AccountTypes.ACCT_TYPE_ROOT) { int i = 0; long lastCategoryId = categoryId; while (i++ < lim) { try { AccountCategory ac = FManEntityManager.getInstance() .getAccountCategory(lastCategoryId); list.add(ac.getCategoryName()); if (ac.getParentCategoryId() == AccountTypes.ACCT_TYPE_ROOT) { break; } lastCategoryId = ac.getParentCategoryId(); } catch (DBException e) { Log.e(TAG + ".getCategoryPath", MiscUtils.stackTrace2String(e)); } } int sz = list.size(); for (i = sz - 1; i >= 0; i--) { ret.append(list.get(i)); if (i > 0) { ret.append(" > "); } } } return ret.toString(); } }
1,613
0.520769
0.515809
50
31.26
22.06428
82
false
false
0
0
0
0
0
0
0.5
false
false
13
adb2c179dce1a8244518878b22f31307c3310554
23,708,219,491,360
62507597c9fa6c7e04eeaf31977a0d45c33fcf2b
/app/src/main/java/us/originally/teamtrack/modules/audio/AudioStreamManager.java
07e97a543fd9d6d5e13f369a1d4040d785b41ceb
[]
no_license
solominh/team-tracking-firebase
https://github.com/solominh/team-tracking-firebase
284ce1488a4a73c2f283ef9643bc53da77589796
5ce15d6eaa380254613896bcfbc9df69744eab69
refs/heads/master
2021-01-15T16:29:25.833000
2015-09-19T13:41:17
2015-09-19T13:41:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package us.originally.teamtrack.modules.audio; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.util.Base64; import android.util.Log; import de.greenrobot.event.EventBus; import us.originally.teamtrack.EventBus.VisualizeEvent; import us.originally.teamtrack.models.AudioModel; import us.originally.teamtrack.models.UserTeamModel; import us.originally.teamtrack.modules.dagger.managers.UserManager; /** * Created by VietHoa on 07/09/15. */ public class AudioStreamManager { private static final String LOG_TAG = "AudioStreamManager"; private static AudioRecord mRecorder = null; private static AudioTrack mPlayer = null; private static int sampleRate = 8000; //44100; private static int channelConfig = AudioFormat.CHANNEL_IN_MONO; private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT; private static int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); private static int bufferSize = 10240; private static CMG711 uLawCodec = new CMG711(); private static EventBus eventBus = new EventBus(); private static int audio_limit_id = 50; //********************************************************************************************** // Player //********************************************************************************************** protected static void initialisePlayer() { mPlayer = new AudioTrack(android.media.AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufSize, AudioTrack.MODE_STREAM); mPlayer.play(); } public static void startPlaying(final AudioModel audioModel) { if (mPlayer == null) { initialisePlayer(); } //Base 64 decode byte[] audio = Base64.decode(audioModel.encode, 2); //uLaw Decoding final byte[] byteArray = new byte[audioModel.size * 2]; uLawCodec.decode(audio, 0, audioModel.size, byteArray); //Play final byte[] buffer = byteArray; new Thread(new Runnable() { @Override public void run() { synchronized (mPlayer) { mPlayer.write(buffer, 0, audioModel.size); } } }).start(); } public static void stopPlaying() { if (mPlayer == null) return; mPlayer.release(); mPlayer = null; } //********************************************************************************************** // Recorder //********************************************************************************************** public static boolean isRecording() { return mRecorder != null; } public static void startRecording(UserTeamModel user, UserManager userManager) { mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufSize * 10); mRecorder.startRecording(); int audioId = 0; //Encoding: byte[] buffer = new byte[bufferSize]; byte[] outBuffer = new byte[bufferSize]; int size; //Capture audio while (mRecorder != null) { size = mRecorder.read(buffer, 0, buffer.length); //Take audio waveform float soundValue = calculatePowerDb(buffer, size); eventBus.getDefault().post(new VisualizeEvent(soundValue)); //uLaw Encoding: uLawCodec.encode(buffer, 0, size, outBuffer); //Base64 encoding String strEncoded = Base64.encodeToString(outBuffer, 2); //Stream audio data audioId += 1; if (audioId > audio_limit_id) { audioId = 1; } long timeStamp = System.currentTimeMillis(); AudioModel audio = new AudioModel(strEncoded, size, audioId, timeStamp, user); userManager.pushAudio(audio); } } public static void stopRecording() { if (mRecorder == null) return; mRecorder.stop(); mRecorder.release(); mRecorder = null; Log.d(LOG_TAG, "encode: stop"); } protected static float calculatePowerDb(byte[] buffer, int readSize) { if (readSize <= 0) return 0; float max = 0; for (int i = 0; i < readSize; i+=2) { int intSample = (buffer[i+1] << 8) | (buffer[i]) & 0xFF; float floatSample = intSample / 32767.0f; floatSample = Math.abs(floatSample); max = Math.max(floatSample, max); } return max; } }
UTF-8
Java
4,805
java
AudioStreamManager.java
Java
[ { "context": "es.dagger.managers.UserManager;\n\n/**\n * Created by VietHoa on 07/09/15.\n */\npublic class AudioStreamManager ", "end": 529, "score": 0.9894925355911255, "start": 522, "tag": "NAME", "value": "VietHoa" } ]
null
[]
package us.originally.teamtrack.modules.audio; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.util.Base64; import android.util.Log; import de.greenrobot.event.EventBus; import us.originally.teamtrack.EventBus.VisualizeEvent; import us.originally.teamtrack.models.AudioModel; import us.originally.teamtrack.models.UserTeamModel; import us.originally.teamtrack.modules.dagger.managers.UserManager; /** * Created by VietHoa on 07/09/15. */ public class AudioStreamManager { private static final String LOG_TAG = "AudioStreamManager"; private static AudioRecord mRecorder = null; private static AudioTrack mPlayer = null; private static int sampleRate = 8000; //44100; private static int channelConfig = AudioFormat.CHANNEL_IN_MONO; private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT; private static int minBufSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat); private static int bufferSize = 10240; private static CMG711 uLawCodec = new CMG711(); private static EventBus eventBus = new EventBus(); private static int audio_limit_id = 50; //********************************************************************************************** // Player //********************************************************************************************** protected static void initialisePlayer() { mPlayer = new AudioTrack(android.media.AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufSize, AudioTrack.MODE_STREAM); mPlayer.play(); } public static void startPlaying(final AudioModel audioModel) { if (mPlayer == null) { initialisePlayer(); } //Base 64 decode byte[] audio = Base64.decode(audioModel.encode, 2); //uLaw Decoding final byte[] byteArray = new byte[audioModel.size * 2]; uLawCodec.decode(audio, 0, audioModel.size, byteArray); //Play final byte[] buffer = byteArray; new Thread(new Runnable() { @Override public void run() { synchronized (mPlayer) { mPlayer.write(buffer, 0, audioModel.size); } } }).start(); } public static void stopPlaying() { if (mPlayer == null) return; mPlayer.release(); mPlayer = null; } //********************************************************************************************** // Recorder //********************************************************************************************** public static boolean isRecording() { return mRecorder != null; } public static void startRecording(UserTeamModel user, UserManager userManager) { mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufSize * 10); mRecorder.startRecording(); int audioId = 0; //Encoding: byte[] buffer = new byte[bufferSize]; byte[] outBuffer = new byte[bufferSize]; int size; //Capture audio while (mRecorder != null) { size = mRecorder.read(buffer, 0, buffer.length); //Take audio waveform float soundValue = calculatePowerDb(buffer, size); eventBus.getDefault().post(new VisualizeEvent(soundValue)); //uLaw Encoding: uLawCodec.encode(buffer, 0, size, outBuffer); //Base64 encoding String strEncoded = Base64.encodeToString(outBuffer, 2); //Stream audio data audioId += 1; if (audioId > audio_limit_id) { audioId = 1; } long timeStamp = System.currentTimeMillis(); AudioModel audio = new AudioModel(strEncoded, size, audioId, timeStamp, user); userManager.pushAudio(audio); } } public static void stopRecording() { if (mRecorder == null) return; mRecorder.stop(); mRecorder.release(); mRecorder = null; Log.d(LOG_TAG, "encode: stop"); } protected static float calculatePowerDb(byte[] buffer, int readSize) { if (readSize <= 0) return 0; float max = 0; for (int i = 0; i < readSize; i+=2) { int intSample = (buffer[i+1] << 8) | (buffer[i]) & 0xFF; float floatSample = intSample / 32767.0f; floatSample = Math.abs(floatSample); max = Math.max(floatSample, max); } return max; } }
4,805
0.567118
0.552966
146
31.910959
27.763166
124
false
false
0
0
0
0
0
0
0.684932
false
false
13
8907e3e7d61f5de9b76e20509110b5d4f0b287b8
31,954,556,722,687
c392c7639b77fa5b073dc36c762e8ccb2bc786b0
/app/src/main/java/com/tencent/liteav/demo/videoupload/impl/UGCClient.java
dbd3a67bb2602bc32365e470ad4ff72055bff32c
[]
no_license
aiyaapp/AiyaEffectsWithTengxunyunAndroid
https://github.com/aiyaapp/AiyaEffectsWithTengxunyunAndroid
891fe4c8253d54c8c1bcdea73b0c3868ec9268fc
b176f99e12b05f1f537a8919525c6e479da984ee
refs/heads/master
2021-06-02T02:38:46.328000
2020-02-17T06:56:31
2020-02-17T06:56:31
112,185,009
4
5
null
false
2019-04-04T06:31:49
2017-11-27T10:58:18
2019-04-04T06:31:04
2019-04-04T06:31:00
89,330
1
2
0
Java
false
false
package com.tencent.liteav.demo.videoupload.impl; import android.content.Context; import android.os.Handler; import com.tencent.liteav.basic.log.TXCLog; import org.json.JSONException; import org.json.JSONObject; import java.util.concurrent.TimeUnit; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; /** * UGC Client */ public class UGCClient { private final static String TAG = "TVC-UGCClient"; private Context context; private String signature; private OkHttpClient okHttpClient; private Handler mainHandler; // private static String TEST_SERVER = "http://112.90.82.173/v3/index.php?Action="; private static String SERVER = "https://vod2.qcloud.com/v3/index.php?Action="; public UGCClient(Context context, String signature, int iTimeOut) { this.context = context; this.signature = signature; okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(iTimeOut, TimeUnit.SECONDS) // 设置超时时间 .readTimeout(iTimeOut, TimeUnit.SECONDS) // 设置读取超时时间 .writeTimeout(iTimeOut, TimeUnit.SECONDS) // 设置写入超时时间 .build(); mainHandler = new Handler(context.getMainLooper()); } // private String getCommonReqPath(String interfaceName) { // return SERVER + interfaceName // + "&Region=gz" // + "&Timestamp=" + String.valueOf(System.currentTimeMillis() / 1000) // + "&Nonce=" + String.valueOf((int) Math.random() * 65535 + 1) // + "&SecretId=" + URLEncoder.encode(scretId) // + "&Signature=" + URLEncoder.encode(signature); // } /** * 申请上传(UGC接口) * * @param info 文件信息 * @param callback 回调 * @return */ public int initUploadUGC(TVCUploadInfo info, String vodSessionKey, Callback callback) { String reqUrl = SERVER + "ApplyUploadUGC"; // String reqUrl = TEST_SERVER + "ApplyUploadUGC"; TXCLog.d(TAG, "initUploadUGC->request url:" + reqUrl); String body = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("signature", signature); jsonObject.put("videoName", info.getFileName()); jsonObject.put("videoType", info.getFileType()); // 判断是否需要上传封面 if (info.isNeedCover()) { jsonObject.put("coverName",info.getCoverName()); jsonObject.put("coverType",info.getCoverImgType()); } if (vodSessionKey != null && !vodSessionKey.isEmpty()) { jsonObject.put("vodSessionKey", vodSessionKey); } body = jsonObject.toString(); TXCLog.d(TAG, body); } catch (JSONException e) { e.printStackTrace(); } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body); Request request = new Request.Builder() .url(reqUrl) .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(callback); return TVCConstants.NO_ERROR; } /** * 上传结束(UGC接口) * * @param info 视频信息 * @param callback 回调 * @return */ public int finishUploadUGC(UGCFinishUploadInfo info, final Callback callback) { String reqUrl = "https://" + info.getDomain() + "/v3/index.php?Action=CommitUploadUGC"; // String reqUrl = "http://112.90.82.173/v3/index.php?Action=CommitUploadUGC"; TXCLog.d(TAG, "finishUploadUGC->request url:" + reqUrl); String body = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("signature", signature); jsonObject.put("vodSessionKey", info.getVodSessionKey()); body = jsonObject.toString(); TXCLog.d(TAG, body); } catch (JSONException e) { e.printStackTrace(); } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body); Request request = new Request.Builder() .url(reqUrl) .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(callback); return TVCConstants.NO_ERROR; } }
UTF-8
Java
4,509
java
UGCClient.java
Java
[ { "context": "// private static String TEST_SERVER = \"http://112.90.82.173/v3/index.php?Action=\";\n private static String ", "end": 685, "score": 0.9851962327957153, "start": 672, "tag": "IP_ADDRESS", "value": "112.90.82.173" }, { "context": "mmitUploadUGC\";\n// String reqUrl = \"http://112.90.82.173/v3/index.php?Action=CommitUploadUGC\";\n TXC", "end": 3579, "score": 0.994906485080719, "start": 3566, "tag": "IP_ADDRESS", "value": "112.90.82.173" } ]
null
[]
package com.tencent.liteav.demo.videoupload.impl; import android.content.Context; import android.os.Handler; import com.tencent.liteav.basic.log.TXCLog; import org.json.JSONException; import org.json.JSONObject; import java.util.concurrent.TimeUnit; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; /** * UGC Client */ public class UGCClient { private final static String TAG = "TVC-UGCClient"; private Context context; private String signature; private OkHttpClient okHttpClient; private Handler mainHandler; // private static String TEST_SERVER = "http://172.16.31.10/v3/index.php?Action="; private static String SERVER = "https://vod2.qcloud.com/v3/index.php?Action="; public UGCClient(Context context, String signature, int iTimeOut) { this.context = context; this.signature = signature; okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(iTimeOut, TimeUnit.SECONDS) // 设置超时时间 .readTimeout(iTimeOut, TimeUnit.SECONDS) // 设置读取超时时间 .writeTimeout(iTimeOut, TimeUnit.SECONDS) // 设置写入超时时间 .build(); mainHandler = new Handler(context.getMainLooper()); } // private String getCommonReqPath(String interfaceName) { // return SERVER + interfaceName // + "&Region=gz" // + "&Timestamp=" + String.valueOf(System.currentTimeMillis() / 1000) // + "&Nonce=" + String.valueOf((int) Math.random() * 65535 + 1) // + "&SecretId=" + URLEncoder.encode(scretId) // + "&Signature=" + URLEncoder.encode(signature); // } /** * 申请上传(UGC接口) * * @param info 文件信息 * @param callback 回调 * @return */ public int initUploadUGC(TVCUploadInfo info, String vodSessionKey, Callback callback) { String reqUrl = SERVER + "ApplyUploadUGC"; // String reqUrl = TEST_SERVER + "ApplyUploadUGC"; TXCLog.d(TAG, "initUploadUGC->request url:" + reqUrl); String body = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("signature", signature); jsonObject.put("videoName", info.getFileName()); jsonObject.put("videoType", info.getFileType()); // 判断是否需要上传封面 if (info.isNeedCover()) { jsonObject.put("coverName",info.getCoverName()); jsonObject.put("coverType",info.getCoverImgType()); } if (vodSessionKey != null && !vodSessionKey.isEmpty()) { jsonObject.put("vodSessionKey", vodSessionKey); } body = jsonObject.toString(); TXCLog.d(TAG, body); } catch (JSONException e) { e.printStackTrace(); } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body); Request request = new Request.Builder() .url(reqUrl) .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(callback); return TVCConstants.NO_ERROR; } /** * 上传结束(UGC接口) * * @param info 视频信息 * @param callback 回调 * @return */ public int finishUploadUGC(UGCFinishUploadInfo info, final Callback callback) { String reqUrl = "https://" + info.getDomain() + "/v3/index.php?Action=CommitUploadUGC"; // String reqUrl = "http://172.16.31.10/v3/index.php?Action=CommitUploadUGC"; TXCLog.d(TAG, "finishUploadUGC->request url:" + reqUrl); String body = ""; try { JSONObject jsonObject = new JSONObject(); jsonObject.put("signature", signature); jsonObject.put("vodSessionKey", info.getVodSessionKey()); body = jsonObject.toString(); TXCLog.d(TAG, body); } catch (JSONException e) { e.printStackTrace(); } RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), body); Request request = new Request.Builder() .url(reqUrl) .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(callback); return TVCConstants.NO_ERROR; } }
4,507
0.599363
0.590257
128
33.320313
26.557112
96
false
false
0
0
0
0
0
0
0.609375
false
false
13
b93b777d0cdfcf2b1e0b1bf3e32ec4ad398e3027
25,494,925,914,940
134e0f2d4497afb49963c87a50c5c439d10b505d
/tsien_app/src/main/java/com/tsien/app/AppData.java
18475f8b3f5fec886b3606c457ec8fd8ca1e0205
[]
no_license
FeyTsien/TsienApp
https://github.com/FeyTsien/TsienApp
b43d8104e4291d7e751654896adf7699853be166
752ba32bffb70a30f02f1d89bd76c370e094287a
refs/heads/master
2020-04-29T02:26:39.348000
2019-05-17T02:44:51
2019-05-17T02:44:51
175,767,536
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tsien.app; import android.annotation.SuppressLint; import com.blankj.utilcode.util.PhoneUtils; import com.blankj.utilcode.util.SPUtils; import com.tsien.bean.result.UserBean; /** * Created by Administrator on 2017/8/31. */ public class AppData { //BaseUrl public static final String KEY_BASE_URL = "base_url"; //是否是第一次打开APP public static final String KEY_IS_FIRST_OPEN = "is_first_open"; //是否是新版APP public static final String KEY_IS_NEW_APP = "is_new_app"; //是否登录 public static final String KEY_IS_LOGIN_ED = "is_logined"; //Token public static final String KEY_TOKEN = "token"; //UserId public static final String KEY_USER_ID = "user_id"; //手机号 public static final String KEY_PHONE_NUMBER = "phone_number"; //身份证 public static final String KEY_ID_CARD = "id_card"; //邮箱 public static final String KEY_EMAIL = "email"; //密码 public static final String KEY_PASSWORD = "password"; //头像Url public static final String KEY_PORTRAIT_URL = "portrait_url"; //昵称 public static final String KEY_NICKNAME = "nickname"; //个性签名 public static final String KEY_SIGNATORY = "signatory"; //Android设备Id public static final String KEY_ANDROID_ID = "android_id"; //是否包含工作台 public static final String KEY_IS_WORKBENCH = "is_workbench"; //是否实名认证 public static final String KEY_AUTHENTICATION_STATUS = "is_authentication_status"; //定位——经度 public static final String KEY_LOCATION_LONGITUDE = "location_longitude"; //定位——纬度 public static final String KEY_LOCATION_LATITUDE = "location_latitude"; /** * 保存String 类型数据 */ public static void setValueStr(String key, String value) { SPUtils.getInstance().put(key, value); } /** * 获取String 类型数据 */ public static String getValueStr(String key) { return SPUtils.getInstance().getString(key); } /** * 保存 Boolean 类型数据 * * @param key * @param isBool */ public static void setValueBool(String key, boolean isBool) { SPUtils.getInstance().put(key, isBool); } /** * 查询 Boolean 类型数据 * * @param key * @return */ public static boolean isValueBool(String key) { return SPUtils.getInstance().getBoolean(key, false); } /** * 清除登录信息 */ public static void clearLogin() { AppData.setValueBool(AppData.KEY_IS_LOGIN_ED,false); AppData.setValueStr(AppData.KEY_TOKEN,""); AppData.setValueStr(AppData.KEY_USER_ID,""); AppData.setValueStr(AppData.KEY_PHONE_NUMBER,""); AppData.setValueStr(AppData.KEY_ID_CARD,""); AppData.setValueStr(AppData.KEY_PASSWORD,""); AppData.setValueStr(AppData.KEY_PORTRAIT_URL,""); AppData.setValueStr(AppData.KEY_NICKNAME,""); AppData.setValueStr(AppData.KEY_SIGNATORY,""); AppData.setValueBool(KEY_IS_WORKBENCH,false); } /** * 保存登录信息 * * @param userBean */ public static void saveLogin(UserBean userBean) { AppData.setValueBool(AppData.KEY_IS_LOGIN_ED,true); AppData.setValueStr(AppData.KEY_TOKEN,userBean.getToken()); AppData.setValueStr(AppData.KEY_USER_ID,userBean.getUserAccountEntity().getId()); AppData.setValueStr(AppData.KEY_PHONE_NUMBER,userBean.getUserAccountEntity().getPhoneNumber()); AppData.setValueStr(AppData.KEY_ID_CARD,userBean.getUserAccountEntity().getCardNo()); // AppData.setPassword(password); AppData.setValueStr(AppData.KEY_PORTRAIT_URL,userBean.getUserAccountEntity().getProfilePhotoUrl()); AppData.setValueStr(AppData.KEY_NICKNAME,userBean.getUserAccountEntity().getNickName()); AppData.setValueStr(AppData.KEY_SIGNATORY,userBean.getUserAccountEntity().getSignatory()); if (userBean.getTbAdhibitionEntityList().size() > 3) { //如果数量大于3个,表明该用户有工作台 AppData.setValueBool(KEY_IS_WORKBENCH,true); } else { AppData.setValueBool(KEY_IS_WORKBENCH,false); } } }
UTF-8
Java
4,322
java
AppData.java
Java
[ { "context": "com.tsien.bean.result.UserBean;\n\n/**\n * Created by Administrator on 2017/8/31.\n */\n\npublic class AppData {\n\n //", "end": 221, "score": 0.7333669662475586, "start": 208, "tag": "NAME", "value": "Administrator" }, { "context": "密码\n public static final String KEY_PASSWORD = \"password\";\n //头像Url\n public static final String KEY_", "end": 974, "score": 0.9991844296455383, "start": 966, "tag": "PASSWORD", "value": "password" }, { "context": "昵称\n public static final String KEY_NICKNAME = \"nickname\";\n //个性签名\n public static final String KEY_S", "end": 1119, "score": 0.579220175743103, "start": 1111, "tag": "USERNAME", "value": "nickname" }, { "context": "ity().getCardNo());\n// AppData.setPassword(password);\n AppData.setValueStr(AppData.KEY_PORTRAI", "end": 3539, "score": 0.9755755066871643, "start": 3531, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.tsien.app; import android.annotation.SuppressLint; import com.blankj.utilcode.util.PhoneUtils; import com.blankj.utilcode.util.SPUtils; import com.tsien.bean.result.UserBean; /** * Created by Administrator on 2017/8/31. */ public class AppData { //BaseUrl public static final String KEY_BASE_URL = "base_url"; //是否是第一次打开APP public static final String KEY_IS_FIRST_OPEN = "is_first_open"; //是否是新版APP public static final String KEY_IS_NEW_APP = "is_new_app"; //是否登录 public static final String KEY_IS_LOGIN_ED = "is_logined"; //Token public static final String KEY_TOKEN = "token"; //UserId public static final String KEY_USER_ID = "user_id"; //手机号 public static final String KEY_PHONE_NUMBER = "phone_number"; //身份证 public static final String KEY_ID_CARD = "id_card"; //邮箱 public static final String KEY_EMAIL = "email"; //密码 public static final String KEY_PASSWORD = "<PASSWORD>"; //头像Url public static final String KEY_PORTRAIT_URL = "portrait_url"; //昵称 public static final String KEY_NICKNAME = "nickname"; //个性签名 public static final String KEY_SIGNATORY = "signatory"; //Android设备Id public static final String KEY_ANDROID_ID = "android_id"; //是否包含工作台 public static final String KEY_IS_WORKBENCH = "is_workbench"; //是否实名认证 public static final String KEY_AUTHENTICATION_STATUS = "is_authentication_status"; //定位——经度 public static final String KEY_LOCATION_LONGITUDE = "location_longitude"; //定位——纬度 public static final String KEY_LOCATION_LATITUDE = "location_latitude"; /** * 保存String 类型数据 */ public static void setValueStr(String key, String value) { SPUtils.getInstance().put(key, value); } /** * 获取String 类型数据 */ public static String getValueStr(String key) { return SPUtils.getInstance().getString(key); } /** * 保存 Boolean 类型数据 * * @param key * @param isBool */ public static void setValueBool(String key, boolean isBool) { SPUtils.getInstance().put(key, isBool); } /** * 查询 Boolean 类型数据 * * @param key * @return */ public static boolean isValueBool(String key) { return SPUtils.getInstance().getBoolean(key, false); } /** * 清除登录信息 */ public static void clearLogin() { AppData.setValueBool(AppData.KEY_IS_LOGIN_ED,false); AppData.setValueStr(AppData.KEY_TOKEN,""); AppData.setValueStr(AppData.KEY_USER_ID,""); AppData.setValueStr(AppData.KEY_PHONE_NUMBER,""); AppData.setValueStr(AppData.KEY_ID_CARD,""); AppData.setValueStr(AppData.KEY_PASSWORD,""); AppData.setValueStr(AppData.KEY_PORTRAIT_URL,""); AppData.setValueStr(AppData.KEY_NICKNAME,""); AppData.setValueStr(AppData.KEY_SIGNATORY,""); AppData.setValueBool(KEY_IS_WORKBENCH,false); } /** * 保存登录信息 * * @param userBean */ public static void saveLogin(UserBean userBean) { AppData.setValueBool(AppData.KEY_IS_LOGIN_ED,true); AppData.setValueStr(AppData.KEY_TOKEN,userBean.getToken()); AppData.setValueStr(AppData.KEY_USER_ID,userBean.getUserAccountEntity().getId()); AppData.setValueStr(AppData.KEY_PHONE_NUMBER,userBean.getUserAccountEntity().getPhoneNumber()); AppData.setValueStr(AppData.KEY_ID_CARD,userBean.getUserAccountEntity().getCardNo()); // AppData.setPassword(<PASSWORD>); AppData.setValueStr(AppData.KEY_PORTRAIT_URL,userBean.getUserAccountEntity().getProfilePhotoUrl()); AppData.setValueStr(AppData.KEY_NICKNAME,userBean.getUserAccountEntity().getNickName()); AppData.setValueStr(AppData.KEY_SIGNATORY,userBean.getUserAccountEntity().getSignatory()); if (userBean.getTbAdhibitionEntityList().size() > 3) { //如果数量大于3个,表明该用户有工作台 AppData.setValueBool(KEY_IS_WORKBENCH,true); } else { AppData.setValueBool(KEY_IS_WORKBENCH,false); } } }
4,326
0.656647
0.654448
128
30.96875
28.122204
107
false
false
0
0
0
0
0
0
0.570313
false
false
13
b61f4b739ce12acf8179cadf98dd1e54d1c8afe4
33,363,305,959,705
05727760beb55e3ed86d99639e1bf7ad30bf85b9
/bhshop/bh-pojo/src/main/java/com/bh/goods/pojo/MyNewGoodsShopPojo.java
9a44b08995470cdb36c74bd2705f5a95e9c7b5e4
[]
no_license
cckmit/bhshop
https://github.com/cckmit/bhshop
289f6002cb545c514b0027023935a7041b62cb75
02fd4883cdcf456fb26b983da77d81f99cb3f8c4
refs/heads/master
2023-03-15T22:53:57.473000
2019-05-20T16:58:00
2019-05-20T16:58:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bh.goods.pojo; public class MyNewGoodsShopPojo { //商品的ID private Integer id; //新品上架的图片 private String publicimg; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPublicimg() { return publicimg; } public void setPublicimg(String publicimg) { this.publicimg = publicimg; } }
UTF-8
Java
384
java
MyNewGoodsShopPojo.java
Java
[]
null
[]
package com.bh.goods.pojo; public class MyNewGoodsShopPojo { //商品的ID private Integer id; //新品上架的图片 private String publicimg; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPublicimg() { return publicimg; } public void setPublicimg(String publicimg) { this.publicimg = publicimg; } }
384
0.703297
0.703297
22
15.545455
13.337327
45
false
false
0
0
0
0
0
0
1.318182
false
false
13
dbbd5df4baee52f81fd0e2b8cb7846f35f6b546a
33,363,305,960,387
409df199b0a8d1149b3fbe95ce640a3efe941912
/OrangeHRM/src/main/java/com/app/pages/RecruitmentPage.java
5d726136b8470be6f836d1609fab551858e0f9b6
[]
no_license
maheedhar-202/Orange
https://github.com/maheedhar-202/Orange
2ea78e185bebc4d96f4db703a76e8ab0239ea624
25133f7cfdbaf9deeaab6efef306c908cb0d0617
refs/heads/master
2023-05-10T12:36:54.109000
2020-06-16T13:50:41
2020-06-16T13:50:41
270,563,299
0
0
null
false
2023-05-09T18:53:25
2020-06-08T06:56:22
2020-06-16T13:55:45
2023-05-09T18:53:21
4,667
0
0
1
HTML
false
false
package com.app.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.app.BasePage.TestBase; public class RecruitmentPage extends TestBase{ @FindBy(xpath = "//b[text()='Recruitment']") WebElement recruitment_Btn; @FindBy(xpath="//input[@type='text']") WebElement candidate_txt; @FindBy(xpath = "//input[@id='candidateSearch_fromDate']") WebElement from_Date; @FindBy(xpath = "//input[@id='candidateSearch_toDate']") WebElement to_Date; @FindBy(xpath = "//input[@id='btnSrch']") WebElement Search_Btn; public RecruitmentPage() { PageFactory.initElements(driver, this); } public String ValidaterecruitmentPageTitle() { return driver.getTitle(); } public void search_Recruitment(String name,String From_date,String To_Date) { recruitment_Btn.click(); candidate_txt.sendKeys(name); from_Date.sendKeys(From_date); to_Date.sendKeys(To_Date); Search_Btn.click(); } }
UTF-8
Java
1,032
java
RecruitmentPage.java
Java
[]
null
[]
package com.app.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.app.BasePage.TestBase; public class RecruitmentPage extends TestBase{ @FindBy(xpath = "//b[text()='Recruitment']") WebElement recruitment_Btn; @FindBy(xpath="//input[@type='text']") WebElement candidate_txt; @FindBy(xpath = "//input[@id='candidateSearch_fromDate']") WebElement from_Date; @FindBy(xpath = "//input[@id='candidateSearch_toDate']") WebElement to_Date; @FindBy(xpath = "//input[@id='btnSrch']") WebElement Search_Btn; public RecruitmentPage() { PageFactory.initElements(driver, this); } public String ValidaterecruitmentPageTitle() { return driver.getTitle(); } public void search_Recruitment(String name,String From_date,String To_Date) { recruitment_Btn.click(); candidate_txt.sendKeys(name); from_Date.sendKeys(From_date); to_Date.sendKeys(To_Date); Search_Btn.click(); } }
1,032
0.707364
0.707364
37
25.891891
19.830067
78
false
false
0
0
0
0
0
0
1.459459
false
false
13
880868ce99fe86c56edc4400ac24bfa84e483083
22,574,348,110,356
a3c7cd173392f292b91616839f08e49b41c12c28
/mmap/src/main/java/com/indeed/util/mmap/AbstractMemory.java
2c3d08178bbcc74cc9fc95a832d26b39176bc51f
[ "Apache-2.0" ]
permissive
indeedeng/util
https://github.com/indeedeng/util
2b12625729b29e0140abbaa853254a8a017521a8
3042601f694e2215655283ddd86ae5cc5b69cae1
refs/heads/main
2023-09-03T21:13:22.171000
2023-06-21T21:13:49
2023-06-21T21:13:49
13,075,106
143
78
Apache-2.0
false
2023-06-23T20:57:51
2013-09-24T19:54:16
2023-04-18T08:23:05
2023-06-23T20:57:50
13,666
144
59
11
Java
false
false
package com.indeed.util.mmap; /** @author jplaisance */ public abstract class AbstractMemory implements Memory { @Override public final ByteArray byteArray(long start, long numBytes) { return new ByteArray(this, start, numBytes); } @Override public final ShortArray shortArray(long start, long numShorts) { return new ShortArray(this, start, numShorts); } @Override public final IntArray intArray(long start, long numInts) { return new IntArray(this, start, numInts); } @Override public final LongArray longArray(long start, long numLongs) { return new LongArray(this, start, numLongs); } @Override public final FloatArray floatArray(long start, long numFloats) { return new FloatArray(this, start, numFloats); } @Override public final DoubleArray doubleArray(long start, long numDoubles) { return new DoubleArray(this, start, numDoubles); } @Override public final CharArray charArray(long start, long numChars) { return new CharArray(this, start, numChars); } }
UTF-8
Java
1,111
java
AbstractMemory.java
Java
[ { "context": "package com.indeed.util.mmap;\n\n/** @author jplaisance */\npublic abstract class AbstractMemory implement", "end": 53, "score": 0.9993631839752197, "start": 43, "tag": "USERNAME", "value": "jplaisance" } ]
null
[]
package com.indeed.util.mmap; /** @author jplaisance */ public abstract class AbstractMemory implements Memory { @Override public final ByteArray byteArray(long start, long numBytes) { return new ByteArray(this, start, numBytes); } @Override public final ShortArray shortArray(long start, long numShorts) { return new ShortArray(this, start, numShorts); } @Override public final IntArray intArray(long start, long numInts) { return new IntArray(this, start, numInts); } @Override public final LongArray longArray(long start, long numLongs) { return new LongArray(this, start, numLongs); } @Override public final FloatArray floatArray(long start, long numFloats) { return new FloatArray(this, start, numFloats); } @Override public final DoubleArray doubleArray(long start, long numDoubles) { return new DoubleArray(this, start, numDoubles); } @Override public final CharArray charArray(long start, long numChars) { return new CharArray(this, start, numChars); } }
1,111
0.679568
0.679568
40
26.775
26.302555
71
false
false
0
0
0
0
0
0
0.725
false
false
13
6dc9bdee00b443872124b49c2afcda80df53b357
18,245,021,082,928
4057115643c9bfd8ed6ca7148a6404de4c050e0a
/src/main/java/com/inspirenetz/api/core/dictionary/ImagePrimaryId.java
25d8fd7635589a566d9e7c2e7f66abcdd8d81bd5
[]
no_license
systemsarchitecture/java-spring
https://github.com/systemsarchitecture/java-spring
38032a8d941f70ca588fce842fb056cef3537065
8462e54291e8a45b3b4a97f303490e2510d62a8e
refs/heads/master
2022-05-20T12:18:08.190000
2017-01-05T10:54:31
2017-01-05T10:54:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.inspirenetz.api.core.dictionary; /** * Created by sandheepgr on 14/5/14. */ public class ImagePrimaryId { public static final Long PRIMARY_DEFAULT_IMAGE = 1L; public static final Long PRIMARY_MERCHANT_LOGO = 2L; public static final Long PRIMARY_PROMOTION_IMAGE =3L; public static final Long PRIMARY_CATALOGUE_IMAGE =4L; public static final Long PRIMARY_RWD_IMAGE =5L; public static final Long ALERT_IMAGE = 6L; public static final Long PRIMARY_LOYALTY_PROGRAM_IMAGE = 7L; public static final Long PRIMARY_PURCHASE_AVAILED_SERVICE_IMAGE = 8L; public static final Long PRIMARY_MERCHANT_SERVICE_IMAGE = 9L; public static final Long PRIMARY_COUPON_IMAGE = 10L; public static final Long PRIMARY_MILESTONE_IMAGE = 11L; public static final Long PRIMARY_MERCHANT_VENDOR_IMAGE = 12L; public static final Long PRIMARY_CATALOGUE_CATEGORY_IMAGE = 13L; public static final Long PRIMARY_MERCHANT_COVER_IMAGE = 14L; public static final Long PRIMARY_TIER_IMAGE = 15L; }
UTF-8
Java
1,031
java
ImagePrimaryId.java
Java
[ { "context": "nspirenetz.api.core.dictionary;\n\n/**\n * Created by sandheepgr on 14/5/14.\n */\npublic class ImagePrimaryId {\n\n ", "end": 74, "score": 0.9996550679206848, "start": 64, "tag": "USERNAME", "value": "sandheepgr" } ]
null
[]
package com.inspirenetz.api.core.dictionary; /** * Created by sandheepgr on 14/5/14. */ public class ImagePrimaryId { public static final Long PRIMARY_DEFAULT_IMAGE = 1L; public static final Long PRIMARY_MERCHANT_LOGO = 2L; public static final Long PRIMARY_PROMOTION_IMAGE =3L; public static final Long PRIMARY_CATALOGUE_IMAGE =4L; public static final Long PRIMARY_RWD_IMAGE =5L; public static final Long ALERT_IMAGE = 6L; public static final Long PRIMARY_LOYALTY_PROGRAM_IMAGE = 7L; public static final Long PRIMARY_PURCHASE_AVAILED_SERVICE_IMAGE = 8L; public static final Long PRIMARY_MERCHANT_SERVICE_IMAGE = 9L; public static final Long PRIMARY_COUPON_IMAGE = 10L; public static final Long PRIMARY_MILESTONE_IMAGE = 11L; public static final Long PRIMARY_MERCHANT_VENDOR_IMAGE = 12L; public static final Long PRIMARY_CATALOGUE_CATEGORY_IMAGE = 13L; public static final Long PRIMARY_MERCHANT_COVER_IMAGE = 14L; public static final Long PRIMARY_TIER_IMAGE = 15L; }
1,031
0.743938
0.71872
24
41.958332
25.376301
73
false
false
0
0
0
0
0
0
0.666667
false
false
13
2b5dd7d8afb90fe07c0313b567e6acb3f7c9871d
9,457,518,047,888
c1f521de9abcd1bd506170e44901fb4100689d69
/model/src/main/java/com/tj720/model/common/SelectDto.java
2f7ff3cc48e2f1655059ea4711756e24f79ef2db
[]
no_license
wyfddh/post_online
https://github.com/wyfddh/post_online
210fcea3b4996cdfb74e021d197291ef258cffe3
621bceb4f03d4d0468b522a031921b38614ced35
refs/heads/master
2020-04-25T15:34:53.751000
2019-01-29T07:44:18
2019-01-29T07:44:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tj720.model.common; import java.io.Serializable; //@Data public class SelectDto implements Serializable{ private static final long serialVersionUID = -3067263031103815640L; private String name; private String value; private String selected; private String disabled; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getSelected() { return selected; } public void setSelected(String selected) { this.selected = selected; } public String getDisabled() { return disabled; } public void setDisabled(String disabled) { this.disabled = disabled; } }
UTF-8
Java
768
java
SelectDto.java
Java
[]
null
[]
package com.tj720.model.common; import java.io.Serializable; //@Data public class SelectDto implements Serializable{ private static final long serialVersionUID = -3067263031103815640L; private String name; private String value; private String selected; private String disabled; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getSelected() { return selected; } public void setSelected(String selected) { this.selected = selected; } public String getDisabled() { return disabled; } public void setDisabled(String disabled) { this.disabled = disabled; } }
768
0.72526
0.696615
47
15.340425
16.373665
68
false
false
0
0
0
0
0
0
1.106383
false
false
13
2dcc7c67f06384ba2360669c92bfc473eeec6d82
28,518,582,879,353
b19af9ac5935cfbf7db2bded10fe60ad2c718d27
/velocityplus/src/net/sf/wdte/ui/text/rules/IDocumentView.java
b8726217da65f2f9dfa5f8f20d187e1314d46f2c
[]
no_license
javamonkey/velocityplus
https://github.com/javamonkey/velocityplus
9c22c7d85165987e5b78773b7f862067c517c2de
e58add9c64eebc7581fc9a9cc74ab1c9fe1aece9
refs/heads/master
2021-01-17T21:39:46.904000
2012-02-12T20:09:59
2012-02-12T20:09:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2002-2004 Widespace, OU and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://solareclipse.sourceforge.net/legal/cpl-v10.html * * Contributors: * Igor Malinin - initial contribution * * $Id: IDocumentView.java,v 1.1 2004/02/10 12:41:21 cell Exp $ */ package net.sf.wdte.ui.text.rules; import org.eclipse.jface.text.IDocument; /** * View to part of parent document. Provides methods for translating character * offsets between this view and parent document. * * @author Igor Malinin */ public interface IDocumentView extends IDocument { IDocument getParentDocument(); int getParentOffset(int localOffset); int getLocalOffset(int parentOffset); }
UTF-8
Java
891
java
IDocumentView.java
Java
[ { "context": "/legal/cpl-v10.html\r\n * \r\n * Contributors:\r\n * Igor Malinin - initial contribution\r\n * \r\n * $Id: IDocumentVie", "end": 362, "score": 0.9998153448104858, "start": 350, "tag": "NAME", "value": "Igor Malinin" }, { "context": "en this view and parent document.\r\n * \r\n * @author Igor Malinin\r\n */\r\npublic interface IDocumentView extends IDoc", "end": 710, "score": 0.9997814297676086, "start": 698, "tag": "NAME", "value": "Igor Malinin" } ]
null
[]
/* * Copyright (c) 2002-2004 Widespace, OU and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://solareclipse.sourceforge.net/legal/cpl-v10.html * * Contributors: * <NAME> - initial contribution * * $Id: IDocumentView.java,v 1.1 2004/02/10 12:41:21 cell Exp $ */ package net.sf.wdte.ui.text.rules; import org.eclipse.jface.text.IDocument; /** * View to part of parent document. Provides methods for translating character * offsets between this view and parent document. * * @author <NAME> */ public interface IDocumentView extends IDocument { IDocument getParentDocument(); int getParentOffset(int localOffset); int getLocalOffset(int parentOffset); }
879
0.720539
0.689113
31
26.741936
26.003681
78
false
false
0
0
0
0
0
0
0.354839
false
false
13
43205fb8784f9d74d32f851c08187fa8708f16d0
17,772,574,738,385
005bd0ff57eb5774f176a802e16da1be70272dea
/src/main/java/com/lab/restaurant/transactional/AppRestauranteController.java
c2c5f16b664890605e8045a92cee235bc6ab7bd4
[]
no_license
jvalagui/BelatrixTeamB
https://github.com/jvalagui/BelatrixTeamB
aa890a04750e8923a1f9785f872e82de144d8eda
921d0354c07e7a294576a612ac80196c3163ef85
refs/heads/master
2021-01-01T05:03:54.970000
2016-05-21T06:39:05
2016-05-21T06:39:05
58,276,181
1
0
null
false
2016-05-21T06:39:05
2016-05-07T17:12:07
2016-05-09T19:10:36
2016-05-21T06:39:05
96
0
0
1
Java
null
null
package com.lab.restaurant.transactional; import com.lab.restaurant.model.*; import com.lab.restaurant.utils.Helper; import java.util.*; /** * Created by Kei on 10/05/2016. */ public class AppRestauranteController { private static Queue<Visita> colaEspera = new LinkedList<Visita>(); public static void menuPrincipal() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Principal\n"); System.out.println("\t(1)Atención de clientes"); System.out.println("\t(2)Opciones"); System.out.println("\t(3)Salir\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 3 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Principal\n"); System.out.println("\t(1)Atención de clientes"); System.out.println("\t(2)Opciones"); System.out.println("\t(3)Salir\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: menuAtencion(); break; case 2: menuOpciones(); break; case 3: System.out.println("\nHasta luego!\n"); break; default: break; } } private static void menuOpciones() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Opciones\n"); System.out.println("\t(1)Mesas"); System.out.println("\t(2)Meseros"); System.out.println("\t(3)Alimentos"); System.out.println("\t(4)Bebidas"); System.out.println("\t(5)Regresar al menú principal\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 5 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Opciones\n"); System.out.println("\t(1)Mesas"); System.out.println("\t(2)Meseros"); System.out.println("\t(3)Alimentos"); System.out.println("\t(4)Bebidas"); System.out.println("\t(5)Regresar al menú principal\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: menuMesas(); break; case 2: menuMeseros(); break; case 3: menuAlimentos(); break; case 4: menuBebidas(); break; case 5: menuPrincipal(); break; default: break; } } private static void menuAtencion() { int opcion; String numeroDocumento; Visita nuevaVisita; int cantidadColaEspera = colaEspera.size(); Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Atención\n"); System.out.println("\t(1)Registrar cliente"); System.out.println("\t(2)Buscar cliente"); System.out.println("\t(3)Ver cola de espera"); System.out.println("\t(4)Atender cola de espera -> " + cantidadColaEspera); System.out.println("\t(5)Atender mesa"); System.out.println("\t(6)Finalizar atencion"); System.out.println("\t(7)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); in.nextLine(); while (opcion > 7 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar cliente"); System.out.println("\t(2)Buscar cliente"); System.out.println("\t(3)Ver cola de espera"); System.out.println("\t(4)Atender cola de espera -> " + cantidadColaEspera); System.out.println("\t(5)Atender mesa"); System.out.println("\t(6)Finalizar atencion"); System.out.println("\t(7)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); in.nextLine(); } switch (opcion) { case 1: Cliente nuevoCliente = ClienteController.registrar(); nuevaVisita = VisitaController.registrar(nuevoCliente); colaEspera.offer(nuevaVisita); System.out.println("\nEl cliente ha entrado a la cola de espera"); Helper.pausa(); menuAtencion(); break; case 2: System.out.println("\nRESTAURANTE BELATRIX - Buscar Cliente\n"); System.out.print("Ingrese el numero de documento: "); numeroDocumento = in.nextLine(); Cliente cliente = ClienteController.buscar(numeroDocumento); if(cliente == null){ System.out.println("\nEl cliente no ha sido encontrado"); Helper.pausa(); menuAtencion(); } else{ String respuesta; System.out.println("\nEl cliente ha sido encontrado"); System.out.println("\n¿Desea poner al cliente " + cliente.getApellidoPaterno() +" " + cliente.getApellidoMaterno() + ", " + cliente.getNombre() + " en la cola de espera? (Y/N)"); respuesta = in.nextLine(); if(respuesta.equalsIgnoreCase("Y")){ if(visitaEnCola(cliente,colaEspera)){ System.out.println("\nEl cliente ya está en la cola de espera"); Helper.pausa(); menuAtencion(); } else{ nuevaVisita = VisitaController.registrar(cliente); colaEspera.add(nuevaVisita); System.out.println("\nEl cliente ha entrado a la cola de espera"); Helper.pausa(); menuAtencion(); } } else{ menuAtencion(); } } break; case 3: verCola(); Helper.pausa(); menuAtencion(); break; case 4: atenderCola(); Helper.pausa(); menuAtencion(); break; case 5: //Asignar Pedido System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuAtencion(); break; case 6: int numeroMesa; Visita visitaAtender; VisitaController.listarVisitasEnAtencion(); System.out.print("\nIngresar numero de mesa: "); numeroMesa = in.nextInt(); in.nextLine(); visitaAtender = VisitaController.obtenerVisitaPorNumeroMesa(numeroMesa); while(visitaAtender == null){ System.out.println("\nNúmero de mesa incorrecto"); VisitaController.listarVisitasEnAtencion(); System.out.print("\nIngresar numero de mesa: "); numeroMesa = in.nextInt(); in.nextLine(); visitaAtender = VisitaController.obtenerVisitaPorNumeroMesa(numeroMesa); } VisitaController.finalizarAtencion(visitaAtender); Helper.pausa(); menuAtencion(); break; case 7: menuPrincipal(); break; default: break; } } private static void menuMesas() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar mesa"); System.out.println("\t(2)Modificar mesa"); System.out.println("\t(3)Eliminar mesa"); System.out.println("\t(4)Listar mesas"); System.out.println("\t(5)Asignar mesero"); System.out.println("\t(6)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 6 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar mesa"); System.out.println("\t(2)Modificar mesa"); System.out.println("\t(3)Eliminar mesa"); System.out.println("\t(4)Listar mesas"); System.out.println("\t(5)Asignar mesero"); System.out.println("\t(6)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: MesaController.registrar(); Helper.pausa(); menuMesas(); break; case 2: //modificar mesa System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuMesas(); break; case 3: //eliminar mesa System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuMesas(); break; case 4: System.out.println("\nRESTAURANTE BELATRIX - Listado de mesas\n"); MesaController.listar(); Helper.pausa(); menuMesas(); break; case 5: System.out.println("\nRESTAURANTE BELATRIX - Asignación de meseros por mesas\n"); MesaController.asignarMesero(); Helper.pausa(); menuMesas(); break; case 6: menuOpciones(); break; default: break; } } private static void menuMeseros() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Meseros\n"); System.out.println("\t(1)Registrar mesero"); System.out.println("\t(2)Modificar mesero"); System.out.println("\t(3)Eliminar mesero"); System.out.println("\t(4)Listar meseros"); System.out.println("\t(5)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 5 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Meseros\n"); System.out.println("\t(1)Registrar mesero"); System.out.println("\t(2)Modificar mesero"); System.out.println("\t(3)Eliminar mesero"); System.out.println("\t(4)Listar meseros"); System.out.println("\t(5)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: System.out.println("\nRESTAURANTE BELATRIX - Registrar nuevo mesero\n"); MeseroController.registrar(); menuMeseros(); Helper.pausa(); break; case 2: //modificar mesero System.out.println("\nEn mantemiento! :v\n"); menuMeseros(); Helper.pausa(); break; case 3: //eliminar mesero System.out.println("\nEn mantemiento! :v\n"); menuMeseros(); Helper.pausa(); break; case 4: //listar meseros System.out.println("\nRESTAURANTE BELATRIX - Listado de meseros\n"); MeseroController.listar(); Helper.pausa(); menuMeseros(); break; case 5: menuOpciones(); break; default: break; } } private static void menuAlimentos() { //COMPLETAR System.out.println("\nEn mantemiento! :v\n"); menuOpciones(); } private static void menuBebidas() { //COMPLETAR System.out.println("\nEn mantemiento! :v\n"); menuOpciones(); } private static boolean visitaEnCola(Cliente cliente, Queue<Visita> colaEspera){ for (Visita visita: colaEspera) { if(visita.getCliente().getNumDocumento().equalsIgnoreCase(cliente.getNumDocumento())){ return true; } } return false; } private static void verCola(){ int contador = 1; if(colaEspera.isEmpty()){ System.out.println("\nLa cola está vacía"); } else{ for (Visita visita: colaEspera) { System.out.println("\n[" + contador + "]"); System.out.println("Cliente: " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre()); System.out.println("Numero de acompanantes: " + visita.getNumeroAcompanantes() + "\n"); contador++; } } } private static void atenderCola(){ int contador = 0; if(colaEspera.isEmpty()){ System.out.println("\nLa cola de espera está vacía"); } else{ for (Visita visita : colaEspera) { int resultado = VisitaController.asignarMesa(visita); if(resultado == 0){ //System.out.println("\nNo hay mesa disponible para el cliente: " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre()); } else{ System.out.println("\nEl cliente " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre() + " entrará a la mesa: " + visita.getMesa().getNumMesa() ); //System.out.println("El mesero: " + visita.getMesa().getMesero().getNombre() + " lo atenderá"); colaEspera.remove(visita); } contador++; } } } }
UTF-8
Java
15,382
java
AppRestauranteController.java
Java
[ { "context": "s.Helper;\n\nimport java.util.*;\n\n\n/**\n * Created by Kei on 10/05/2016.\n */\npublic class AppRestauranteC", "end": 160, "score": 0.7040271759033203, "start": 159, "tag": "NAME", "value": "K" }, { "context": "Helper;\n\nimport java.util.*;\n\n\n/**\n * Created by Kei on 10/05/2016.\n */\npublic class AppRestauranteCon", "end": 162, "score": 0.6892473697662354, "start": 160, "tag": "USERNAME", "value": "ei" } ]
null
[]
package com.lab.restaurant.transactional; import com.lab.restaurant.model.*; import com.lab.restaurant.utils.Helper; import java.util.*; /** * Created by Kei on 10/05/2016. */ public class AppRestauranteController { private static Queue<Visita> colaEspera = new LinkedList<Visita>(); public static void menuPrincipal() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Principal\n"); System.out.println("\t(1)Atención de clientes"); System.out.println("\t(2)Opciones"); System.out.println("\t(3)Salir\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 3 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Principal\n"); System.out.println("\t(1)Atención de clientes"); System.out.println("\t(2)Opciones"); System.out.println("\t(3)Salir\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: menuAtencion(); break; case 2: menuOpciones(); break; case 3: System.out.println("\nHasta luego!\n"); break; default: break; } } private static void menuOpciones() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Opciones\n"); System.out.println("\t(1)Mesas"); System.out.println("\t(2)Meseros"); System.out.println("\t(3)Alimentos"); System.out.println("\t(4)Bebidas"); System.out.println("\t(5)Regresar al menú principal\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 5 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Opciones\n"); System.out.println("\t(1)Mesas"); System.out.println("\t(2)Meseros"); System.out.println("\t(3)Alimentos"); System.out.println("\t(4)Bebidas"); System.out.println("\t(5)Regresar al menú principal\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: menuMesas(); break; case 2: menuMeseros(); break; case 3: menuAlimentos(); break; case 4: menuBebidas(); break; case 5: menuPrincipal(); break; default: break; } } private static void menuAtencion() { int opcion; String numeroDocumento; Visita nuevaVisita; int cantidadColaEspera = colaEspera.size(); Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Atención\n"); System.out.println("\t(1)Registrar cliente"); System.out.println("\t(2)Buscar cliente"); System.out.println("\t(3)Ver cola de espera"); System.out.println("\t(4)Atender cola de espera -> " + cantidadColaEspera); System.out.println("\t(5)Atender mesa"); System.out.println("\t(6)Finalizar atencion"); System.out.println("\t(7)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); in.nextLine(); while (opcion > 7 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar cliente"); System.out.println("\t(2)Buscar cliente"); System.out.println("\t(3)Ver cola de espera"); System.out.println("\t(4)Atender cola de espera -> " + cantidadColaEspera); System.out.println("\t(5)Atender mesa"); System.out.println("\t(6)Finalizar atencion"); System.out.println("\t(7)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); in.nextLine(); } switch (opcion) { case 1: Cliente nuevoCliente = ClienteController.registrar(); nuevaVisita = VisitaController.registrar(nuevoCliente); colaEspera.offer(nuevaVisita); System.out.println("\nEl cliente ha entrado a la cola de espera"); Helper.pausa(); menuAtencion(); break; case 2: System.out.println("\nRESTAURANTE BELATRIX - Buscar Cliente\n"); System.out.print("Ingrese el numero de documento: "); numeroDocumento = in.nextLine(); Cliente cliente = ClienteController.buscar(numeroDocumento); if(cliente == null){ System.out.println("\nEl cliente no ha sido encontrado"); Helper.pausa(); menuAtencion(); } else{ String respuesta; System.out.println("\nEl cliente ha sido encontrado"); System.out.println("\n¿Desea poner al cliente " + cliente.getApellidoPaterno() +" " + cliente.getApellidoMaterno() + ", " + cliente.getNombre() + " en la cola de espera? (Y/N)"); respuesta = in.nextLine(); if(respuesta.equalsIgnoreCase("Y")){ if(visitaEnCola(cliente,colaEspera)){ System.out.println("\nEl cliente ya está en la cola de espera"); Helper.pausa(); menuAtencion(); } else{ nuevaVisita = VisitaController.registrar(cliente); colaEspera.add(nuevaVisita); System.out.println("\nEl cliente ha entrado a la cola de espera"); Helper.pausa(); menuAtencion(); } } else{ menuAtencion(); } } break; case 3: verCola(); Helper.pausa(); menuAtencion(); break; case 4: atenderCola(); Helper.pausa(); menuAtencion(); break; case 5: //Asignar Pedido System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuAtencion(); break; case 6: int numeroMesa; Visita visitaAtender; VisitaController.listarVisitasEnAtencion(); System.out.print("\nIngresar numero de mesa: "); numeroMesa = in.nextInt(); in.nextLine(); visitaAtender = VisitaController.obtenerVisitaPorNumeroMesa(numeroMesa); while(visitaAtender == null){ System.out.println("\nNúmero de mesa incorrecto"); VisitaController.listarVisitasEnAtencion(); System.out.print("\nIngresar numero de mesa: "); numeroMesa = in.nextInt(); in.nextLine(); visitaAtender = VisitaController.obtenerVisitaPorNumeroMesa(numeroMesa); } VisitaController.finalizarAtencion(visitaAtender); Helper.pausa(); menuAtencion(); break; case 7: menuPrincipal(); break; default: break; } } private static void menuMesas() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar mesa"); System.out.println("\t(2)Modificar mesa"); System.out.println("\t(3)Eliminar mesa"); System.out.println("\t(4)Listar mesas"); System.out.println("\t(5)Asignar mesero"); System.out.println("\t(6)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 6 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Mesas\n"); System.out.println("\t(1)Registrar mesa"); System.out.println("\t(2)Modificar mesa"); System.out.println("\t(3)Eliminar mesa"); System.out.println("\t(4)Listar mesas"); System.out.println("\t(5)Asignar mesero"); System.out.println("\t(6)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: MesaController.registrar(); Helper.pausa(); menuMesas(); break; case 2: //modificar mesa System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuMesas(); break; case 3: //eliminar mesa System.out.println("\nEn mantemiento! :v\n"); Helper.pausa(); menuMesas(); break; case 4: System.out.println("\nRESTAURANTE BELATRIX - Listado de mesas\n"); MesaController.listar(); Helper.pausa(); menuMesas(); break; case 5: System.out.println("\nRESTAURANTE BELATRIX - Asignación de meseros por mesas\n"); MesaController.asignarMesero(); Helper.pausa(); menuMesas(); break; case 6: menuOpciones(); break; default: break; } } private static void menuMeseros() { int opcion; Scanner in = new Scanner(System.in); System.out.println("\nRESTAURANTE BELATRIX - Menú Meseros\n"); System.out.println("\t(1)Registrar mesero"); System.out.println("\t(2)Modificar mesero"); System.out.println("\t(3)Eliminar mesero"); System.out.println("\t(4)Listar meseros"); System.out.println("\t(5)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); while (opcion > 5 || opcion < 1) { //si escoge una opcion inválida System.out.println("\nOpción no válida!"); System.out.println("\nRESTAURANTE BELATRIX - Menú Meseros\n"); System.out.println("\t(1)Registrar mesero"); System.out.println("\t(2)Modificar mesero"); System.out.println("\t(3)Eliminar mesero"); System.out.println("\t(4)Listar meseros"); System.out.println("\t(5)Regresar al menú de opciones\n"); System.out.print("Ingrese una opción: "); opcion = in.nextInt(); } switch (opcion) { case 1: System.out.println("\nRESTAURANTE BELATRIX - Registrar nuevo mesero\n"); MeseroController.registrar(); menuMeseros(); Helper.pausa(); break; case 2: //modificar mesero System.out.println("\nEn mantemiento! :v\n"); menuMeseros(); Helper.pausa(); break; case 3: //eliminar mesero System.out.println("\nEn mantemiento! :v\n"); menuMeseros(); Helper.pausa(); break; case 4: //listar meseros System.out.println("\nRESTAURANTE BELATRIX - Listado de meseros\n"); MeseroController.listar(); Helper.pausa(); menuMeseros(); break; case 5: menuOpciones(); break; default: break; } } private static void menuAlimentos() { //COMPLETAR System.out.println("\nEn mantemiento! :v\n"); menuOpciones(); } private static void menuBebidas() { //COMPLETAR System.out.println("\nEn mantemiento! :v\n"); menuOpciones(); } private static boolean visitaEnCola(Cliente cliente, Queue<Visita> colaEspera){ for (Visita visita: colaEspera) { if(visita.getCliente().getNumDocumento().equalsIgnoreCase(cliente.getNumDocumento())){ return true; } } return false; } private static void verCola(){ int contador = 1; if(colaEspera.isEmpty()){ System.out.println("\nLa cola está vacía"); } else{ for (Visita visita: colaEspera) { System.out.println("\n[" + contador + "]"); System.out.println("Cliente: " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre()); System.out.println("Numero de acompanantes: " + visita.getNumeroAcompanantes() + "\n"); contador++; } } } private static void atenderCola(){ int contador = 0; if(colaEspera.isEmpty()){ System.out.println("\nLa cola de espera está vacía"); } else{ for (Visita visita : colaEspera) { int resultado = VisitaController.asignarMesa(visita); if(resultado == 0){ //System.out.println("\nNo hay mesa disponible para el cliente: " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre()); } else{ System.out.println("\nEl cliente " + visita.getCliente().getApellidoPaterno() + " " + visita.getCliente().getApellidoMaterno() + ", " + visita.getCliente().getNombre() + " entrará a la mesa: " + visita.getMesa().getNumMesa() ); //System.out.println("El mesero: " + visita.getMesa().getMesero().getNombre() + " lo atenderá"); colaEspera.remove(visita); } contador++; } } } }
15,382
0.503654
0.497194
419
35.577564
28.682287
248
false
false
0
0
0
0
0
0
0.637232
false
false
13
62eba4e6ef0cff7d4e908ffb25cf5c5e99540fa5
9,122,510,606,579
307296590d1fd9e70055b96311c97863a4627b1e
/src/main/java/br/com/si/clinicamedica/service/TiposExamesService.java
3a99c29182f4d78fdc2432b2a2f7e6396f0d253d
[]
no_license
HenriqueJorge/clinicamedica
https://github.com/HenriqueJorge/clinicamedica
d803d7268f86fd2215960114d758ca6e18cae267
8954a5e7446e33475392ea38b5849ccc9e089239
refs/heads/master
2020-04-20T08:51:55.798000
2019-02-06T19:20:09
2019-02-06T19:20:09
168,751,887
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.si.clinicamedica.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.si.clinicamedica.model.TiposExames; import br.com.si.clinicamedica.repository.TiposExamesRepository; @Service public class TiposExamesService{ @Autowired TiposExamesRepository repository; public TiposExames create(TiposExames tiposExames) { return repository.save(tiposExames); } public List<TiposExames> readAll() { return repository.findAll(); } public TiposExames readById(Integer id) { if(repository.existsById(id)) { return repository.findById(id).get(); } return null; } public TiposExames update(TiposExames tiposExames) { if(repository.existsById(tiposExames.getId())) { return repository.save(tiposExames); } return null; } public void delete(Integer id) { repository.deleteById(id); } }
UTF-8
Java
937
java
TiposExamesService.java
Java
[]
null
[]
package br.com.si.clinicamedica.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.si.clinicamedica.model.TiposExames; import br.com.si.clinicamedica.repository.TiposExamesRepository; @Service public class TiposExamesService{ @Autowired TiposExamesRepository repository; public TiposExames create(TiposExames tiposExames) { return repository.save(tiposExames); } public List<TiposExames> readAll() { return repository.findAll(); } public TiposExames readById(Integer id) { if(repository.existsById(id)) { return repository.findById(id).get(); } return null; } public TiposExames update(TiposExames tiposExames) { if(repository.existsById(tiposExames.getId())) { return repository.save(tiposExames); } return null; } public void delete(Integer id) { repository.deleteById(id); } }
937
0.766275
0.766275
43
20.790697
20.661793
64
false
false
0
0
0
0
0
0
1.27907
false
false
13
3430e77fa8e1d29bce57c21b4eead667d3a46293
2,207,613,219,936
2103e1c9d3dd8f8fe82ff2f1ccdb87bca545aa2e
/src/main/java/com/pingming/plantcap/domain/CrmGCurrency.java
1fa96efcc6b6491f32a9766993e317d83b77a512
[]
no_license
philipzhou2009/plantcap-spring-boot
https://github.com/philipzhou2009/plantcap-spring-boot
0eb1c9a58fbb222cde6f802336626b984146f3ff
d705859cbfffcdfe27cc29a063ae48f7b9bb644a
refs/heads/master
2018-01-10T12:40:02.358000
2016-02-01T16:07:46
2016-02-01T16:07:46
47,343,840
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pingming.plantcap.domain; // Generated Jan 25, 2016 2:40:46 PM by Hibernate Tools 4.3.1.Final import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * CrmGCurrency generated by hbm2java */ @Entity @Table(name = "crm_g_currency", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "currency") ) public class CrmGCurrency implements java.io.Serializable { private Long id; private String currency; private boolean display; private String symbol; private String unitText; private Set<CrmOrder> crmOrders = new HashSet<CrmOrder>(0); public CrmGCurrency() { } public CrmGCurrency(String currency, boolean display) { this.currency = currency; this.display = display; } public CrmGCurrency(String currency, boolean display, String symbol, String unitText, Set<CrmOrder> crmOrders) { this.currency = currency; this.display = display; this.symbol = symbol; this.unitText = unitText; this.crmOrders = crmOrders; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "currency", unique = true, nullable = false, length = 10) public String getCurrency() { return this.currency; } public void setCurrency(String currency) { this.currency = currency; } @Column(name = "display", nullable = false) public boolean isDisplay() { return this.display; } public void setDisplay(boolean display) { this.display = display; } @Column(name = "symbol", length = 30) public String getSymbol() { return this.symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } @Column(name = "unit_text", length = 50) public String getUnitText() { return this.unitText; } public void setUnitText(String unitText) { this.unitText = unitText; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "crmGCurrency") public Set<CrmOrder> getCrmOrders() { return this.crmOrders; } public void setCrmOrders(Set<CrmOrder> crmOrders) { this.crmOrders = crmOrders; } }
UTF-8
Java
2,445
java
CrmGCurrency.java
Java
[]
null
[]
package com.pingming.plantcap.domain; // Generated Jan 25, 2016 2:40:46 PM by Hibernate Tools 4.3.1.Final import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** * CrmGCurrency generated by hbm2java */ @Entity @Table(name = "crm_g_currency", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "currency") ) public class CrmGCurrency implements java.io.Serializable { private Long id; private String currency; private boolean display; private String symbol; private String unitText; private Set<CrmOrder> crmOrders = new HashSet<CrmOrder>(0); public CrmGCurrency() { } public CrmGCurrency(String currency, boolean display) { this.currency = currency; this.display = display; } public CrmGCurrency(String currency, boolean display, String symbol, String unitText, Set<CrmOrder> crmOrders) { this.currency = currency; this.display = display; this.symbol = symbol; this.unitText = unitText; this.crmOrders = crmOrders; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "currency", unique = true, nullable = false, length = 10) public String getCurrency() { return this.currency; } public void setCurrency(String currency) { this.currency = currency; } @Column(name = "display", nullable = false) public boolean isDisplay() { return this.display; } public void setDisplay(boolean display) { this.display = display; } @Column(name = "symbol", length = 30) public String getSymbol() { return this.symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } @Column(name = "unit_text", length = 50) public String getUnitText() { return this.unitText; } public void setUnitText(String unitText) { this.unitText = unitText; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "crmGCurrency") public Set<CrmOrder> getCrmOrders() { return this.crmOrders; } public void setCrmOrders(Set<CrmOrder> crmOrders) { this.crmOrders = crmOrders; } }
2,445
0.733742
0.724744
103
22.737864
22.763435
116
false
false
0
0
0
0
0
0
1.320388
false
false
13
25a0a76168c9e2d2c2ead4814e92fc3bb75300b1
33,397,665,699,007
5106d6b134e613391286913fe16175b7609b88e5
/repo/core/branches/intact-jami-1.0.0-alpha-SNAPSHOT/src/main/java/uk/ac/ebi/intact/jami/model/listener/PolymerSequenceListener.java
528252a000888be3975516efd67650c0f50ac0fc
[]
no_license
EBI-IntAct/intact
https://github.com/EBI-IntAct/intact
b7ace4d6e9a45563e56fd6c7f6eeea024cff5586
285883503f0818778d3e7aae7427b87e95f401ea
refs/heads/master
2020-12-24T08:24:10.446000
2015-03-25T16:04:46
2015-03-25T16:04:46
32,396,831
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package uk.ac.ebi.intact.jami.model.listener; import uk.ac.ebi.intact.jami.model.SequenceChunk; import uk.ac.ebi.intact.jami.model.extension.IntactPolymer; import uk.ac.ebi.intact.jami.utils.IntactUtils; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import java.util.ArrayList; import java.util.Collection; /** * This listener listen to Polymer object pre update/persist/load events * and set sequence accordingly to existing annotations * This listener is for backward compatibility only with previous intact-core. * * @author Marine Dumousseau (marine@ebi.ac.uk) * @version $Id$ * @since <pre>07/01/14</pre> */ public class PolymerSequenceListener { @PrePersist @PreUpdate public void prePersist(IntactPolymer intactPolymer) { if (intactPolymer.getSequence() != null){ String oldSeq = convertToSequence(intactPolymer.getSequenceChunks()); if (oldSeq == null || !oldSeq.equals(intactPolymer.getSequence())){ convertSequence(intactPolymer.getSequence(), intactPolymer.getSequenceChunks()); } } else if (!intactPolymer.getSequenceChunks().isEmpty()) { intactPolymer.getSequenceChunks().clear(); } } @PostLoad public void postLoad(IntactPolymer intactPolymer) { if (!intactPolymer.getSequenceChunks().isEmpty() && intactPolymer.getSequence() == null){ intactPolymer.setSequence(convertToSequence(intactPolymer.getSequenceChunks())); } } private String convertToSequence(Collection<SequenceChunk> sequenceChunks){ StringBuilder sequence = new StringBuilder(); for ( SequenceChunk sequenceChunk : sequenceChunks ) { sequence.append( sequenceChunk.getSequenceChunk() ); } return sequence.toString(); } private void convertSequence( String aSequence, Collection<SequenceChunk> chunks ) { // Save work if the new sequence is identical to the old one. // The container to hold redundant chunks. ArrayList<SequenceChunk> chunkPool = null; // All old data are kept, we try to recycle as much chunk as possible if ( !chunks.isEmpty() ) { // There is existing chunk ... prepare them for recycling. chunkPool = new ArrayList<SequenceChunk>( chunks.size() ); chunkPool.addAll( chunks ); int count = chunkPool.size(); // clean chunk to recycle for ( int i = 0; i < count; i++ ) { SequenceChunk sc = chunkPool.get( i ); chunks.remove(sc); } } // Note the use of integer operations int chunkCount = aSequence.length() / IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK; if ( aSequence.length() % IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK > 0 ) { chunkCount++; } for ( int i = 0; i < chunkCount; i++ ) { String chunk = aSequence.substring( i * IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK, Math.min( ( i + 1 ) * IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK, aSequence.length() ) ); if ( chunkPool != null && chunkPool.size() > 0 ) { // recycle chunk SequenceChunk sc = chunkPool.remove( 0 ); sc.setSequenceChunk( chunk ); sc.setSequenceIndex( i ); chunks.add(sc); } else { // create new chunk chunks.add(new SequenceChunk(i, chunk)); } } } }
UTF-8
Java
3,617
java
PolymerSequenceListener.java
Java
[ { "context": "lity only with previous intact-core.\n *\n * @author Marine Dumousseau (marine@ebi.ac.uk)\n * @version $Id$\n * @since <pr", "end": 615, "score": 0.9998753666877747, "start": 598, "tag": "NAME", "value": "Marine Dumousseau" }, { "context": "ous intact-core.\n *\n * @author Marine Dumousseau (marine@ebi.ac.uk)\n * @version $Id$\n * @since <pre>07/01/14</pre>\n ", "end": 633, "score": 0.999933660030365, "start": 617, "tag": "EMAIL", "value": "marine@ebi.ac.uk" } ]
null
[]
package uk.ac.ebi.intact.jami.model.listener; import uk.ac.ebi.intact.jami.model.SequenceChunk; import uk.ac.ebi.intact.jami.model.extension.IntactPolymer; import uk.ac.ebi.intact.jami.utils.IntactUtils; import javax.persistence.PostLoad; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import java.util.ArrayList; import java.util.Collection; /** * This listener listen to Polymer object pre update/persist/load events * and set sequence accordingly to existing annotations * This listener is for backward compatibility only with previous intact-core. * * @author <NAME> (<EMAIL>) * @version $Id$ * @since <pre>07/01/14</pre> */ public class PolymerSequenceListener { @PrePersist @PreUpdate public void prePersist(IntactPolymer intactPolymer) { if (intactPolymer.getSequence() != null){ String oldSeq = convertToSequence(intactPolymer.getSequenceChunks()); if (oldSeq == null || !oldSeq.equals(intactPolymer.getSequence())){ convertSequence(intactPolymer.getSequence(), intactPolymer.getSequenceChunks()); } } else if (!intactPolymer.getSequenceChunks().isEmpty()) { intactPolymer.getSequenceChunks().clear(); } } @PostLoad public void postLoad(IntactPolymer intactPolymer) { if (!intactPolymer.getSequenceChunks().isEmpty() && intactPolymer.getSequence() == null){ intactPolymer.setSequence(convertToSequence(intactPolymer.getSequenceChunks())); } } private String convertToSequence(Collection<SequenceChunk> sequenceChunks){ StringBuilder sequence = new StringBuilder(); for ( SequenceChunk sequenceChunk : sequenceChunks ) { sequence.append( sequenceChunk.getSequenceChunk() ); } return sequence.toString(); } private void convertSequence( String aSequence, Collection<SequenceChunk> chunks ) { // Save work if the new sequence is identical to the old one. // The container to hold redundant chunks. ArrayList<SequenceChunk> chunkPool = null; // All old data are kept, we try to recycle as much chunk as possible if ( !chunks.isEmpty() ) { // There is existing chunk ... prepare them for recycling. chunkPool = new ArrayList<SequenceChunk>( chunks.size() ); chunkPool.addAll( chunks ); int count = chunkPool.size(); // clean chunk to recycle for ( int i = 0; i < count; i++ ) { SequenceChunk sc = chunkPool.get( i ); chunks.remove(sc); } } // Note the use of integer operations int chunkCount = aSequence.length() / IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK; if ( aSequence.length() % IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK > 0 ) { chunkCount++; } for ( int i = 0; i < chunkCount; i++ ) { String chunk = aSequence.substring( i * IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK, Math.min( ( i + 1 ) * IntactUtils.MAX_SEQ_LENGTH_PER_CHUNK, aSequence.length() ) ); if ( chunkPool != null && chunkPool.size() > 0 ) { // recycle chunk SequenceChunk sc = chunkPool.remove( 0 ); sc.setSequenceChunk( chunk ); sc.setSequenceIndex( i ); chunks.add(sc); } else { // create new chunk chunks.add(new SequenceChunk(i, chunk)); } } } }
3,597
0.617915
0.614598
95
37.073685
28.438759
97
false
false
0
0
0
0
0
0
0.442105
false
false
13