blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
31447d978103b8d881d8d20c85d78f1508cdccc0
Java
ritika-07/Java-Programming
/Part-2/Q2/Q2.java
UTF-8
1,046
3.53125
4
[]
no_license
import java.util.*; class Employee { String id; String name; String dob; void getdata() { Scanner sc= new Scanner (System.in); System.out.println("Enter details: "); id= sc.next(); name= sc.next(); dob= sc.next(); } void validate() throws InvalidEmployeeCode { int flag=0; if (id.charAt(0)>='0' && id.charAt(0)<='9') if (id.charAt(1)>='0' && id.charAt(1)<='9') if (id.charAt(2)=='-') if (id.charAt(3)=='F' || id.charAt(3)=='S') if (id.charAt(4)=='-') if (id.charAt(5)>='0' && id.charAt(5)<='9') if (id.charAt(6)>='0' && id.charAt(6)<='9') if (id.charAt(7)>='0' && id.charAt(7)<='9') flag=1; if (flag==0) { throw new InvalidEmployeeCode (); } } void display() { System.out.println("Details:"); System.out.println("ID: "+ id + "\nName: " + name + "\nDOB: "+ dob); } } class Q2 { public static void main (String[] args) { Employee e= new Employee(); e.getdata(); try { e.validate(); e.display(); } catch ( Exception er) { System.out.println(er); } } }
true
7ae2221cb7f295536d76f31587726f5cb36c36b0
Java
ihanfeng/weixin
/src/test/java/io/github/rcarlosdasilva/weixin/test/Mp.java
UTF-8
8,387
2.203125
2
[ "Apache-2.0" ]
permissive
package io.github.rcarlosdasilva.weixin.test; import java.util.List; import com.google.common.collect.Lists; import io.github.rcarlosdasilva.weixin.api.Weixin; import io.github.rcarlosdasilva.weixin.core.WeixinRegistry; import io.github.rcarlosdasilva.weixin.model.response.user.UserOpenIdListResponse; public class Mp { private String name; private String id; private String secret; /** . */ public Mp(String name, String id, String secret) { this.name = name; this.id = id; this.secret = secret; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } /** . */ public static void main(String[] args) { List<Mp> mps = Lists.newArrayList(); mps.add(new Mp("齐齐哈尔教育云", "wx7b54b16181a88d2a", "e01fcd5d70a5680a66b150faa1ba4417")); mps.add(new Mp("鹤岗市教育云", "wx85214943cc5578ca", "c7417d3e0910920f5320033e5d247af1")); mps.add(new Mp("七台河市教育局", "wx8c987fb5ddf68cd9", "51c942e3773542af3f15cf1d35bbfb16")); mps.add(new Mp("西海岸新区教育", "wxe39c8f7d67ce8b7d", "cfc86744f537a98cb865a73706985cf9")); mps.add(new Mp("淮北市教育局", "wxd5f5146d4605066d", "1f710dfeaeb12bbfb23636f4a894a3bf")); mps.add(new Mp("菏泽高新区", "wx5bb598c3e959f75d", "596752e3e0c0a3aa611ec537d0e791ad")); mps.add(new Mp("林口县教育局", "wx217d6e7944dd80e2", "c4dc54fabb20a19a855289a73e6a9509")); mps.add(new Mp("相山区教育局", "wx455cb6e441ec48c6", "170a599a149386060e15d7f5f0817e7a")); mps.add(new Mp("潍坊高新区教育局", "wx295819358df58de9", "059c6900eddf3e1c5760e2c545673dc9")); mps.add(new Mp("青云谱区教育局", "wx5690983269d20ec9", "ed1f7f4a6733cf3adc1dbec3260ef883")); mps.add(new Mp("佳木斯市教育局", "wx3128e58ac8a7499d", "c6bfa53bed39f3ea3939824ead6bf10c")); mps.add(new Mp("滨州市教育局", "wx876cd11041b9697a", "bae2f613473140c9fb5f145366e6ad4f")); mps.add(new Mp("潍坊市坊子区教育信息化", "wx059e414180e1be21", "0773f0cc262ff3915bcbcfad20366a8b")); mps.add(new Mp("蚌埠淮上区教育局", "wx5c9aca511e748039", "4e719322e5259e484b65eb0a60ca84cd")); mps.add(new Mp("临沂兰山区教育局", "wx0b9fc759b613857f", "e39495b0f92c21517916f0fc5158be35")); mps.add(new Mp("绥化庆安县", "wxf89c0535c293c9fb", "a3ac45ec2b275eeb3627fb1b465e263d")); mps.add(new Mp("菏泽牡丹区教育局", "wx280589fbe567395d", "d50879e26b255b86025c75753a106451")); mps.add(new Mp("九江濂溪区教育局", "wxbc5fe3ae895d1fb7", "fcc317adf71f04a8a480e19ec34883e8")); mps.add(new Mp("辽源市教育局", "wx4869b4ec6bdbc0d6", "75ae6979a87b154cd2d5ef44a29e62d0")); mps.add(new Mp("相山区教育局", "wx8dba0065130a9ced", "d4bfbc2218fe0c99588532543388b56b")); mps.add(new Mp("濉溪县教育局", "wx3bb54bed3dc067bc", "ecbb884112c207baa3c511387dfb3512")); mps.add(new Mp("莱西市教育局", "wxfcc0dd9760c0b4b0", "659bfec2c06e663a59437a381abc1f2b")); mps.add(new Mp("赢信慧通演示", "wxc2cf57f67aadc121", "5f8dff78c7ff4866fe019a90b44bb6ed")); mps.add(new Mp("道外区教育局", "wxb0e3274a8655246e", "8810cbda030be6f508fa2f3130a4d268")); mps.add(new Mp("新乡市教育局", "wx5690983269d20ec9", "ed1f7f4a6733cf3adc1dbec3260ef883")); mps.add(new Mp("夏津县教育局", "wxfe0d459eb60bd876", "59e0efd3ec580b5189c61bb4ee36cc95")); mps.add(new Mp("彭州市教育局", "wxe9f076e697514e49", "e97d1c0d5072094b1e7d1c68486e1916")); mps.add(new Mp("菏泽高新区", "wx5bb598c3e959f75d", "596752e3e0c0a3aa611ec537d0e791ad")); mps.add(new Mp("牡丹发布", "wxf179fe892ac256c0", "c0e998b03458e4c324557d0589847d61")); mps.add(new Mp("菏泽高新区教育局", "wxfe895d6f01e2e8b4", "4a1ba969db3cf86072e87ab1ef77864f")); mps.add(new Mp("菏泽市鄄城县", "wx01056ea3f97e9c62", "7cda95a3732290d00b86225476459c42")); mps.add(new Mp("胶州市教育局", "wxecdc5c4b293dccb3", "37833568dbe6bd18c1585df13688c623")); mps.add(new Mp("哈尔滨市教育局", "wxecdc5c4b293dccb3", "37833568dbe6bd18c1585df13688c623")); mps.add(new Mp("宣汉县政府", "wxfcc0dd9760c0b4b0", "659bfec2c06e663a59437a381abc1f2b")); mps.add(new Mp("连云港市连云区教育", "wxff936a13e0ca828d", "1485cbcef4ddadbdc189f981783c7b1d")); mps.add(new Mp("安徽省教育局", "wxbd960f67d09e23f8", "a89f01e55cec561ed89b8d1f758a08e8")); mps.add(new Mp("青岛市教育局", "wx4869b4ec6bdbc0d6", "75ae6979a87b154cd2d5ef44a29e62d0")); mps.add(new Mp("青岛市教育局", "wxbc5fe3ae895d1fb7", "fcc317adf71f04a8a480e19ec34883e8")); mps.add(new Mp("阿城区教育局", "wx7b58348051a7dc2c", "dee9d60651ea31da742f16b79cb80044")); mps.add(new Mp("蚌埠市教育局", "wxdc88585365ae4b29", "bc17c7b82d254db43d8c468b8a701e58")); mps.add(new Mp("七台河市第九中学", "wxe8e6783f4a2c2c6f", "d78de68d2cff9f54767b6a1c6748bd3a")); mps.add(new Mp("七台河市第五小学", "wx88734550a47e81af", "dd4a2aa7db2a4f5591d2dfa6b4c02029")); mps.add(new Mp("七台河市第六小学", "wxbd6249b7b2e1ea26", "d9726debfd05e083f822c76215ddf837")); mps.add(new Mp("七台河市第二小学", "wx1c64553cfd549514", "9ec61485304c528881c884f38a070fe8")); mps.add(new Mp("黑龙江省七台河市第十小学", "wx16be5a45a68bb351", "6f8b62cf2db68e372b899d0360e7ac3a")); // mps.add(new Mp("七台河市第四中学", "wxf9ec8ac06594cd32", // "f1ce7dd3bc4cf8289ea7efbbcff9aaa1")); mps.add(new Mp("七台河市第九小学", "wxbafa8f770647e1d0", "59ea5d6858dea32919bb1318ef79b891")); mps.add(new Mp("黑龙江省七台河市第七小学", "wx51edfc9aa076f2b9", "00aa0eb0071196646de1071ba5966422")); mps.add(new Mp("青岛昊儿宝贝", "wx5a7b22d3332d98c0", "7a34ea341c4d55dc546f93689a41476e")); mps.add(new Mp("青岛永和路小学", "wxad6fff6c39a69d6e", "5b77dc1c8d46023713fec9ed449654d3")); mps.add(new Mp("君塘镇人民政府", "wx9a219272f9e9a61f", "1c02e85fb5558ba09bf6d4fd8b3412fc")); mps.add(new Mp("六汪镇五道口小学", "wxea8c4f9259e7fa5e", "834e8da884ec9bdca43c96db473d25e4")); mps.add(new Mp("卡贝少儿文化艺术中心", "wxd5c9b9955fd912c4", "22475af735ccdf859f2d74c7b4130b0d")); mps.add(new Mp("黄岛区亚森木业幼儿园", "wx8d30b016fff8e5cf", "8381fc6cbea5a010db74df727acfa020")); mps.add(new Mp("城阳区棘洪滩街道中华埠小学", "wxe194c3033f9ff325", "5217507bc42ed6d7755053f940e62112")); mps.add(new Mp("崂山区睿博优胜文化艺术活动中心", "wxbffc45330bbd6c9b", "794b4907d375c62b2d1b1b79beef22ab")); mps.add(new Mp("崂山区九水园", "wx5cff8c3687951f3a", "ec05542c346a69368c94ad255338cca3")); mps.add(new Mp("郭家瞳阳光园", "wxb3a8e166d4a9e528", "4410eeafe58bc78187c5323100aa255b")); mps.add(new Mp("平度市山水龙苑", "wx28dea77bf47d450a", "59ead25f8b52a7a6531f77a4928b844e")); mps.add(new Mp("黄岛区集合号幼儿园", "wxe2e19b1e2d9f74f7", "3e4592bf6ba9772136b4f385f0bb1806")); mps.add(new Mp("青岛双星海逸", "wx0b0dac77c551ed79", "a3f37a9519e6f91712efcfddbf295463")); mps.add(new Mp("青岛福林小学", "wx7c044435f4e5c371", "6a80524743284986b780f937ee933caf")); mps.add(new Mp("黄岛区胶河经济区后立柱小学", "wxcb425709d6f10103", "1caf508b9db5ebda01a59f2b6d27824a")); mps.add(new Mp("崂山区青山小学", "wxc44b82a38c13af88", "341e6811fa80064b225cf1763d985d91")); mps.add(new Mp("陵城区陵城镇明德小学", "wxee909cc25c9c37a7", "03ab7743f367a6ed653915ac0ed3024c")); mps.add(new Mp("尚志朝中", "wxcec47068a1ece9d1", "bde879408439cd4097fcea99be195709")); // mps.add(new Mp("拓东日盛", "wx1e43acce998e687b", // "c88d5e37e79daf5bbcccb833f05dc7c4")); for (Mp mp : mps) { WeixinRegistry.registryUnique(mp.getId(), mp.getSecret()); UserOpenIdListResponse resp = Weixin.withUnique().user().listAllUsersOpenId(); System.out.println("[ " + mp.getName() + " ] 总用户数:" + resp.getTotal()); } } }
true
7af80cafdb171f7c3386f9a39e937295851f33af
Java
geralex/SWG-NGE
/dsrc/sku.0/sys.server/compiled/game/script/conversation/som_kenobi_crazed_hermit.java
UTF-8
45,457
1.875
2
[]
no_license
package script.conversation; import script.*; import script.base_class.*; import script.combat_engine.*; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import script.base_script; import script.library.ai_lib; import script.library.chat; import script.library.groundquests; import script.library.jedi; import script.library.utils; public class som_kenobi_crazed_hermit extends script.base_script { public som_kenobi_crazed_hermit() { } public static String c_stringFile = "conversation/som_kenobi_crazed_hermit"; public boolean som_kenobi_crazed_hermit_condition__defaultCondition(obj_id player, obj_id npc) throws InterruptedException { return true; } public boolean som_kenobi_crazed_hermit_condition_playerJedi(obj_id player, obj_id npc) throws InterruptedException { return jedi.isForceSensitive(player); } public boolean som_kenobi_crazed_hermit_condition_hermitChat2(obj_id player, obj_id npc) throws InterruptedException { return groundquests.isTaskActive(player, "som_kenobi_main_quest_1", "talkHermit2"); } public boolean som_kenobi_crazed_hermit_condition_hermitChat1(obj_id player, obj_id npc) throws InterruptedException { return groundquests.isTaskActive(player, "som_kenobi_main_quest_1", "talkHermit1"); } public boolean som_kenobi_crazed_hermit_condition_underAttack(obj_id player, obj_id npc) throws InterruptedException { return groundquests.isTaskActive(player, "som_kenobi_main_quest_1", "attacked"); } public void som_kenobi_crazed_hermit_action_signalTalked1(obj_id player, obj_id npc) throws InterruptedException { groundquests.sendSignal(player, "talkedHermit1"); } public void som_kenobi_crazed_hermit_action_removeInvuln(obj_id player, obj_id npc) throws InterruptedException { setInvulnerable(npc, false); } public void som_kenobi_crazed_hermit_action_attack(obj_id player, obj_id npc) throws InterruptedException { startCombat(npc, player); clearCondition(npc, CONDITION_CONVERSABLE); } public void som_kenobi_crazed_hermit_action_signalTalked2(obj_id player, obj_id npc) throws InterruptedException { groundquests.sendSignal(player, "talkedHermit2"); } public int som_kenobi_crazed_hermit_handleBranch1(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_69")) { doAnimationAction(player, "implore"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "sigh_deeply"); string_id message = new string_id(c_stringFile, "s_71"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_72"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 2); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_70")) { doAnimationAction(player, "point_accusingly"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "dismiss"); string_id message = new string_id(c_stringFile, "s_86"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } boolean hasResponse2 = false; if (som_kenobi_crazed_hermit_condition_playerJedi(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse2 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_87"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_88"); } if (hasResponse2) { responses[responseIndex++] = new string_id(c_stringFile, "s_89"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 10); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch2(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_72")) { if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "scared"); string_id message = new string_id(c_stringFile, "s_73"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } boolean hasResponse2 = false; if (som_kenobi_crazed_hermit_condition_playerJedi(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse2 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_74"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_77"); } if (hasResponse2) { responses[responseIndex++] = new string_id(c_stringFile, "s_75"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 3); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch3(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_74")) { doAnimationAction(player, "shake_head_no"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "helpme"); string_id message = new string_id(c_stringFile, "s_78"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_79"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_80"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 4); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_77")) { doAnimationAction(player, "implore"); som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "twitch"); som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_85"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } if (response.equals("s_75")) { som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "twitch"); som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_76"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch4(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_79")) { som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_81"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } if (response.equals("s_80")) { doAnimationAction(player, "offer_affection"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "shiver"); som_kenobi_crazed_hermit_action_signalTalked2(player, npc); string_id message = new string_id(c_stringFile, "s_82"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_83"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 6); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch6(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_83")) { doAnimationAction(player, "twitch"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "heavy_cough_vomit"); string_id message = new string_id(c_stringFile, "s_84"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch10(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_87")) { som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "twitch"); som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_91"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } if (response.equals("s_88")) { if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "squirm"); string_id message = new string_id(c_stringFile, "s_92"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_95"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_94"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 12); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_89")) { som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_90"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch12(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_95")) { doAnimationAction(player, "nod"); som_kenobi_crazed_hermit_action_removeInvuln(player, npc); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "point_accusingly"); som_kenobi_crazed_hermit_action_attack(player, npc); string_id message = new string_id(c_stringFile, "s_96"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } if (response.equals("s_94")) { doAnimationAction(player, "nod"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "shiver"); som_kenobi_crazed_hermit_action_signalTalked2(player, npc); string_id message = new string_id(c_stringFile, "s_97"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_98"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 14); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch14(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_98")) { doAnimationAction(player, "twitch"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "heavy_cough_vomit"); string_id message = new string_id(c_stringFile, "s_99"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch17(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_37")) { if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "squirm"); string_id message = new string_id(c_stringFile, "s_40"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_41"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 18); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_56")) { if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "blame"); string_id message = new string_id(c_stringFile, "s_58"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_60"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 23); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch18(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_41")) { doAnimationAction(player, "rub_chin_thoughtful"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "gesticulate_wildly"); string_id message = new string_id(c_stringFile, "s_42"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition_playerJedi(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_44"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_52"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 19); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch19(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_44")) { doAnimationAction(player, "slow_down"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "heavy_cough_vomit"); string_id message = new string_id(c_stringFile, "s_46"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_48"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 20); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_52")) { doAnimationAction(player, "shush"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "scream"); doAnimationAction(player, "taken_aback"); som_kenobi_crazed_hermit_action_signalTalked1(player, npc); string_id message = new string_id(c_stringFile, "s_54"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch20(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_48")) { doAnimationAction(player, "offer_affection"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "scream"); doAnimationAction(player, "taken_aback"); som_kenobi_crazed_hermit_action_signalTalked1(player, npc); string_id message = new string_id(c_stringFile, "s_50"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch23(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_60")) { if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "gesticulate_wildly"); string_id message = new string_id(c_stringFile, "s_62"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition_playerJedi(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_64"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_104"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 24); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch24(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_64")) { doAnimationAction(player, "point_accusingly"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "implore"); string_id message = new string_id(c_stringFile, "s_66"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_100"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 25); npcSpeak(player, message); npcSetConversationResponses(player, responses); } else { utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); } return SCRIPT_CONTINUE; } } if (response.equals("s_104")) { doAnimationAction(player, "shush"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "scream"); som_kenobi_crazed_hermit_action_signalTalked1(player, npc); string_id message = new string_id(c_stringFile, "s_106"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int som_kenobi_crazed_hermit_handleBranch25(obj_id player, obj_id npc, string_id response) throws InterruptedException { if (response.equals("s_100")) { doAnimationAction(player, "shake_head_no"); if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "scream"); som_kenobi_crazed_hermit_action_signalTalked1(player, npc); string_id message = new string_id(c_stringFile, "s_102"); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); npcEndConversationWithMessage(player, message); return SCRIPT_CONTINUE; } } return SCRIPT_DEFAULT; } public int OnInitialize(obj_id self) throws InterruptedException { if ((!isMob(self)) || (isPlayer(self))) { detachScript(self, "conversation.som_kenobi_crazed_hermit"); } ai_lib.setDefaultCalmBehavior(self, ai_lib.BEHAVIOR_SENTINEL); setInvulnerable(self, true); return SCRIPT_CONTINUE; } public int OnAttach(obj_id self) throws InterruptedException { ai_lib.setDefaultCalmBehavior(self, ai_lib.BEHAVIOR_SENTINEL); setCondition(self, CONDITION_CONVERSABLE); setInvulnerable(self, true); return SCRIPT_CONTINUE; } public int OnObjectMenuRequest(obj_id self, obj_id player, menu_info menuInfo) throws InterruptedException { int menu = menuInfo.addRootMenu(menu_info_types.CONVERSE_START, null); menu_info_data menuInfoData = menuInfo.getMenuItemById(menu); menuInfoData.setServerNotify(false); return SCRIPT_CONTINUE; } public int OnIncapacitated(obj_id self, obj_id killer) throws InterruptedException { clearCondition(self, CONDITION_CONVERSABLE); detachScript(self, "conversation.som_kenobi_crazed_hermit"); return SCRIPT_CONTINUE; } public boolean npcStartConversation(obj_id player, obj_id npc, String convoName, string_id greetingId, prose_package greetingProse, string_id[] responses) throws InterruptedException { Object[] objects = new Object[responses.length]; System.arraycopy(responses, 0, objects, 0, responses.length); return npcStartConversation(player, npc, convoName, greetingId, greetingProse, objects); } public int OnStartNpcConversation(obj_id self, obj_id player) throws InterruptedException { obj_id npc = self; if (ai_lib.isInCombat(npc) || ai_lib.isInCombat(player)) { return SCRIPT_OVERRIDE; } if (som_kenobi_crazed_hermit_condition_hermitChat2(player, npc)) { doAnimationAction(npc, "shiver"); string_id message = new string_id(c_stringFile, "s_67"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_69"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_70"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 1); npcStartConversation(player, npc, "som_kenobi_crazed_hermit", message, responses); } else { chat.chat(npc, player, message); } return SCRIPT_CONTINUE; } if (som_kenobi_crazed_hermit_condition_hermitChat1(player, npc)) { doAnimationAction(npc, "bounce"); string_id message = new string_id(c_stringFile, "s_93"); int numberOfResponses = 0; boolean hasResponse = false; boolean hasResponse0 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse0 = true; } boolean hasResponse1 = false; if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { ++numberOfResponses; hasResponse = true; hasResponse1 = true; } if (hasResponse) { int responseIndex = 0; string_id responses[] = new string_id[numberOfResponses]; if (hasResponse0) { responses[responseIndex++] = new string_id(c_stringFile, "s_37"); } if (hasResponse1) { responses[responseIndex++] = new string_id(c_stringFile, "s_56"); } utils.setScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId", 17); npcStartConversation(player, npc, "som_kenobi_crazed_hermit", message, responses); } else { chat.chat(npc, player, message); } return SCRIPT_CONTINUE; } if (som_kenobi_crazed_hermit_condition_underAttack(player, npc)) { doAnimationAction(npc, "clap_rousing"); string_id message = new string_id(c_stringFile, "s_108"); chat.chat(npc, player, message); return SCRIPT_CONTINUE; } if (som_kenobi_crazed_hermit_condition__defaultCondition(player, npc)) { doAnimationAction(npc, "dismiss"); string_id message = new string_id(c_stringFile, "s_110"); chat.chat(npc, player, message); return SCRIPT_CONTINUE; } chat.chat(npc, "Error: All conditions for OnStartNpcConversation were false."); return SCRIPT_CONTINUE; } public int OnNpcConversationResponse(obj_id self, String conversationId, obj_id player, string_id response) throws InterruptedException { if (!conversationId.equals("som_kenobi_crazed_hermit")) { return SCRIPT_CONTINUE; } obj_id npc = self; int branchId = utils.getIntScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); if (branchId == 1 && som_kenobi_crazed_hermit_handleBranch1(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 2 && som_kenobi_crazed_hermit_handleBranch2(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 3 && som_kenobi_crazed_hermit_handleBranch3(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 4 && som_kenobi_crazed_hermit_handleBranch4(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 6 && som_kenobi_crazed_hermit_handleBranch6(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 10 && som_kenobi_crazed_hermit_handleBranch10(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 12 && som_kenobi_crazed_hermit_handleBranch12(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 14 && som_kenobi_crazed_hermit_handleBranch14(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 17 && som_kenobi_crazed_hermit_handleBranch17(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 18 && som_kenobi_crazed_hermit_handleBranch18(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 19 && som_kenobi_crazed_hermit_handleBranch19(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 20 && som_kenobi_crazed_hermit_handleBranch20(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 23 && som_kenobi_crazed_hermit_handleBranch23(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 24 && som_kenobi_crazed_hermit_handleBranch24(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } if (branchId == 25 && som_kenobi_crazed_hermit_handleBranch25(player, npc, response) == SCRIPT_CONTINUE) { return SCRIPT_CONTINUE; } chat.chat(npc, "Error: Fell through all branches and responses for OnNpcConversationResponse."); utils.removeScriptVar(player, "conversation.som_kenobi_crazed_hermit.branchId"); return SCRIPT_CONTINUE; } }
true
3afec7fc1e2af832c9dae8a588fb66b9192caaa7
Java
SDEprojects/21SDE1-DNTJ-RuntimeTerror
/Game/src/com/runtimeterror/controller/SwingController.java
UTF-8
2,949
2.34375
2
[]
no_license
package com.runtimeterror.controller; import com.runtimeterror.model.Item; import com.runtimeterror.model.Leaderboard; import com.runtimeterror.model.Rooms; import java.util.HashMap; import java.util.List; import java.util.Map; public class SwingController { private GameInterface gi; //CTOR public SwingController(GameInterface gi) { // done: Setup with game interface this.gi = gi; } // GUI TEST FUNCTIONS public String processInput(String input) { return gi.submitPlayerString(input); } public String getRoomDesc() { return gi.getRoomText(); } public String getInventory() { return gi.getPLayerInventory(); } public String getRoomImagePath() { return gi.getRoomImagePath(); } public boolean getStatus() { return gi.getPLayerStatus(); } public int getMonsterData() { return gi.getMonsterLocation(); } public void startNewGame() { gi.reset(); } public boolean isGameOver() { return gi.isGameOver(); } public boolean isKilledByMonster() { return gi.isKilledByMonster(); } public String getMessageLabel() { return gi.getMessageLabel(); } public void resetRound() { gi.resetRound(); } public String getRoomMapPath() { return gi.getRoomMapPath(); } public int getPlayerHealth() { return gi.getPlayerHealth(); } public boolean hasMap() { return gi.hasMap(); } public boolean isMonsterNear() {return gi.isMonsterNear();} public boolean isMonsterSameRoom() {return gi.isMonsterSameRoom();} public String getDialogue() {return gi.getDialogue();} public boolean isHealthIncrease() {return gi.isHealthIncrease();} public int getTimeToEndGame() {return gi.timeToEndGame();} public List<Item> getPlayerItems() {return gi.playerInventory();} public List<Item> getRoomItems() {return gi.getRoomItems();} public boolean hasItems() {return gi.hasItems();} public boolean isCloseToDying() { return gi.isPlayerClosedToDying(); } public String getMonsterLabel() {return gi.getMonsterLabel();} public Map<String, Rooms> getAvailableRooms() {return gi.getAvailableRooms();} public boolean hasStairs() {return gi.hasStairs();} public boolean hasElevator() {return gi.hasElevator();} public void setupGameDifficulty(String level) {gi.setupDifficulty(level);} public List<Leaderboard> getLeaderboard(int size) {return gi.getLeaderboard(size);} public boolean addToLeaderboard(String userName, int gameTime, int runtime) { return gi.addToLeaderboard(userName, gameTime, runtime); } public boolean isBloodLost() { return gi.isBloodLost();} public String getDifficultyLevel() { return gi.getDifficultyLevel(); } public HashMap<String, List<Integer>> getDifficultyMap() {return gi.getDifficultyMap();} }
true
5e6ed3c78fbd71499bae6b15019b740769852016
Java
douglasespindola/CarX
/src/main/java/service/UserService.java
UTF-8
4,935
2.375
2
[]
no_license
package service; import dto.TokenDto; import entity.User; import org.joda.time.DateTime; import javax.enterprise.context.RequestScoped; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import javax.xml.bind.DatatypeConverter; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; @Named @RequestScoped public class UserService{ @PersistenceContext(name = "pi2017") private EntityManager entityManager; @Transactional public List<User> getAll() { try { Query query = entityManager.createNamedQuery("User.getAllUsers"); return query.getResultList(); } catch (Exception e){ return new ArrayList<>(); } } @Transactional public User get(Integer id) { try { Query query = entityManager.createNamedQuery("User.getUser"); query.setParameter("id", id); return (User) query.getSingleResult(); } catch (Exception e) { return null; } } @Transactional public synchronized User update(User user) throws NoSuchAlgorithmException { Query query = entityManager.createNamedQuery("User.checkUserNamedAvailable"); query.setParameter("email",user.getEmail()).setParameter("cpf",user.getCpf()); if(user.getPassword()!=null){ String password = user.getPassword(); user.setPassword(password); } List<User> users = query.getResultList(); if(users.size() == 0) { return entityManager.merge(user); } for(User us: users) { if(us.getId() == user.getId()) { if(user.getPassword()==null){ user.setPasswordToString(us.getPassword()); } return entityManager.merge(user); } } throw new IllegalArgumentException("Esse email já está vinculado a uma conta favor usar outro"); } @Transactional public synchronized User create(User user) throws NoSuchAlgorithmException { Query query = entityManager.createNamedQuery("User.checkUserNamedAvailable"); query.setParameter("email",user.getEmail()).setParameter("cpf",user.getCpf()); List<User> users = query.getResultList(); if(users.size() == 0){ String password = user.getPassword(); user.setPassword(password); entityManager.persist(user); return user; } throw new IllegalArgumentException("Esse email ou cpf já está vinculado a uma conta, favor usar outro"); } @Transactional public void remove(Integer id) { User user = entityManager.find(User.class, id); entityManager.remove(user); } @Transactional public TokenDto getToken(User user) { TokenDto tokenDto = new TokenDto(); try { Query query = entityManager.createNamedQuery("User.getLogin"); query.setParameter("email", user.getEmail()).setParameter("password", user.convertPasswordToMD5(user.getPassword())); User userLogged = (User) query.getSingleResult(); if (userLogged != null) { userLogged.setToken(DatatypeConverter.printBase64Binary( (user.getEmail() + ":" + (new DateTime().getMillis() + (60 * 60 * 60 * 60))).getBytes()) ); entityManager.persist(userLogged); tokenDto.setToken(userLogged.getToken()); tokenDto.setName(userLogged.getName()); tokenDto.setEmail(userLogged.getEmail()); tokenDto.setCpf(userLogged.getCpf().toString()); tokenDto.setUserId(userLogged.getId()); return tokenDto; } tokenDto.setToken(null); return tokenDto; } catch (Exception e) { tokenDto.setToken(null); return tokenDto; } } @Transactional public TokenDto checkToken(String token) { try { Query query = entityManager.createNamedQuery("User.getToken"); query.setParameter("token", token); User user = (User)query.getSingleResult(); if(user==null) return null; TokenDto tokenDto = new TokenDto(); tokenDto.setEmail(user.getEmail()); tokenDto.setName(user.getName()); tokenDto.setCpf(user.getCpf().toString()); tokenDto.setToken(user.getToken()); tokenDto.setUserId(user.getId()); return tokenDto; } catch (Exception e) { return null; } } }
true
b77635b6dba2650c56b6d5996b36c10b53dc1102
Java
AhmedAkram96/AnalysisAssignment2
/AnalysisAssignment/src/GraphLib/Vertex.java
UTF-8
538
2.5
2
[]
no_license
package GraphLib; import java.util.ArrayList; public class Vertex { protected StringBuffer _strUniqueID, //a unique id identifying vertex _strData; //data associated with vertex protected int _nX,_nY; //Coordinates of vertex on some //map. Assume 0,0 is //bottom left public StringBuffer getUniqueID( ){ return _strUniqueID; } public StringBuffer getData( ){ return _strData; } public int getX( ){ return _nX; } public int getY( ){ return _nY; } }
true
66abd20b3fccb2d19b23ab569267be0cf9e9719d
Java
impactotecnologico/java-news
/1 Colecciones, streams y filtros/1.6/lambdas/src/lambdas/Main.java
UTF-8
2,603
3.90625
4
[]
no_license
package lambdas; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Random; public class Main { static List<Alumno> listaAlumnos = new ArrayList<>(); public static void main(String[] args) { crear(); obtenerTodos(); filtroNombre(); totalAlumnos(); notasAprobadas(); primerosAlumnos(); menorEdad(); primeroEnLista(); filtradoPorCaracter(); } public static void crear() { String[] nombres = {"Javier", "Lillian","Pedro","Manuel","Jose Julian","Gabriel","Martha","Joel","Juanjo","Maria"}; String[] apellidos = {"Molina Cano", "Gomez Alvarez","Duque", "Gonzalez","Gomez Gutierrez","Fernández de la Peña","Morillo Perez","Valente","Diaz Jiménez","Marin"}; final String nombreCurso = "Java 8"; for (int i = 0; i < 10; i++) { int calificacion = new Random().ints(2, 10).limit(1).findFirst().getAsInt(); int edad = new Random().ints(20, 40).limit(1).findFirst().getAsInt(); listaAlumnos.add(new Alumno(i, "12345" + i, nombres[i], apellidos [i], nombreCurso, calificacion, edad)); } } public static void obtenerTodos() { System.out.println("****Obtenemos todos los alumnos****"); listaAlumnos.stream().forEach(a->System.out.println(a)); } public static void filtroNombre() { System.out.println("****filtrado de alumnos cuyo nombre comience por L o G****"); listaAlumnos.stream().filter(c->c.getNombre().charAt(0)=='L' || c.getNombre().charAt(0) == 'G').forEach(c->System.out.println(c)); } public static void totalAlumnos() { System.out.println("****Imprimir el total de alumnos en la lista****"); System.out.println(listaAlumnos.stream().count()); } public static void notasAprobadas() { System.out.println("****Imprimir alumnos con notas mayores a 7****"); listaAlumnos.stream().filter(a->a.getNota() > 7).forEach(p->System.out.println(p)); } public static void primerosAlumnos() { System.out.println("****Obtener los primeros 3 alumnos****"); listaAlumnos.stream().limit(3).forEach(a -> System.out.println(a)); } public static void menorEdad() { System.out.println("****Obtener alumno con menor edad****"); System.out.println(listaAlumnos.stream().min(Comparator.comparing(Alumno::getEdad))); } public static void primeroEnLista() { System.out.println("****Imprimir primer alumno de la lista****"); System.out.println(listaAlumnos.stream().findFirst()); } public static void filtradoPorCaracter() { System.out.println("****filtrado de alumnos por caracter en su nombre****"); listaAlumnos.stream().filter(a->a.getNombre().contains("a")).forEach(System.out::println); } }
true
013fb72595253317ffde04f65db0b4853751c763
Java
BigScary/TekkitCustomizer
/src/me/ryanhamshire/TekkitCustomizer/BlockEventHandler.java
UTF-8
1,754
2.25
2
[]
no_license
/* TekkitCustomizer Server Plugin for Minecraft Copyright (C) 2012 Ryan Hamshire This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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 me.ryanhamshire.TekkitCustomizer; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; public class BlockEventHandler implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) public void onBlockPlace(BlockPlaceEvent placeEvent) { Player player = placeEvent.getPlayer(); Block block = placeEvent.getBlock(); MaterialInfo bannedInfo = TekkitCustomizer.instance.isBanned(ActionType.Ownership, player, block.getTypeId(), block.getData(), block.getLocation()); if(bannedInfo == null) { bannedInfo = TekkitCustomizer.instance.isBanned(ActionType.Placement, player, block.getTypeId(), block.getData(), block.getLocation()); } if(bannedInfo != null) { placeEvent.setCancelled(true); player.sendMessage("Sorry, that block is banned. Reason: " + bannedInfo.reason); } } }
true
5ce6b817516a7ab3df07a97acba9504f4d936886
Java
laivizhu/laivizhu.github.io
/sic/src/com/laivi/sic/basic/util/PropertiesUtil.java
UTF-8
1,414
2.953125
3
[]
no_license
package com.laivi.sic.basic.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; public class PropertiesUtil { private static final String PROPERTIES_FILE = "jdbc.properties"; public static String readData(String key) { Properties props = new Properties(); try { InputStream in = Resources.getResourceAsStream(PROPERTIES_FILE); props.load(in); in.close(); String value = props.getProperty(key); return value; } catch (FileNotFoundException e) { System.out.println("Properties File is not Found!"); e.printStackTrace(); return ""; } catch (IOException e) { System.out.println("Properties File Load Error!"); e.printStackTrace(); return ""; } } public static void writeData(String key, String value) { Properties props = new Properties(); try { File file = Resources.getResourceAsFile(PROPERTIES_FILE); if (!file.exists()) { file.createNewFile(); } InputStream in = new FileInputStream(file); props.load(in); in.close(); OutputStream os = new FileOutputStream(Resources.getResourceAsFile(PROPERTIES_FILE)); props.setProperty(key, value); props.store(os, "Update " + key + "' value"); os.close(); } catch (IOException e) { } } }
true
0206e50b1de3c713b7fe96562026fd817eb27fe2
Java
wangg121/ifindnbigdata
/javase/src/main/java/com/ifindn/annotation/method/MethodTest.java
UTF-8
844
3.140625
3
[]
no_license
package com.ifindn.annotation.method; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * 将注解注入到方法上 */ public class MethodTest { @MyTargetMethod(name = "zhangsan",age = 12) public void record(String name, int age){ System.out.println(name + age); } public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class clazz = MethodTest.class; Method record = clazz.getMethod("record",String.class,int.class); MyTargetMethod annotation = record.getAnnotation(MyTargetMethod.class); String name = annotation.name(); int age = annotation.age(); Object m = clazz.newInstance(); record.invoke(m,name,age); } }
true
fe62359424491a6ceefd688def0262612e99a6e0
Java
fujaba/fulib.org
/backend/src/main/java/org/fulib/webapp/tool/Tools.java
UTF-8
5,957
2.140625
2
[ "MIT" ]
permissive
package org.fulib.webapp.tool; import org.fulib.mockups.FulibMockups; import org.fulib.scenarios.tool.ScenarioCompiler; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import javax.tools.ToolProvider; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; public class Tools { // --------------- File Filters --------------- public static boolean isJava(Path file) { return file.toString().endsWith(".java"); } public static boolean isClass(Path file) { return file.toString().endsWith(".class"); } // --------------- File Utilities --------------- public static void deleteRecursively(Path dir) { try (final Stream<Path> stream = Files.walk(dir)) { stream.sorted(Comparator.reverseOrder()).forEach(file -> { try { Files.deleteIfExists(file); } catch (IOException ignored) { } }); } catch (IOException ignored) { } } // --------------- Tool Invocation --------------- public static int scenarioc( OutputStream out, OutputStream err, Path scenarioSrcDir, Path modelSrcDir, Path testSrcDir, String... args ) { final List<String> finalArgs = new ArrayList<>(8 + args.length); finalArgs.add("--classpath"); finalArgs.add(FulibMockups.class.getProtectionDomain().getCodeSource().getLocation().getPath()); finalArgs.add("-m"); finalArgs.add(modelSrcDir.toString()); finalArgs.add("-t"); finalArgs.add(testSrcDir.toString()); finalArgs.add(scenarioSrcDir.toString()); finalArgs.add("--diagram-handlers=.html.png=import(org.fulib.FulibTools).objectDiagrams().dumpPng(%s, %s)"); Collections.addAll(finalArgs, args); return new ScenarioCompiler().run(null, out, err, finalArgs.toArray(new String[0])); } public static int javac(String classpath, Path outFolder, Path... sourceFolders) throws IOException { return javac(null, null, classpath, outFolder, sourceFolders); } public static int javac(OutputStream out, OutputStream err, String classpath, Path outFolder, Path... sourceFolders) throws IOException { Files.createDirectories(outFolder); ArrayList<String> args = new ArrayList<>(); Arrays.stream(sourceFolders).flatMap(sourceFolder -> { try { // noinspection resource return Files.walk(sourceFolder).filter(Tools::isJava); } catch (IOException e) { return Stream.empty(); } }).map(Path::toString).forEach(args::add); args.add("-d"); args.add(outFolder.toString()); if (classpath != null) { args.add("-classpath"); args.add(classpath); } return ToolProvider.getSystemJavaCompiler().run(null, out, err, args.toArray(new String[0])); } public static Result runTests(Path mainClassesDir, Path testClassesDir) { URL[] classPathUrls = new URL[0]; try { classPathUrls = new URL[] { mainClassesDir.toUri().toURL(), testClassesDir.toUri().toURL() }; } catch (MalformedURLException e) { Logger.getGlobal().log(Level.SEVERE, "could not build classpath", e); } List<Class<?>> testClasses = new ArrayList<>(); try (final URLClassLoader classLoader = new URLClassLoader(classPathUrls); final Stream<Path> stream = Files.walk(testClassesDir)) { stream.filter(Tools::isClass).sorted().forEach(path -> { final String relativePath = testClassesDir.relativize(path).toString(); final String className = relativePath .substring(0, relativePath.length() - ".class".length()) .replace('/', '.') .replace('\\', '.'); try { final Class<?> testClass = Class.forName(className, true, classLoader); testClasses.add(testClass); } catch (ClassNotFoundException e) { throw new AssertionError(className + " should exist", e); } }); return new JUnitCore().run(testClasses.toArray(new Class[0])); } catch (IOException ex) { throw new RuntimeException("failed to walk " + testClassesDir.toString(), ex); } } public static int genCompileRun(// OutputStream out, OutputStream err,// Path srcDir, // Path modelSrcDir, Path testSrcDir,// Path modelClassesDir, Path testClassesDir,// String... scenariocArgs ) throws Exception { final PrintStream printErr = new PrintStream(err, false, StandardCharsets.UTF_8); try { final int scenarioc = scenarioc(out, err, srcDir, modelSrcDir, testSrcDir, scenariocArgs); if (scenarioc != 0) { return scenarioc << 2; } String classPath = System.getProperty("java.class.path"); try (final Stream<Path> stream = Files.walk(modelSrcDir)) { if (stream.anyMatch(Tools::isJava)) { // only compile model folder if there are any java files. final int modelJavac = javac(out, err, classPath, modelClassesDir, modelSrcDir); if (modelJavac != 0) { return modelJavac << 2 | 1; } } } final String testClassPath = modelClassesDir + File.pathSeparator + classPath; final int testJavac = javac(out, err, testClassPath, testClassesDir, testSrcDir); if (testJavac != 0) { return testJavac << 2 | 2; } // call all test methods final Result testResult = Tools.runTests(modelClassesDir, testClassesDir); for (final Failure failure : testResult.getFailures()) { printErr.print(failure.getTestHeader()); printErr.println("failed:"); failure.getException().printStackTrace(printErr); } final int failureCount = testResult.getFailureCount(); return failureCount == 0 ? 0 : failureCount << 2 | 3; } catch (Exception ex) { ex.printStackTrace(printErr); return -1; } finally { printErr.flush(); } } }
true
de1519bd5bc72f2d0818cc7cfa04d69284708d73
Java
saw303/dox
/core/src/test/java/ch/silviowangler/dox/AutomaticTranslatorAdviceTest.java
UTF-8
7,602
1.898438
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2012 - 2017 Silvio Wangler (silvio.wangler@gmail.com) * * 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 ch.silviowangler.dox; import static ch.silviowangler.dox.api.AttributeDataType.STRING; import static java.util.Locale.ENGLISH; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.google.common.collect.Sets; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import java.util.Arrays; import java.util.List; import java.util.Set; import ch.silviowangler.dox.api.Attribute; import ch.silviowangler.dox.api.DescriptiveIndex; import ch.silviowangler.dox.api.DocumentReference; import ch.silviowangler.dox.api.Domain; import ch.silviowangler.dox.api.NoTranslationFoundException; import ch.silviowangler.dox.api.TranslatableKey; import ch.silviowangler.dox.api.TranslationService; import ch.silviowangler.dox.aspect.AutomaticTranslatorAdvice; /** * @author Silvio Wangler * @since 0.1 */ @RunWith(MockitoJUnitRunner.class) public class AutomaticTranslatorAdviceTest { @InjectMocks private AutomaticTranslatorAdvice advice = new AutomaticTranslatorAdvice(); @Mock private TranslationService translationService; @Mock private MessageSource messageSource; @Test public void testAddTranslationIfNeeded() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); final String expectedTranslation = "This is an english text"; when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenReturn(expectedTranslation); Attribute attribute = new Attribute("hello", true, STRING); assertNull(attribute.getTranslation()); advice.addTranslationIfNeeded(attribute); assertThat(attribute.getTranslation(), is(expectedTranslation)); } @Test public void testAddTranslationIfNeededInCollections() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); final String expectedTranslation = "This is an english text"; when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenReturn(expectedTranslation); when(translationService.findTranslation("Attribute:and good bye", ENGLISH)).thenReturn(expectedTranslation); List<Attribute> list = Arrays.asList(new Attribute("hello", true, STRING), new Attribute("and good bye", true, STRING)); advice.addTranslationIfNeeded(list); for (Attribute attribute : list) { assertThat(attribute.getTranslation(), is(expectedTranslation)); } } @Test public void testAddTranslationIfNeededInArrays() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); final String expectedTranslation = "This is an english text"; when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenReturn(expectedTranslation); when(translationService.findTranslation("Attribute:and good bye", ENGLISH)).thenReturn(expectedTranslation); Attribute[] array = {new Attribute("hello", true, STRING), new Attribute("and good bye", true, STRING)}; advice.addTranslationIfNeeded(array); for (Attribute attribute : array) { assertThat(attribute.getTranslation(), is(expectedTranslation)); } } @Test public void testAddTranslationIfNeededInException() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenThrow(new NoTranslationFoundException("hello", ENGLISH)); final String expectedTranslation = "No translation available for key 'hello' and locale ''"; when(messageSource.getMessage("translationadvice.no.translation.available", new Object[]{"Attribute:hello", ENGLISH}, ENGLISH)).thenReturn(expectedTranslation); Attribute attribute = new Attribute("hello", true, STRING); assertNull(attribute.getTranslation()); advice.addTranslationIfNeeded(attribute); assertThat(attribute.getTranslation(), is(expectedTranslation)); } @Test public void testAddTranslationCompositeTranslatableIfNeededInException() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenThrow(new NoTranslationFoundException("hello", ENGLISH)); final String expectedDomainName = "Yet another domain name"; when(translationService.findTranslation("Domain:I.AM.A.DOMAN", ENGLISH)).thenReturn(expectedDomainName); final String expectedTranslation = "No translation available for key 'hello' and locale ''"; when(messageSource.getMessage("translationadvice.no.translation.available", new Object[]{"Attribute:hello", ENGLISH}, ENGLISH)).thenReturn(expectedTranslation); Attribute attribute = new Attribute("hello", true, new Domain("I.AM.A.DOMAN"), STRING, false); assertNull(attribute.getTranslation()); advice.addTranslationIfNeeded(attribute); assertThat(attribute.getDomain().getTranslation(), is(expectedDomainName)); } @Test public void testAnalyzeMapOfDocumentReference() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); DocumentReference documentReference = new DocumentReference("hello.txt"); documentReference.getIndices().put(new TranslatableKey("hello", null), new DescriptiveIndex("World")); when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenReturn("I am translated text"); advice.addTranslationIfNeeded(documentReference); assertTrue(documentReference.getIndices().containsKey(new TranslatableKey("hello"))); assertThat(documentReference.getIndices().size(), is(1)); assertThat(documentReference.getIndices().keySet().iterator().next().getTranslation(), is("I am translated text")); } @Test public void testAnalyzeMapOfDocumentReferenceOnSet() throws Throwable { LocaleContextHolder.setLocale(ENGLISH); DocumentReference documentReference = new DocumentReference("hello.txt"); documentReference.getIndices().put(new TranslatableKey("hello", null), new DescriptiveIndex("World")); Set<DocumentReference> resultSet = Sets.newHashSet(documentReference); when(translationService.findTranslation("Attribute:hello", ENGLISH)).thenReturn("I am translated text"); advice.addTranslationIfNeeded(resultSet); assertTrue(documentReference.getIndices().containsKey(new TranslatableKey("hello"))); assertThat(documentReference.getIndices().size(), is(1)); assertThat(documentReference.getIndices().keySet().iterator().next().getTranslation(), is("I am translated text")); } }
true
118703193cceecfe7a6279b953ad3fa68f4ce1fd
Java
coffeba/Spring
/spring-ssm-seckill/src/main/java/com/tazine/seckill/dao/SeckillOrdersDao.java
UTF-8
619
2.140625
2
[ "MIT" ]
permissive
package com.tazine.seckill.dao; import com.tazine.seckill.entity.SeckillOrders; /** * 秒杀订单 SeckillOrdersDao.xml Interface * * @author frank * @since 1.0.0 */ public interface SeckillOrdersDao { /** * 插入购买明细(可过滤重复) * * @param secKillId * @param userPhone * @return 如果影响行数>1,表示更新行数 */ int insertSeckill(long secKillId, long userPhone); /** * 根据id查询秒杀订单并携带秒杀实体 * * @param seckillId * @return */ SeckillOrders queryByIdWithSeckill(long seckillId); }
true
1e48b2a33c261a9cab490498b9a5f48de40db817
Java
csdavidg/users-mc
/src/test/java/com/uber/usersmc/service/TripServiceTest.java
UTF-8
1,905
2.25
2
[]
no_license
package com.uber.usersmc.service; import com.uber.usersmc.entity.Trip; import com.uber.usersmc.entity.User; import com.uber.usersmc.repository.TripDao; import com.uber.usersmc.repository.UserDao; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(SpringExtension.class) @Transactional @SpringBootTest public class TripServiceTest { @Autowired private TripDao tripDao; @Autowired private UserDao userDao; @Autowired private TripService tripService; private Trip trip; private User user; @BeforeEach public void setUp() { user = User.builder() .firstName("Cristian") .lastName("Sanchez") .phoneNumber(789456123) .build(); userDao.save(user); trip = Trip.builder() .user(user) .origin("home") .destiny("work") .build(); tripDao.save(trip); } @Test public void testSavingTrip() { Trip tripSave = tripService.createTrip(trip); assertNotNull(tripSave); assertNotNull(tripSave.getId()); } @Test public void testGettingTripsByUser() { List<Trip> trips = tripService.getTripsByUserId(user.getId()); assertEquals(trips.size(), 1); assertTrue(trips.contains(trip)); } }
true
d91b85dbef692cd586d300cdbe456ae01ef278ae
Java
openlangrid/wrappers
/Source Code/jp.ac.kyoto_u.i.soc.ai.langrid.webapps.opennlp/src/jp/ac/kyoto_u/i/soc/ai/langrid/webapps/opennlppostagger/OpenNLPPosTaggerService.java
UTF-8
6,400
1.945313
2
[]
no_license
package jp.ac.kyoto_u.i.soc.ai.langrid.webapps.opennlppostagger; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.en; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.de; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.da; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.nl; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.pt; import static jp.go.nict.langrid.language.ISO639_1LanguageTags.se; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.tokenize.TokenizerME; import opennlp.tools.tokenize.TokenizerModel; import jp.go.nict.langrid.language.Language; import jp.go.nict.langrid.service_1_2.InvalidParameterException; import jp.go.nict.langrid.service_1_2.ProcessFailedException; import jp.go.nict.langrid.service_1_2.morphologicalanalysis.typed.Morpheme; import jp.go.nict.langrid.service_1_2.typed.PartOfSpeech; import jp.go.nict.langrid.wrapper.ws_1_2.morphologicalanalysis.AbstractMorphologicalAnalysisService; public class OpenNLPPosTaggerService extends AbstractMorphologicalAnalysisService { private static final Map<String, PartOfSpeech> POS_TAG_MAP; private static Logger logger = Logger.getLogger(OpenNLPPosTaggerService.class.getName()); /** * Static Constructor */ static { //Initializing POS tag mapping between OpenNLP library and Language Grid //http://www.cis.upenn.edu/~treebank/ POS_TAG_MAP = new HashMap<String, PartOfSpeech>(); POS_TAG_MAP.put("XOTHER", PartOfSpeech.other); // *%$* POS_TAG_MAP.put("-LRB-", PartOfSpeech.other); // ( POS_TAG_MAP.put("-RRB-", PartOfSpeech.other); // ) POS_TAG_MAP.put("NNP", PartOfSpeech.noun_proper); POS_TAG_MAP.put("NNPS", PartOfSpeech.noun_proper); POS_TAG_MAP.put("NN", PartOfSpeech.noun_common); POS_TAG_MAP.put("NNS", PartOfSpeech.noun_common); POS_TAG_MAP.put("PRP", PartOfSpeech.noun_pronoun); POS_TAG_MAP.put("PRP$", PartOfSpeech.noun_pronoun); POS_TAG_MAP.put("NT", PartOfSpeech.noun); POS_TAG_MAP.put("NR", PartOfSpeech.noun); POS_TAG_MAP.put("VB", PartOfSpeech.verb); POS_TAG_MAP.put("VBD", PartOfSpeech.verb); POS_TAG_MAP.put("VBG", PartOfSpeech.verb); POS_TAG_MAP.put("VBN", PartOfSpeech.verb); POS_TAG_MAP.put("VBP", PartOfSpeech.verb); POS_TAG_MAP.put("VBZ", PartOfSpeech.verb); POS_TAG_MAP.put("VV", PartOfSpeech.verb); POS_TAG_MAP.put("JJ", PartOfSpeech.adjective); POS_TAG_MAP.put("JJR", PartOfSpeech.adjective); POS_TAG_MAP.put("JJS", PartOfSpeech.adjective); POS_TAG_MAP.put("RB", PartOfSpeech.adverb); POS_TAG_MAP.put("RBR", PartOfSpeech.adverb); POS_TAG_MAP.put("RBS", PartOfSpeech.adverb); POS_TAG_MAP.put("SYM", PartOfSpeech.unknown); } private String modelPath; public void setModelPath(String modelPath) { this.modelPath = modelPath; } /** * Constructor * @throws IOException */ public OpenNLPPosTaggerService() throws IOException { modelPath = getInitParameterString("modelPath", "/srv/openlangrid/resource/OpenNLP/models"); setSupportedLanguageCollection(Arrays.asList(en,da,de,nl,pt,se)); } @Override protected Collection<Morpheme> doAnalyze(Language language, String text) throws InvalidParameterException, ProcessFailedException { List<Morpheme> results = new LinkedList<Morpheme>(); // a list to store POS tagging result String tokens[] = null; try { tokens = tokinize(text, language); } catch(IOException e){ logger.log(Level.SEVERE, "failed to execute service.", e); throw new ProcessFailedException(e); } String tags[] = null; try { tags = POSTag(tokens, language); } catch(IOException e){ logger.log(Level.SEVERE, "failed to execute service.", e); throw new ProcessFailedException(e); } for(int i=0;i<tokens.length;i++) { String word = tokens[i]; String lemma = tokens[i]; String posText = tags[i]; //Mapping to langrid POS tag PartOfSpeech pos = POS_TAG_MAP.containsKey(posText)?POS_TAG_MAP.get(posText):PartOfSpeech.other; Morpheme morpheme = new Morpheme(word, lemma, pos); results.add(morpheme); } return results; } private String[] tokinize(String sentence, Language language) throws IOException { InputStream modelIn = null; modelIn = new FileInputStream(getTokinizerModelByLang(language)); TokenizerModel model = new TokenizerModel(modelIn); Tokenizer tokenizer = new TokenizerME(model); String tokens[] = tokenizer.tokenize(sentence); if (modelIn != null) modelIn.close(); return tokens; } private String[] POSTag(String[] tokens, Language language) throws IOException { InputStream modelIn = null; modelIn = new FileInputStream(getPOSModelByLang(language)); POSModel model = new POSModel(modelIn); POSTaggerME tagger = new POSTaggerME(model); String tags[] = tagger.tag(tokens); if (modelIn != null) modelIn.close(); return tags; } private String getPOSModelByLang(Language language) { String modelFileName = "en-pos-maxent.bin"; if(language == en ) modelFileName = "en-pos-maxent.bin"; if(language == da ) modelFileName = "da-pos-perceptron.bin"; if(language == de ) modelFileName = "de-pos-maxent.bin"; if(language == nl ) modelFileName = "nl-pos-maxent.bin"; if(language == pt ) modelFileName = "pt-pos-maxent.bin"; if(language == se ) modelFileName = "se-pos-maxent.bin"; return modelPath + File.separator + modelFileName; } private String getTokinizerModelByLang(Language language) { String modelFileName = "en-token.bin"; if(language == en ) modelFileName = "en-token.bin"; if(language == da ) modelFileName = "da-token.bin"; if(language == de ) modelFileName = "de-token.bin"; if(language == nl ) modelFileName = "nl-token.bin"; if(language == pt ) modelFileName = "pt-token.bin"; if(language == se ) modelFileName = "se-token.bin"; return modelPath + File.separator + modelFileName; } }
true
07db1f94b0c326ca0378ef38d0875293b04de3f5
Java
dlxotn216/advanced-java
/src/main/java/me/advanced/java/java8/in/action/ch07/optional/Ch07Application.java
UTF-8
382
1.882813
2
[]
no_license
package me.advanced.java.java8.in.action.ch07.optional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by taesu on 2018-07-12. */ @SpringBootApplication public class Ch07Application { public static void main(String[] args) { SpringApplication.run(Ch07Application.class); } }
true
f8108936125f58cac68c724668c922c71266c7c9
Java
Kai-Qian/Leetcode
/DP/96. Unique Binary Search Trees.java
UTF-8
1,794
3.515625
4
[ "MIT" ]
permissive
/* 比如,以1为根的树有几个,完全取决于有二个元素的子树有几种。同理,2为根的子树取决于一个元素的子树有几个。以3为根的情况,则与1相同。 定义Count[i] 为以[0,i]能产生的Unique Binary Tree的数目, 如果数组为空,毫无疑问,只有一种BST,即空树, Count[0] =1 如果数组仅有一个元素{1},只有一种BST,单个节点 Count[1] = 1 如果数组有两个元素{1,2}, 那么有如下两种可能 1 2 \ / 2 1 Count[2] = Count[0] * Count[1] (1为根的情况) + Count[1] * Count[0] (2为根的情况。 再看一遍三个元素的数组,可以发现BST的取值方式如下: Count[3] = Count[0]*Count[2] (1为根的情况,左边有0个数字,所以有count[0]种子树,右边有2个数字,所以有之前的count[2]种子树) + Count[1]*Count[1] (2为根的情况,左边有1个数字,所以有count[1]种子树,右边有1个数字,所以有之前的count[1]种子树) + Count[2]*Count[0] (3为根的情况,左边有2个数字,所以有count[2]种子树,右边有0个数字,所以有之前的count[0]种子树) 所以,由此观察,可以得出Count的递推公式为 Count[i] = ∑ Count[0...k] * [ k+1....i] 0<=k<i-1 问题至此划归为一维动态规划。 */ public class Solution { public int numTrees(int n) { if(n < 2) { return 1; } int[] ans = new int[n + 1]; ans[0] = 1; ans[1] = 1; for(int i = 2; i < n + 1; i++) { for(int j = 0; j < i; j++) { ans[i] = ans[i] + ans[j] * ans[i - j - 1]; } } return ans[n]; } }
true
f4f12854083ba4a078d0b67ad0515391366a0b17
Java
sagnik/pdffigures-scala
/pdfxtk/pdfXtk/src/main/java/at/ac/tuwien/dbai/pdfwrap/gui/exceptions/UnknownShapeException.java
UTF-8
653
3.078125
3
[ "Apache-2.0" ]
permissive
package at.ac.tuwien.dbai.pdfwrap.gui.exceptions; /** * This exception should be used if the shape that was specified by the user * is not known yet. * * @author Timo Schleicher * */ @SuppressWarnings("serial") public class UnknownShapeException extends IllegalArgumentException { /** * Creates a {@link UnknownShapeException} */ public UnknownShapeException() { super(); } /** * Creates a {@link UnknownShapeException} and adds the specified String * * @param s The shape of the name that is previously unknown */ public UnknownShapeException(String s) { super("The specified shape \"" + s + "\" is not known yet."); } }
true
8151f052102d2b302fceb6f8bf92491016397e83
Java
WeYaTa/ToDo-Android
/app/src/main/java/com/uph/finalproject/ui/login/LoadingFragment.java
UTF-8
1,595
1.820313
2
[]
no_license
package com.uph.finalproject.ui.login; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.fragment.app.Fragment; import androidx.room.Room; import com.uph.finalproject.KeyboardControl; import com.uph.finalproject.LoginActivity; import com.uph.finalproject.R; import com.uph.finalproject.application.MyApplication; import com.uph.finalproject.data.factory.AppDatabase; public class LoadingFragment extends Fragment { private EditText usernameEditText; private EditText passwordEditText; private CardView loginButton; private ProgressBar loadingProgressBar; private TextView register; private AppDatabase db; private CheckBox remember; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_loading, container, false); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
true
5e54858da3d26626a05d3c56df3977f3f335c8a0
Java
MinevoltRPG/Trails
/src/main/java/me/ccrama/Trails/listeners/BreakBlockListener.java
UTF-8
1,164
2.375
2
[ "Unlicense" ]
permissive
package me.ccrama.Trails.listeners; import com.jeff_media.customblockdata.CustomBlockData; import me.ccrama.Trails.Trails; import org.bukkit.NamespacedKey; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; public class BreakBlockListener implements Listener { private final Trails main; public BreakBlockListener(Trails plugin) { this.main = plugin; } @EventHandler public void breakBlock(BlockBreakEvent event) { final PersistentDataContainer customBlockData = new CustomBlockData(event.getBlock(), main); if (customBlockData.has(new NamespacedKey(main, "w"), PersistentDataType.INTEGER)) customBlockData.remove(new NamespacedKey(main, "w")); if (customBlockData.has(new NamespacedKey(main, "n"), PersistentDataType.STRING)) customBlockData.remove(new NamespacedKey(main, "n")); if (customBlockData.has(new NamespacedKey(main, "r"), PersistentDataType.STRING)) customBlockData.remove(new NamespacedKey(main, "r")); } }
true
edf0cded8930efa575614987b5c538b771c85983
Java
gibinaghi/amusement-park
/src/main/java/com/park/controller/ParkController.java
UTF-8
770
2.234375
2
[]
no_license
package com.park.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; //contolador de entrada para llamar endpoints que sirve para realizar el CRUD //de las operaciones del parque de diversiones @RestController @RequestMapping("/park") public class ParkController { //test para saber si se llega al servicio @PostMapping public ResponseEntity<Void> test(){ return ResponseEntity.ok().build(); } //create: crear un nuevo juego para el parque @PostMapping("/game") public ResponseEntity<Void> createGame(Game request){ return ResponseEntity.ok().build(); } }
true
f5291e26e6d40e1961e9ea22f788903a1c13587e
Java
moutainhigh/chdHRP
/src/com/chd/hrp/mat/entity/MatOrderMain.java
UTF-8
8,439
2
2
[]
no_license
/** * @Description: * @Copyright: Copyright (c) 2015-9-16 下午9:54:34 * @Company: 智慧云康(北京)数据科技有限公司 * @网站:www.s-chd.com */ package com.chd.hrp.mat.entity; import java.io.Serializable; import java.util.*; /** * * @Description: * state: 0:中止 1:新建 2:审核 3:执行完毕 4:已合并 * @Table: * MAT_ORDER_MAIN * @Author: bell * @email: bell@s-chd.com * @Version: 1.0 */ public class MatOrderMain implements Serializable { private static final long serialVersionUID = 5454155825314635342L; /** * 集团ID */ private Long group_id; /** * 医院ID */ private Long hos_id; /** * 账套编码 */ private String copy_code; /** * 订单ID */ private Long order_id; /** * 订单编号 */ private String order_code; /** * 订单日期 */ private Date order_date; /** * 采购方式 */ private Long pur_type; /** * 单据类型 */ private Long order_type; /** * 摘要 */ private String brif; /** * 供应商ID */ private Long sup_id; /** * 供应商变更ID */ private Long sup_no; /** * 采购部门ID */ private Long dept_id; /** * 采购部门变更ID */ private Long dept_no; /** * 采购员 */ private Long stocker; /** * 采购单位 */ private Long pur_hos_id; /** * 收货单位ID */ private Long take_hos_id; /** * 付款单位ID */ private Long pay_hos_id; /** * 采购类型 */ private String stock_type_code; /** * 付款条件 */ private String pay_code; /** * 到货地址 */ private String arr_address; /** * 制单人 */ private Long maker; /** * 制单日期 */ private Date make_date; /** * 审核人 */ private Long checker; /** * 审核日期 */ private Date check_date; /** * 状态 */ private Integer state; /** * 通知状态 */ private Integer is_notice; /** * 通知日期 */ private Date notice_date; /** * 备注 */ private String note; /** * 导入验证信息 */ private String error_type; /** * 设置 集团ID * @param value */ public void setGroup_id(Long value) { this.group_id = value; } /** * 获取 集团ID * @return Long */ public Long getGroup_id() { return this.group_id; } /** * 设置 医院ID * @param value */ public void setHos_id(Long value) { this.hos_id = value; } /** * 获取 医院ID * @return Long */ public Long getHos_id() { return this.hos_id; } /** * 设置 账套编码 * @param value */ public void setCopy_code(String value) { this.copy_code = value; } /** * 获取 账套编码 * @return String */ public String getCopy_code() { return this.copy_code; } /** * 设置 订单ID * @param value */ public void setOrder_id(Long value) { this.order_id = value; } /** * 获取 订单ID * @return Long */ public Long getOrder_id() { return this.order_id; } /** * 设置 订单编号 * @param value */ public void setOrder_code(String value) { this.order_code = value; } /** * 获取 订单编号 * @return String */ public String getOrder_code() { return this.order_code; } /** * 设置 订单日期 * @param value */ public void setOrder_date(Date value) { this.order_date = value; } /** * 获取 订单日期 * @return Date */ public Date getOrder_date() { return this.order_date; } /** * 设置 摘要 * @param value */ public void setBrif(String value) { this.brif = value; } /** * 获取 摘要 * @return String */ public String getBrif() { return this.brif; } /** * 设置 供应商ID * @param value */ public void setSup_id(Long value) { this.sup_id = value; } /** * 获取 供应商ID * @return Long */ public Long getSup_id() { return this.sup_id; } /** * 设置 供应商变更ID * @param value */ public void setSup_no(Long value) { this.sup_no = value; } /** * 获取 供应商变更ID * @return Long */ public Long getSup_no() { return this.sup_no; } /** * 设置 采购部门ID * @param value */ public void setDept_id(Long value) { this.dept_id = value; } /** * 获取 采购部门ID * @return Long */ public Long getDept_id() { return this.dept_id; } /** * 设置 采购部门变更ID * @param value */ public void setDept_no(Long value) { this.dept_no = value; } /** * 获取 采购部门变更ID * @return Long */ public Long getDept_no() { return this.dept_no; } /** * 设置 采购员 * @param value */ public void setStocker(Long value) { this.stocker = value; } /** * 获取 采购员 * @return Long */ public Long getStocker() { return this.stocker; } /** * 设置 采购单位 * @param value */ public void setPur_hos_id(Long value) { this.pur_hos_id = value; } /** * 获取 采购单位 * @return Long */ public Long getPur_hos_id() { return this.pur_hos_id; } /** * 设置 收货单位ID * @param value */ public void setTake_hos_id(Long value) { this.take_hos_id = value; } /** * 获取 收货单位ID * @return Long */ public Long getTake_hos_id() { return this.take_hos_id; } /** * 设置 付款单位ID * @param value */ public void setPay_hos_id(Long value) { this.pay_hos_id = value; } /** * 获取 付款单位ID * @return Long */ public Long getPay_hos_id() { return this.pay_hos_id; } /** * 设置 采购类型 * @param value */ public void setStock_type_code(String value) { this.stock_type_code = value; } /** * 获取 采购类型 * @return String */ public String getStock_type_code() { return this.stock_type_code; } /** * 设置 付款条件 * @param value */ public void setPay_code(String value) { this.pay_code = value; } /** * 获取 付款条件 * @return String */ public String getPay_code() { return this.pay_code; } /** * 设置 到货地址 * @param value */ public void setArr_address(String value) { this.arr_address = value; } /** * 获取 到货地址 * @return String */ public String getArr_address() { return this.arr_address; } /** * 设置 制单人 * @param value */ public void setMaker(Long value) { this.maker = value; } /** * 获取 制单人 * @return Long */ public Long getMaker() { return this.maker; } /** * 设置 制单日期 * @param value */ public void setMake_date(Date value) { this.make_date = value; } /** * 获取 制单日期 * @return Date */ public Date getMake_date() { return this.make_date; } /** * 设置 审核人 * @param value */ public void setChecker(Long value) { this.checker = value; } /** * 获取 审核人 * @return Long */ public Long getChecker() { return this.checker; } /** * 设置 审核日期 * @param value */ public void setCheck_date(Date value) { this.check_date = value; } /** * 获取 审核日期 * @return Date */ public Date getCheck_date() { return this.check_date; } /** * 设置 状态 * @param value */ public void setState(Integer value) { this.state = value; } /** * 获取 状态 * @return Integer */ public Integer getState() { return this.state; } /** * 设置 通知状态 * @param value */ public void setIs_notice(Integer value) { this.is_notice = value; } /** * 获取 通知状态 * @return Integer */ public Integer getIs_notice() { return this.is_notice; } /** * 设置 通知日期 * @param value */ public void setNotice_date(Date value) { this.notice_date = value; } /** * 获取 通知日期 * @return Date */ public Date getNotice_date() { return this.notice_date; } /** * 设置 备注 * @param value */ public void setNote(String value) { this.note = value; } /** * 获取 备注 * @return String */ public String getNote() { return this.note; } public Long getPur_type() { return pur_type; } public void setPur_type(Long pur_type) { this.pur_type = pur_type; } public Long getOrder_type() { return order_type; } public void setOrder_type(Long order_type) { this.order_type = order_type; } /** * 设置 导入验证信息 */ public void setError_type(String error_type) { this.error_type = error_type; } /** * 获取 导入验证信息 */ public String getError_type() { return error_type; } }
true
0474650884db4cb3306a9bd525922f44234ee146
Java
iqbal999/Online_Library_Management_System
/app/src/main/java/com/example/simu/olms/activities/Dashboard.java
UTF-8
4,880
1.9375
2
[]
no_license
package com.example.simu.olms.activities; import android.content.Intent; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.view.View; import android.widget.Toast; import com.example.simu.olms.R; import com.example.simu.olms.api.RetrofitClient; import com.example.simu.olms.model.DefaultResponse; import com.example.simu.olms.model.StudentInfo; import com.example.simu.olms.storage.SharedPrefManager; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.InstanceIdResult; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Dashboard extends AppCompatActivity implements View.OnClickListener { private CardView cv_profile, cv_logout, cv_issue_book, cv_return_book, cv_history, cv_all_request, cv_all_return_request; String token; private StudentInfo studentInfo; SharedPreferences prefs; String userType; Call<DefaultResponse> call; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); studentInfo = SharedPrefManager.getInstance(this).getStudentInfo(); prefs = getSharedPreferences(SharedPrefManager.SHARED_PREF_NAME, MODE_PRIVATE); userType = prefs.getString("user",null); FirebaseInstanceId.getInstance().getInstanceId() .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { if (task.isSuccessful()) { token = task.getResult().getToken(); saveToken(token); } else { Toast.makeText(Dashboard.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); cv_profile = findViewById(R.id.cardView_profile); cv_logout = findViewById(R.id.cardView_logout); cv_issue_book = findViewById(R.id.cardView_issue_book); cv_return_book = findViewById(R.id.cardView_return_book); cv_history = findViewById(R.id.cardView_history); cv_all_request = findViewById(R.id.cardView_all_request); cv_all_return_request = findViewById(R.id.cardView_return_request); cv_profile.setOnClickListener(this); cv_logout.setOnClickListener(this); cv_issue_book.setOnClickListener(this); cv_return_book.setOnClickListener(this); cv_history.setOnClickListener(this); cv_all_request.setOnClickListener(this); cv_all_return_request.setOnClickListener(this); } private void saveToken(String token) { if(userType.equals("Student")){ call = RetrofitClient .getInstance() .getApi() .saveToken(studentInfo.getId(), token); call.enqueue(new Callback<DefaultResponse>() { @Override public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) { } @Override public void onFailure(Call<DefaultResponse> call, Throwable t) { } }); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.cardView_profile: startActivity(new Intent(this, StudentProfile.class)); break; case R.id.cardView_logout: logout(); break; case R.id.cardView_issue_book: startActivity(new Intent(this, SearchBook.class)); break; case R.id.cardView_return_book: startActivity(new Intent(this, ShowIssuedBooks.class)); break; case R.id.cardView_history: startActivity(new Intent(this, ShowAllIssuedBooksOfUser.class)); break; case R.id.cardView_all_request: startActivity(new Intent(this, Request.class)); break; case R.id.cardView_return_request: startActivity(new Intent(this, AllReturnRequest.class)); break; } } private void logout() { SharedPrefManager.getInstance(getApplicationContext()).clear(); startActivity(new Intent(this,Login.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); } }
true
7d6dde4b2c7ad03505b0aa5c4778ee18d341f1ab
Java
MuhammedRishdhi123/Protabler
/app/src/main/java/com/example/protabler/JsonList/SessionList.java
UTF-8
387
2.046875
2
[]
no_license
package com.example.protabler.JsonList; import com.example.protabler.Dto.SessionDTO; import com.example.protabler.Entities.Session; import java.util.List; public class SessionList { private List<SessionDTO> List; public List<SessionDTO> getSessionList() { return List; } public void setSessionList(List<SessionDTO> list) { this.List = list; } }
true
bdae97e7b65265327013455c5fb9d9f1e6b92faa
Java
rslcvz/JDBC_Practice
/src/test/java/RestApiTests/SpartanTestsWithParameters.java
UTF-8
2,086
2.75
3
[]
no_license
package RestApiTests; import static io.restassured.RestAssured.*; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import io.restassured.RestAssured; import io.restassured.response.Response; import javafx.scene.layout.Priority; import org.testng.Assert; import org.testng.Assert.*; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SpartanTestsWithParameters { @BeforeClass public static void setUp() { // Base URL http://3.83.88.105:8000/api //BASE URI means all API end point share this portion. //We dont have to write everything -- You can give more specific RestAssured.baseURI = "http://54.164.29.19"; RestAssured.port = 8000; RestAssured.basePath = "/api"; } @Test public void test(){ Response response = get("/hello"); System.out.println("response.statusCode() = " + response.statusCode()); System.out.println(response.asString()); System.out.println(response.getHeader("content-type")); } @Test public void helloTest(){ Response response = get("/hello"); assertEquals(200, response.statusCode()); assertEquals("Hello from Sparta", response.asString()); // rest assured ;ibrary provide multiple method with same meaning //like getHeader = header, getContentType=contentType, statusCode = getStatusCode assertEquals("text/plain;charset=UTF-8", response.header("content-type")); } @Test public void Hello_EndPoint_HeaderContains_Test(){ Response response = get("/hello"); String headerValue = response.getHeader("Date"); System.out.println("headerValue = " + headerValue); //its giving you the date or null(Both Passing) //if its null dont pass, this is how we do it. assertNotNull(headerValue); assert response.getHeaders().hasHeaderWithName("Date"); // Get header returns String, you cannt assert with a number. assertEquals ("17", response.getHeader("content-length")); } }
true
700c9a6cf4cc50d8f4fe4e21b5b3586bafea48e7
Java
GustavoRuiz9/Projects
/ProyectoGrado/src/Vista/GUIProyecto.java
UTF-8
18,436
2.125
2
[]
no_license
package Vista; import Control.reporteProyectos; import Control.ejecucionBD; import Control.funcionesComunes; import javax.swing.JOptionPane; import Modelo.MiModelo; import java.awt.Image; import javax.swing.ImageIcon; /** * * @author tavo */ public class GUIProyecto extends java.awt.Dialog { MiModelo modeloTable; GUIAgregarProyecto nuevoProyecto; int contC = 0; Image logo = new ImageIcon(getClass().getResource("/Imagen/logo_ventana.png")).getImage(); public GUIProyecto(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); this.setLocationRelativeTo(null); this.setResizable(false); modeloTable = new MiModelo(); tablaProyectos.setModel(modeloTable); // consulta de proyectos para el Director que inicio sesion ejecucionBD.sql = "select codigo_proy as \"PROYECTO\", titulo as \"TITULO\", CLIENTE.nombre as \"CLIENTE\"," + "cant_personas as \"NUM. DESARROLLADORES\", num_entregas as \"NUM. ENTREGAS\",\n" + "TO_CHAR (fecha_inicio,'dd/MM/yyyy') as \"INICIO\", TO_CHAR (fecha_fin,'dd/MM/yyyy') " + "as \"FIN\", valor_final as \"VALOR FINAL\" from proyecto, cliente where " + "proyecto.cliente = cliente.codigo_cliente order by proyecto.codigo_proy"; funcionesComunes.cargarTabla(modeloTable); this.setTitle("Proyectos"); this.setIconImage(logo); // labelNumProy.setText("Proyectos: " + ejecucionBD.cantidadRegistros()); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tablaProyectos = new javax.swing.JTable(); jPanel3 = new javax.swing.JPanel(); botonAdd = new javax.swing.JButton(); btoDrop = new javax.swing.JButton(); btoUpd = new javax.swing.JButton(); btonView = new javax.swing.JButton(); btonView1 = new javax.swing.JButton(); btonClose = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); tituloPantProy = new javax.swing.JLabel(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { closeDialog(evt); } }); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); tablaProyectos.setBackground(new java.awt.Color(0, 153, 153)); tablaProyectos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); tablaProyectos.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N tablaProyectos.setForeground(new java.awt.Color(51, 51, 51)); tablaProyectos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); tablaProyectos.setAlignmentX(0.0F); tablaProyectos.setAlignmentY(0.0F); tablaProyectos.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); tablaProyectos.setGridColor(new java.awt.Color(0, 255, 51)); tablaProyectos.setSelectionBackground(new java.awt.Color(153, 255, 255)); tablaProyectos.setSelectionForeground(new java.awt.Color(0, 0, 0)); jScrollPane1.setViewportView(tablaProyectos); jPanel3.setBackground(new java.awt.Color(102, 102, 102)); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("")); botonAdd.setText("Agregar"); botonAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botonAddActionPerformed(evt); } }); btoDrop.setText("Borrar"); btoDrop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btoDropActionPerformed(evt); } }); btoUpd.setText("Modificar"); btoUpd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btoUpdActionPerformed(evt); } }); btonView.setText("Visualizar"); btonView.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btonViewActionPerformed(evt); } }); btonView1.setText("Observaciones"); btonView1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btonView1ActionPerformed(evt); } }); btonClose.setText("Menu"); btonClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btonCloseActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(botonAdd) .addGap(30, 30, 30) .addComponent(btoDrop) .addGap(30, 30, 30) .addComponent(btoUpd) .addGap(30, 30, 30) .addComponent(btonView) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btonView1) .addGap(30, 30, 30) .addComponent(btonClose) .addGap(40, 40, 40)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botonAdd) .addComponent(btoDrop) .addComponent(btoUpd) .addComponent(btonView) .addComponent(btonView1) .addComponent(btonClose)) .addContainerGap(20, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 856, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(0, 0, 0)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, 0) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(0, 0, 0)) ); jPanel2.setBackground(new java.awt.Color(102, 102, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); tituloPantProy.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N tituloPantProy.setText("PROYECTOS BMS"); tituloPantProy.setVerticalAlignment(javax.swing.SwingConstants.TOP); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(373, 373, 373) .addComponent(tituloPantProy) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(21, Short.MAX_VALUE) .addComponent(tituloPantProy) .addGap(19, 19, 19)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog if ((JOptionPane.showOptionDialog(this, "¿Desea cerrar la App o ir a Menu?", "Salir", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"Cerrar App", "Menu"}, "Cerrar")) == 0) { System.exit(0); } else { this.dispose(); new GUIMenuDirector(null, true).setVisible(true); } }//GEN-LAST:event_closeDialog private void botonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAddActionPerformed nuevoProyecto = new GUIAgregarProyecto(null, true, modeloTable, tablaProyectos); nuevoProyecto.setVisible(true); }//GEN-LAST:event_botonAddActionPerformed private void btoUpdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btoUpdActionPerformed String campo = null; ejecucionBD.sql = "select * from proyecto order by codigo_proy"; ejecucionBD.ejecutarConsulta(); campo = ejecucionBD.ubicarCursor(tablaProyectos.getSelectedRow()); if (campo != null) { ejecucionBD.sql = "select codigo_proy, cant_personas, est_cant_pers, num_entregas, titulo, categoria, cliente, " + "TO_CHAR (fecha_inicio,'dd/MM/yyyy') as \"FECHA_INICIO\", TO_CHAR (fecha_fin,'dd/MM/yyyy') as \"FECHA_FIN\"," + " TO_CHAR(fecha_fin_real,'dd/MM/yyyy') as \"FECHA_FIN_REAL\", valor_estimado, valor_final, " + "estado, rangopf from proyecto where codigo_proy='" + campo + "'"; if (ejecucionBD.ejecutarConsulta()) { nuevoProyecto = new GUIAgregarProyecto(null, true, modeloTable, tablaProyectos, ejecucionBD.obtenerObjeto()); nuevoProyecto.setVisible(true); } } else { JOptionPane.showMessageDialog(null, "Antes de modificar, seleccione un Proyecto!", "Atencion", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_btoUpdActionPerformed private void btonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btonCloseActionPerformed this.dispose(); new GUIMenuDirector(null, true).setVisible(true); // GUIMenuDirector.Proyectos.setVisible(false); }//GEN-LAST:event_btonCloseActionPerformed private void btoDropActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btoDropActionPerformed try { String titulo = null; String campo = null; ejecucionBD.sql = "select * from proyecto order by codigo_proy"; ejecucionBD.ejecutarConsulta(); campo = ejecucionBD.ubicarCursor(tablaProyectos.getSelectedRow()); if (tablaProyectos.getSelectedRow() != -1) { titulo = ejecucionBD.result.getString("TITULO"); } if (campo != null) { ejecucionBD.sql = "select * from entrega where proyecto ='" + campo + "'"; ejecucionBD.ejecutarConsulta(); if (ejecucionBD.cantidadRegistros() == 0) { ejecucionBD.sql = "select * from observacion where codigo_proy ='" + campo + "'"; ejecucionBD.ejecutarConsulta(); if (ejecucionBD.cantidadRegistros() > 0) { if (JOptionPane.showConfirmDialog(null, "Desea borrar el proyecto " + titulo + " y su Observacion") == 0) { if (ejecucionBD.ejecutarDelete("Observacion", campo, "codigo_proy")) { if (ejecucionBD.ejecutarDelete("Proyecto", campo, "codigo_proy")) { ejecucionBD.sql = "select codigo_proy as \"PROYECTO\", titulo as \"TITULO\", CLIENTE.nombre as \"CLIENTE\"," + "cant_personas as \"NUM. DESARROLLADORES\", num_entregas as \"NUM. ENTREGAS\",\n" + "TO_CHAR (fecha_inicio,'dd/MM/yyyy') as \"INICIO\", TO_CHAR (fecha_fin,'dd/MM/yyyy') " + "as \"FIN\", valor_final as \"VALOR FINAL\" from proyecto, cliente where " + "proyecto.cliente = cliente.codigo_cliente order by proyecto.codigo_proy"; modeloTable = new MiModelo(); funcionesComunes.cargarTabla(modeloTable); tablaProyectos.setModel(modeloTable); } } } } else { if (JOptionPane.showConfirmDialog(null, "Desea borrar el proyecto " + titulo) == 0) { if (ejecucionBD.ejecutarDelete("Proyecto", campo, "codigo_proy")) { ejecucionBD.sql = "select codigo_proy as \"PROYECTO\", titulo as \"TITULO\", CLIENTE.nombre as \"CLIENTE\"," + "cant_personas as \"NUM. DESARROLLADORES\", num_entregas as \"NUM. ENTREGAS\",\n" + "TO_CHAR (fecha_inicio,'dd/MM/yyyy') as \"INICIO\", TO_CHAR (fecha_fin,'dd/MM/yyyy') " + "as \"FIN\", valor_final as \"VALOR FINAL\" from proyecto, cliente where " + "proyecto.cliente = cliente.codigo_cliente"; modeloTable = new MiModelo(); funcionesComunes.cargarTabla(modeloTable); tablaProyectos.setModel(modeloTable); } } } } else { JOptionPane.showMessageDialog(null, "El proyecto " + titulo + " tiene asociado entregas, para poder eliminarlo\n" + "primero borre esas entregas", "Alerta", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Antes de borrar, seleccione un Proyecto!", "Atencion", JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { System.out.println("Error en Borrar Proyecto"); } }//GEN-LAST:event_btoDropActionPerformed private void btonViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btonViewActionPerformed reporteProyectos reporteProyecto = new reporteProyectos("Proyectos Best Mind Software", "ReporteProyectos.pdf"); int respuesta = JOptionPane.showConfirmDialog(null, "Se ha generado el documento, ¿Desea abrirlo?", "Pregunta", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (respuesta == JOptionPane.YES_OPTION) { reporteProyecto.abrirPDF(); } }//GEN-LAST:event_btonViewActionPerformed private void btonView1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btonView1ActionPerformed // TODO add your handling code here: GUIObservacion a = new GUIObservacion(null, true); a.setVisible(true); }//GEN-LAST:event_btonView1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botonAdd; private javax.swing.JButton btoDrop; private javax.swing.JButton btoUpd; private javax.swing.JButton btonClose; private javax.swing.JButton btonView; private javax.swing.JButton btonView1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tablaProyectos; private javax.swing.JLabel tituloPantProy; // End of variables declaration//GEN-END:variables }
true
af17e5012d7dd3a39120bead92d9072e26150fee
Java
Fuzzy3/Picchal
/app/src/main/java/com/oestbalmer/android/pichal/Authenticatation/AuthService.java
UTF-8
872
2.3125
2
[]
no_license
package com.oestbalmer.android.pichal.Authenticatation; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.oestbalmer.android.pichal.DatabaseService; import com.oestbalmer.android.pichal.Model.User; public class AuthService extends DatabaseService implements IAuthService { @Override public void createUser(IAuthService.onUserCreated listener) { FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if(firebaseUser != null) { User user = new User(firebaseUser.getDisplayName(), firebaseUser.getUid(), firebaseUser.getEmail()); DatabaseReference mSingleUserRef = mUsersRef.child(user.getId()); mSingleUserRef.setValue(user); listener.onFinished(); } } }
true
1cf9fb521e348690141b5554dd8afda120c420d6
Java
mario-4/java-lab
/spring-restapi/src/main/java/com/appgenesislab/rest/repository/JpaCrmService.java
UTF-8
3,705
2.421875
2
[]
no_license
package com.appgenesislab.rest.repository; import com.appgenesislab.rest.exception.CustomerNotFoundException; import com.appgenesislab.rest.exception.UserNotFoundException; import com.appgenesislab.rest.model.Customer; import com.appgenesislab.rest.model.User; import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.util.*; @Service @Transactional class JpaCrmService implements CrmService { private CustomerRepository customerRepository; private UserRepository userRepository; @Autowired public JpaCrmService(CustomerRepository customerRepository, UserRepository userRepository) { this.customerRepository = customerRepository; this.userRepository = userRepository; } @Override public Collection<Customer> search(long userId, String token) { return this.customerRepository.search(userId, "%" + token + "%"); } @Override public User findById(long userId) { User user = userRepository.findOne(userId); if (null == user) throw new UserNotFoundException(userId); return user; } @Override public User createUser(String username, String password, String firstName, String lastName) { User user = new User(username, password, firstName, lastName); this.userRepository.save(user); return user; } @Override public User removeUser(long userId) { User u = userRepository.findOne(userId); this.userRepository.delete(userId); return u; } @Override public User updateUser(long userId, String username, String password, String firstName, String lastName) { User user = userRepository.findOne(userId); user.setUsername(username); user.setFirstName(firstName); user.setLastName(lastName); user.setPassword(password); return this.userRepository.save(user); } @Override public User findUserByUsername(String username) { return userRepository.findByUsername(username); } @Override public Customer removeCustomer(long userId, long customerId) { User user = userRepository.findOne(userId); Customer customer = customerRepository.findOne(customerId); user.getCustomers().remove(customer); this.userRepository.save(user); customer.setUser(null); this.customerRepository.delete(customer); return customer; } @Override public Customer addCustomer(long userId, String firstName, String lastName) { Customer customer = new Customer(this.userRepository.findOne(userId), firstName, lastName, new Date()); return this.customerRepository.save(customer); } @Override public Collection<Customer> loadCustomerAccounts(long userId) { List<Customer> customersList = this.customerRepository.findByUserId(userId); ArrayList<Customer> customers = new ArrayList<Customer>(); for (Customer c : customersList) { Hibernate.initialize(c); User user = new User(userId); c.setUser(user); customers.add(c); } return Collections.unmodifiableList(customers); } @Override public Customer findCustomerById(long customerId) { Customer customer = customerRepository.findOne(customerId); if (null == customer) throw new CustomerNotFoundException(customerId); Hibernate.initialize(customer.getUser()); return customer; } }
true
df2ce48d9c40e93f9be313e5d34638ac5f489134
Java
yanglin0883/leetcode
/5416/Solution.java
UTF-8
360
3.109375
3
[]
no_license
class Solution { public int isPrefixOfWord(String sentence, String searchWord) { String[] words = sentence.split(" "); for(int i=0;i<words.length;i++){ if(words[i].length()<searchWord.length())continue; if(words[i].substring(0,searchWord.length()).equals(searchWord)) return i+1; } return -1; } }
true
ed1a71dba33e66285768199d2f28134746c70f64
Java
AntonSolomin/myApp
/src/main/java/com/myApp/myApp/entities/PostReview.java
UTF-8
1,222
2.390625
2
[]
no_license
package com.myApp.myApp.entities; import javax.persistence.*; import java.util.Date; /** * Created by Anton on 01-Nov-17. */ @Entity public class PostReview { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private Date timestamp; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="post_id") private Post post; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name="user_id") private User user; public PostReview () {} public PostReview (User user, Post post) { this.timestamp = new Date(); this.post = post; this.user = user; post.addReview(this); user.addReview(this); } public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
true
98de9df4564c2a68c279dde5443fb78e024360ca
Java
akoscynich/NNtests
/src/test/java/_Data.java
UTF-8
5,385
2.125
2
[ "Apache-2.0" ]
permissive
import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static java.lang.Integer.parseInt; import static java.util.Arrays.asList; public class _Data extends _Manager { //Ссылки public static String homePage = baseUrl + "/ru/"; public static String cart = baseUrl + "/ru/checkout/cart/"; public static String reg = baseUrl + "/ru/customer/account/create/"; public static String myAccount = baseUrl + "/ru/customer/account/"; //Кнопки public static void openMiniCart() { click(By.cssSelector("a.action.showcart")); } public static void clearMiniCart() { click(By.xpath("//div[2]/div[1]/div[2]/a")); } public static By logIn = By.cssSelector("div.welcome.welcome-ppl"); public static By createAccount = By.xpath("//div/div[2]/div/div[2]/div"); public static By submitReg = By.cssSelector("#form-validate > div > div.primary > button"); //Локаторы public static String summInMiniCart = "//div[2]/div/div[2]/span"; public static String priceInMiniCart = "//div[3]/span[2]/span"; public static String totalInMiniCart = "//div[4]/div[1]/div/span/span"; public static By firstnameRegField = By.name("firstname"); public static By lastnameRegField = By.name("lastname"); public static By machineCodeRegField = By.name("machine_code_reg"); public static By telephone = By.cssSelector("input.input-text.required-entry.validate-nsp-telephone"); public static By eMailRegField = By.name("email"); public static By passRegField = By.name("password"); public static By passConfRegField = By.name("password_confirmation"); //Список размеров окна public static List<String> breakPoints() { List<String> breakPoints = new ArrayList<>(); breakPoints.add(0, "1920"); breakPoints.add(1, "768"); breakPoints.add(2, "320"); return breakPoints; } //Список категорий public static List<String> categories() { List<String> categories = new ArrayList<>(); categories.add(0, baseUrl + "/ru/coffee-capsules"); categories.add(1, baseUrl + "/ru/coffee-machines-1"); categories.add(2, baseUrl + "/ru/accessories"); return categories; } //Список основных страниц public static List<String> mainPages() { List<String> categories = new ArrayList<>(); categories.add(0, baseUrl + "/ru/coffee-capsules"); categories.add(1, baseUrl + "/ru/coffee-machines-1"); categories.add(2, baseUrl + "/ru/accessories"); categories.add(3, baseUrl + "/ru/"); return categories; } //Собирает список ссылок с текущей страницы public static List<String> listOfLinks() { List<WebElement> allTheLinkList = finds(By.tagName("a")); List<String> links = new ArrayList<>(); for (WebElement link : allTheLinkList) { if (link.getAttribute("href") != null && !(link.getAttribute("href").equals(""))) { links.add(link.getAttribute("href")); } } return links; } //Собирает множетство ссылок с текущей страницы public static Set<String> setOfLinks() { Set<WebElement> allTheLinkList = new HashSet<>(finds(By.tagName("a"))); Set<String> links = new HashSet<>(); for (WebElement link : allTheLinkList) { if (link.getAttribute("href") != null && !(link.getAttribute("href").equals(""))) { links.add(link.getAttribute("href")); } } return links; } //Собирает список всех сумм в корзине в виде строк удаляя все символы кроме цифр public static List<String> summsFromMiniCart() { List<WebElement> summs = finds(By.xpath(_Data.summInMiniCart)); List<String> summText = new ArrayList<>(); for (WebElement sum : summs) { List<String> formatedString = new ArrayList<>(asList((sum.getText()).split(" "))); formatedString.remove(formatedString.size() - 1); summText.add(formatedString.stream().map(String::toString).collect(Collectors.joining(""))); } return summText; } //Количество продуктов на странице в категории public static int productCount() { return finds(By.cssSelector("div.product.name.product-item-name")).size(); } //Находит элемент по локатору, берет его текст, режет на части по пробелам удаляет последний элемент, //склеивает в строку то что осталось и парсит в int. //Например преобразует строку "123 456 руб." в int 123456 public static int i(String link) { List<String> i = new ArrayList<>(asList(getText(By.xpath(link)).split(" "))); i.remove(i.size() - 1); return parseInt(i.stream().map(String::toString).collect(Collectors.joining(""))); } }
true
a1e659578d331197f57ce9770bbee5ec91768d1a
Java
jambestwick/HackWechat
/app/src/main/java/com/tencent/mm/ui/base/preference/InputPreference.java
UTF-8
1,253
1.851563
2
[]
no_license
package com.tencent.mm.ui.base.preference; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView.OnEditorActionListener; import com.tencent.mm.w.a.g; public class InputPreference extends Preference { private String rYb; private a rYe; private OnClickListener rYh; private String yiN; private EditText yiO; private Button yiP; private OnEditorActionListener yiQ; public InputPreference(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public InputPreference(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); this.rYh = new 1(this); this.yiQ = new 2(this); } protected final void onBindView(View view) { super.onBindView(view); this.yiO = (EditText) view.findViewById(g.cdj); this.yiO.setHint(this.rYb); this.yiO.setOnEditorActionListener(this.yiQ); this.yiP = (Button) view.findViewById(g.button); this.yiP.setText(this.yiN); this.yiP.setOnClickListener(this.rYh); } }
true
5117177938e84341b97d4329e526b1bed6f9df14
Java
xcesco/kripton
/kripton-sqlite-test-library/src/main/java/com/abubusoft/kripton/android/sqlite/SQLiteTestUtils.java
UTF-8
15,452
1.882813
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2015, 2017 Francesco Benincasa (info@abubusoft.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.abubusoft.kripton.android.sqlite; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; import com.abubusoft.kripton.android.Logger; import com.abubusoft.kripton.android.sqlite.SQLiteUpdateTaskHelper.OnResultListener; import com.abubusoft.kripton.android.sqlite.SQLiteUpdateTaskHelper.QueryType; import com.abubusoft.kripton.android.sqlite.commons.IOUtils; import com.abubusoft.kripton.android.sqlite.internals.MigrationSQLChecker; import com.abubusoft.kripton.common.StringUtils; import com.abubusoft.kripton.exception.KriptonRuntimeException; import com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlBaseListener; import com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlLexer; import com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser; import com.abubusoft.kripton.processor.sqlite.grammars.jsql.JqlParser.Sql_stmtContext; import android.content.Context; import androidx.sqlite.db.SupportSQLiteDatabase; /** * <p> * Utility class containing useful methods to: * </p> * * <ul> * <li>clear test database</li> * <li>massive table renaming</li> * <li>massive table drops</li> * <li>retrieve table and index lists</li> * <li>execute SQL statements</li> * <li>schema verification</li> * * * @author Francesco Benincasa (info@abubusoft.com) */ public abstract class SQLiteTestUtils { /** * Reset instance. * * @param classDataSource * the class data source */ public static void resetDataSourceInstance(Class<? extends AbstractDataSource> classDataSource) { Field threadLocalField; try { threadLocalField = classDataSource.getDeclaredField("instance"); threadLocalField.setAccessible(true); threadLocalField.set(null, null); threadLocalField.setAccessible(false); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { e.printStackTrace(); throw (new KriptonRuntimeException(e)); } } /** * Query. * * @param db * the db * @param conditions * the conditions * @param type * the type * @param listener * the listener */ private static void query(SupportSQLiteDatabase db, String conditions, QueryType type, OnResultListener listener) { SQLiteUpdateTaskHelper.query(db, conditions, type, listener); } /** * Drop all entity of particular type (table or index). If prefix is * specified, the drop operation is applied only to entity with prefix. * * @param db * the db * @param type * the type * @param prefix * the prefix */ private static void drop(SupportSQLiteDatabase db, final QueryType type, String prefix) { String dropSQL = StringUtils.hasText(prefix) ? "name like '" + prefix + "' || '%'" : null; query(db, dropSQL, type, new OnResultListener() { @Override public void onRow(SupportSQLiteDatabase db, String name, String sql) { String drop = "DROP " + type.toString().toUpperCase() + " " + name; Logger.info(drop); db.execSQL(drop); } }); } /** * Retrieve all table as a Map of (name, sql). * * @param db * the db * @return the all tables */ public static Map<String, String> getAllTables(SupportSQLiteDatabase db) { return SQLiteUpdateTaskHelper.getAllTables(db); } /** * Add to all schema's table a specifix prefix. * * @param db * the db * @param prefix * the prefix */ public static void renameAllTablesWithPrefix(SupportSQLiteDatabase db, final String prefix) { Logger.info("MASSIVE TABLE RENAME OPERATION: ADD PREFIX " + prefix); query(db, null, QueryType.TABLE, new OnResultListener() { @Override public void onRow(SupportSQLiteDatabase db, String name, String sql) { sql = String.format("ALTER TABLE %s RENAME TO %s%s;", name, prefix, name); Logger.info(sql); db.execSQL(sql); } }); } /** * Drop all table with specific prefix. * * @param db * the db * @param prefix * the prefix */ public static void dropTablesWithPrefix(SupportSQLiteDatabase db, String prefix) { Logger.info("MASSIVE TABLE DROP OPERATION%s", StringUtils.ifNotEmptyAppend(prefix, " WITH PREFIX ")); drop(db, QueryType.TABLE, prefix); } /** * Drop tables and indices. * * @param db * the db */ public static void dropTablesAndIndices(SupportSQLiteDatabase db) { drop(db, QueryType.INDEX, null); drop(db, QueryType.TABLE, null); } /** * Retrieve all indexes as a Map of (name, sql). * * @param db * the db * @return indexes */ public static Map<String, String> getAllIndexes(SupportSQLiteDatabase db) { return SQLiteUpdateTaskHelper.getAllIndexes(db); } /** * Execute SQL contained in raw resource. * * @param database * the database * @param context * the context * @param rawResourceId * the raw resource id */ public static void executeSQL(final SupportSQLiteDatabase database, Context context, int rawResourceId) { String[] c = IOUtils.readTextFile(context, rawResourceId).split(";"); List<String> commands = Arrays.asList(c); executeSQL(database, commands); } /** * Read SQL from file. * * @param fileName * the file name * @return the list */ public static List<String> readSQLFromFile(String fileName) { try { return readSQLFromFile(new FileInputStream(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } /** * Execute SQL from file. * * @param database * the database * @param fileName * the sql definition file */ public static void executeSQLFromFile(SupportSQLiteDatabase database, String fileName) { List<String> executionList = readSQLFromFile(fileName); for (String item : executionList) { Logger.info(item); database.execSQL(item); } } /** * Read SQL from file. * * @param fileInputStream * the file input stream * @return the list */ public static List<String> readSQLFromFile(InputStream fileInputStream) { String content = IOUtils.readText(fileInputStream); // remove comments content = content.replaceAll("\\/\\*.*\\*\\/", ""); content = content.replaceAll("--.*\n", ""); content = content.replaceAll("\n", ""); final String buffer = content; final List<String> executionList = new ArrayList<>(); MigrationSQLChecker.getInstance().analyze(content, new JqlBaseListener() { public void enterSql_stmt(Sql_stmtContext ctx) { int start = ctx.getStart().getStartIndex(); int stop = ctx.getStop().getStopIndex() + 1; if (start == stop) return; String statement = buffer.substring(start, stop).trim(); executionList.add(statement); }; }); return executionList; /* * String[] c = content.split(";"); List<String> commands = new * ArrayList<>(); for (String i : c) { if (StringUtils.hasText(i)) { * commands.add(i.trim()); } } * * return commands; */ } /** * Execute SQL. * * @param database * the database * @param fileInputStream * the file input stream */ public static void executeSQL(final SupportSQLiteDatabase database, InputStream fileInputStream) { List<String> commands = readSQLFromFile(fileInputStream); executeSQL(database, commands); } /** * Execute SQL. * * @param database * the database * @param commands * the commands */ public static void executeSQL(final SupportSQLiteDatabase database, List<String> commands) { for (String command : commands) { executeSQL(database, command); } // commands.forEach(command -> { // executeSQL(database, command); // }); } /** * Execute SQL. * * @param database * the database * @param command * the command */ public static void executeSQL(final SupportSQLiteDatabase database, String command) { // remove comments command = command.replaceAll("\\/\\*.*\\*\\/", ""); command = command.replaceAll("--.*$", ""); if (command.trim().length() > 0) { Logger.info(command); database.execSQL(command); } } /** * Verify schema. * * @param database * the database * @param inputStream * the input stream */ public static void verifySchema(SupportSQLiteDatabase database, InputStream inputStream) { List<String> ddl = extractCommands(database, inputStream); verifySchemaInternal(database, ddl); } /** * Verify schema. * * @param <H> * the generic type * @param dataSource * the data source * @param inputStream * the input stream */ public static <H extends AbstractDataSource> void verifySchema(H dataSource, InputStream inputStream) { verifySchema(dataSource.openWritableDatabase(), inputStream); } /** * Verify schema. * * @param database * the database * @param context * the context * @param rawId * the raw id */ public static void verifySchema(SupportSQLiteDatabase database, Context context, int rawId) { verifySchema(database, context.getResources().openRawResource(rawId)); } /** * Extract commands. * * @param database * the database * @param inputStream * the input stream * @return the list */ static List<String> extractCommands(SupportSQLiteDatabase database, InputStream inputStream) { final List<String> result = new ArrayList<>(); final String input = IOUtils.readText(inputStream); JqlLexer lexer = new JqlLexer(CharStreams.fromString(input)); CommonTokenStream tokens = new CommonTokenStream(lexer); JqlParser parser = new JqlParser(tokens); ParserRuleContext parseContext = parser.parse(); ParseTreeWalker walk = new ParseTreeWalker(); walk.walk(new JqlBaseListener() { @Override public void enterSql_stmt(Sql_stmtContext ctx) { int start = ctx.getStart().getStartIndex(); int stop = ctx.getStop().getStopIndex() + 1; if (start == stop) return; result.add(input.substring(start, stop)); } }, parseContext); return result; } /** * Verify schema. * * @param <H> * the generic type * @param dataSource * the data source * @param context * the context * @param rawId * the raw id */ public static <H extends AbstractDataSource> void verifySchema(H dataSource, Context context, int rawId) { verifySchema(dataSource.openWritableDatabase(), context, rawId); } public static <H extends AbstractDataSource> void showSchema(H dataSource) { boolean needToBeOpened = !dataSource.isOpen(); SupportSQLiteDatabase database=null; if (needToBeOpened) { database = dataSource.openReadOnlyDatabase(); } List<String> actualSql = new ArrayList<String>(); actualSql.addAll(SQLiteTestUtils.getAllTables(database).values()); actualSql.addAll(SQLiteTestUtils.getAllIndexes(database).values()); Logger.info("Database schema version %s", database.getVersion()); for (String item : actualSql) { Logger.info("DDL: %s", item); } if (database!=null && needToBeOpened) { try { database.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Verify schema internal. * * @param database * the database * @param expectedSQL * the expected SQL */ static void verifySchemaInternal(SupportSQLiteDatabase database, List<String> expectedSQL) { Set<String> actualSql = new HashSet<String>(); actualSql.addAll(SQLiteTestUtils.getAllTables(database).values()); actualSql.addAll(SQLiteTestUtils.getAllIndexes(database).values()); Logger.info("Database schema version %s", database.getVersion()); if (actualSql.size() != expectedSQL.size()) { Logger.error( "Database schema comparison result: ERROR - Number of tables and indexes between aspected and actual schemas are different"); for (String item1 : actualSql) { Logger.info("actual: " + item1); } for (String item1 : expectedSQL) { Logger.info("expected: " + item1); } throw new KriptonRuntimeException( "Number of tables and indexes between aspected and actual schemas are different"); } for (String item : expectedSQL) { if (!actualSql.contains(item)) { Logger.error("Database schema comparison result: ERROR - Actual and expected schemas are NOT the same"); for (String item1 : actualSql) { Logger.info("actual: " + item1); } for (String item1 : expectedSQL) { Logger.info("expected: " + item1); } throw new KriptonRuntimeException("not found element: " + item); } } Logger.info("Database schema comparison result: OK - Actual and expected schemas are the same!"); try { database.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Force a schema update for a datasource. Note that no DDL was execute * untill the database was opened. * * @param <H> * the element type * @param dataSource * the data source * @param version * to upgrade. */ public static <H extends AbstractDataSource> void forceDataSourceSchemaUpdate(H dataSource, int version) { dataSource.forceClose(); dataSource.version = version; dataSource.database = null; dataSource.sqliteHelper = null; dataSource.openWritableDatabase(); } /** * Clear datasource. * * @param <H> * the element type * @param dataSource * the data source */ public static <H extends AbstractDataSource> void clearDataSource(H dataSource) { if (dataSource.options.inMemory) { dataSource.close(); return; } dataSource.openWritableDatabase(); File file = new File(dataSource.database.getPath(), dataSource.name); dataSource.forceClose(); Logger.info("Clear database file %s", file.getAbsolutePath()); if (!file.delete()) { Logger.warn("Can not delete database " + file.getAbsolutePath()); } } public static void dropIndex(SupportSQLiteDatabase database, String... indexNames) { for (String indexName : indexNames) { drop(database, QueryType.INDEX, indexName); } } }
true
6b880bf02b3fa266daf02385512949996e04b85f
Java
kashyapchhabria/xoportal
/xo_reporting_portal/app/com/xo/web/ext/tableau/models/TableauWorkbook.java
UTF-8
3,363
2.171875
2
[ "Apache-2.0" ]
permissive
package com.xo.web.ext.tableau.models; // Generated 27-Oct-2014 07:17:17 by Hibernate Tools 4.3.1 import java.util.HashSet; import java.util.Set; import com.xo.web.models.system.AbstractEntity; import com.xo.web.viewdtos.KeyValueDTO; /** * TableauWorkbook generated by hbm2java */ @SuppressWarnings("serial") public class TableauWorkbook extends AbstractEntity { private String tableauWorkbookId; private TableauProject tableauProject; private String name; private String description; private Set<TableauView> tableauViews = new HashSet<TableauView>(0); public TableauWorkbook() { } public TableauWorkbook(String id,TableauProject tableauProject, boolean active) { this.tableauWorkbookId = id; this.tableauProject = tableauProject; this.active = active; } public TableauWorkbook(String id,TableauProject tableauProject, String name, String description, boolean active, Set<TableauView> tableauViewses) { this.tableauWorkbookId = id; this.tableauProject = tableauProject; this.name = name; this.description = description; this.active = active; this.tableauViews = tableauViewses; } public TableauWorkbook(WorkBook workBook) { this.tableauWorkbookId = workBook.id; this.name = workBook.name; this.displayName = workBook.name; this.description = workBook.description; } public String getTableauWorkbookId() { return this.tableauWorkbookId; } public void setTableauWorkbookId(String id) { this.tableauWorkbookId = id; } public TableauProject getTableauProject() { return this.tableauProject; } public void setTableauProject(TableauProject tableauProject) { this.tableauProject = tableauProject; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public Set<TableauView> getTableauViews() { return this.tableauViews; } public void setTableauViews(Set<TableauView> tableauViewses) { this.tableauViews = tableauViewses; } @Override public int hashCode() { int hash = 0; hash += (tableauWorkbookId != null ? tableauWorkbookId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the tableauWorkbookId fields are not set if (!(object instanceof TableauWorkbook)) { return false; } TableauWorkbook other = (TableauWorkbook) object; if ((this.tableauWorkbookId == null && other.tableauWorkbookId != null) || (this.tableauWorkbookId != null && !this.tableauWorkbookId.equals(other.tableauWorkbookId))) { return false; } return true; } public String toString() { return this.name; } public KeyValueDTO asKeyValue() { return new KeyValueDTO(this.tableauWorkbookId, this.name); } public String getDisplayName() { return this.displayName != null ? this.displayName : this.name; } }
true
b844d1689c09de22130025b4611fa700c3493737
Java
DeependraKhandelwal/Photo
/Photo-Walls/OnlinePhotoShoping/src/main/java/com/ops/in/service/impl/IPaymentServiceImpl.java
UTF-8
3,353
2.28125
2
[]
no_license
package com.ops.in.service.impl; import java.util.List; import java.util.Map; import java.util.Optional; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ops.in.entitie.Cart; import com.ops.in.entitie.Payment; import com.ops.in.entitie.Product; import com.ops.in.entitie.ShippingInfo; import com.ops.in.exception.CartNotFoundException; import com.ops.in.exception.OrderDetailsException; import com.ops.in.exception.OrderDetailsNotFoundException; import com.ops.in.pojo.CartInfo; import com.ops.in.pojo.ProductItem; import com.ops.in.repository.ICartRepository; import com.ops.in.repository.IOrderDetailsRepository; import com.ops.in.repository.IShippingInfoRepository; import com.ops.in.service.IPaymentService; @Service public class IPaymentServiceImpl implements IPaymentService { private static final Logger Logger =LoggerFactory.getLogger(IPaymentServiceImpl.class); @Autowired private IOrderDetailsRepository orderdetailRepository; @Autowired ICartRepository cartRepo; @Autowired IShippingInfoRepository shippingInfoRepo; @Override public Payment saveOrderDetails(Integer cartId)throws OrderDetailsException { Logger.info("Cart viewAllProducts()"); Cart cart = cartRepo.findById(cartId).orElse(null); if(cart==null) { throw new CartNotFoundException(); } else { CartInfo cartinfo=new CartInfo(); Map<Product, Integer> map=cart.getProducts(); Double total =map.entrySet().stream().mapToDouble(p->p.getKey().getPrice()*p.getValue()).sum(); System.out.println(total); /* * for(Product p:map.keySet()) { * * ProductItem item=new ProductItem(); item.setProductId(p.getProductId()); * item.setProductName(p.getProductName()); * item.setProductImage(p.getProductImage()); item.setPrice(p.getPrice()); * item.setQuantity(map.get(p)); cartinfo.getProductList().add(item); * cartinfo.setTotal(total); } */ Payment payment=new Payment(); payment.setSubTotal(total); // payment.setShippingInfo(shippingInfoRepo.getById(d)); return orderdetailRepository.save(payment); } } @Override public List<Payment> getOrderDetailsList()throws OrderDetailsException{ Logger.info("Trying to fetch all OrderDetails in service layer "); return orderdetailRepository.findAll(); } @Override public Optional<Payment> getOrderDetailsById(Integer orderDetailsId) throws OrderDetailsException{ Logger.info("Trying to fetch OrderDetails in service layer "); return orderdetailRepository.findById(orderDetailsId); } @Override public Payment updateOrderDetails(Payment orderdeatails)throws OrderDetailsException { Logger.info("Trying to update OrderDetails in service layer "); Integer orderDetailsId=orderdeatails.getPaymentId(); orderdeatails.setPaymentId(orderDetailsId); return orderdetailRepository.save(orderdeatails); } @Override public void deleteOrderDetails(Integer orderDetailsId) throws OrderDetailsException{ Logger.info("Trying to delete OrderDetails in service layer"); orderdetailRepository.deleteById(orderDetailsId); } }
true
2447dbfee0e13d254864d0cfaf987441f40fc272
Java
tomas-93/SpringBook
/Spring-Forms/src/main/java/com/tomas/spring/config/ServletContextConfiguration.java
UTF-8
5,776
2.203125
2
[ "Apache-2.0" ]
permissive
package com.tomas.spring.config; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; import org.springframework.stereotype.Controller; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.RequestToViewNameTranslator; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import javax.inject.Inject; import java.util.Arrays; import java.util.List; @Configuration @EnableWebMvc @ComponentScan( basePackages = "com.tomas.spring", useDefaultFilters = false, includeFilters = @ComponentScan.Filter(Controller.class) ) public class ServletContextConfiguration extends WebMvcConfigurerAdapter { @Inject ObjectMapper objectMapper; @Inject Marshaller marshaller; @Inject Unmarshaller unmarshaller; @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) { //Uso de bytges Http headers converters.add(new ByteArrayHttpMessageConverter()); //uso de string o text/plan en httpmessage converters.add(new StringHttpMessageConverter()); //Uso multipart para el envio y carga de archivos del formulario converters.add(new FormHttpMessageConverter()); //Lectura y escritura de objetos Sources converters.add(new SourceHttpMessageConverter<>()); //Lectura y escritura de XML uso de sprgin MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter(); xmlConverter.setSupportedMediaTypes(Arrays.asList( new MediaType("application", "xml"), new MediaType("text", "xml") )); xmlConverter.setMarshaller(this.marshaller); xmlConverter.setUnmarshaller(this.unmarshaller); converters.add(xmlConverter); //Para la lectura y escritura de JSON con el uso de JACKSON MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setSupportedMediaTypes(Arrays.asList( new MediaType("application", "json"), new MediaType("text", "json") )); jsonConverter.setObjectMapper(this.objectMapper); converters.add(jsonConverter); } @Override public void configureContentNegotiation( ContentNegotiationConfigurer configurer) { //Configuracion los tipo de peticiones, ya sea por xml o json configurer.favorPathExtension(true).favorParameter(false) .parameterName("mediaType").ignoreAcceptHeader(false) .useJaf(false).defaultContentType(MediaType.APPLICATION_XML) .mediaType("xml", MediaType.APPLICATION_XML) .mediaType("json", MediaType.APPLICATION_JSON); } @Bean public ViewResolver viewResolver() { //Configuracion de donde se encuentran los archivos estaticos. y el uso forwards //del modelo hacia la vista InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/jsp/view/"); resolver.setSuffix(".jsp"); return resolver; } /* View name translator ayuda en la simplificacion de la URL en el request al -> nobre de la vita http://localhost:8080/gamecast/display.html » display http://localhost:8080/gamecast/displayShoppingCart.html » displayShoppingCart http://localhost:8080/gamecast/admin/index.html » admin/index */ @Bean public RequestToViewNameTranslator viewNameTranslator() { return new DefaultRequestToViewNameTranslator(); } /* Una interfaz de estrategia para la resolución de carga de archivos de varias partes de conformidad con el RFC 1867 . Implementaciones son típicamente utilizable tanto dentro de un contexto de aplicación y autónomo. Hay dos implementaciones concretas incluidas en la primavera, a partir de la primavera 3,1: *CommonsMultipartResolver para Apache Commons FileUpload *StandardServletMultipartResolver para el Servlet API 3.0 + Parte */ @Bean public MultipartResolver multipartResolver() { return new StandardServletMultipartResolver(); } }
true
19729fd14dac88a5fcf8d3f9995efc6f2954f386
Java
ardhi95/MovieStation
/app/src/main/java/com/example/nabella/moviestation/activity/ticket/Jadwal_FilmActivity.java
UTF-8
5,312
2.109375
2
[]
no_license
package com.example.nabella.moviestation.activity.ticket; import android.content.Intent; import android.content.res.Resources; import android.graphics.Rect; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import com.example.nabella.moviestation.R; import com.example.nabella.moviestation.activity.adapter.JadwalAdapter; import com.example.nabella.moviestation.entities.Jadwal; import com.example.nabella.moviestation.lib.FormData; import com.example.nabella.moviestation.lib.InternetTask; import com.example.nabella.moviestation.lib.OnInternetTaskFinishedListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Jadwal_FilmActivity extends AppCompatActivity { private RecyclerView recyclerView; private JadwalAdapter adapter; private List<Jadwal> jadwalList; public String txt_idb, txt_idm, jNama; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jadwal__film); Toolbar act = (Toolbar) findViewById(R.id.toolBarS); act.setTitle("Jam Tayang"); Intent i = getIntent(); txt_idb = i.getStringExtra("id_bioskop"); txt_idm = i.getStringExtra("id_movie"); jNama = i.getStringExtra("nama"); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); jadwalList = new ArrayList<>(); adapter = new JadwalAdapter(this, jadwalList); RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new Jadwal_FilmActivity.GridSpacingItemDecoration(2, dpToPx(10), true)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); getJadwal(); } private int dpToPx(int dp) { Resources r = getResources(); return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics())); } public void getJadwal(){ FormData data = new FormData(); data.add("method", "getJadwalMovie"); data.add("id_bioskop", txt_idb.toString()); data.add("id_movie", txt_idm.toString()); InternetTask uploadTask = new InternetTask("Movie", data); uploadTask.setOnInternetTaskFinishedListener(new OnInternetTaskFinishedListener() { @Override public void OnInternetTaskFinished(InternetTask internetTask) { try { JSONObject jsonObject = new JSONObject(internetTask.getResponseString()); if (jsonObject.get("code").equals(200)){ JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length();i++){ jadwalList.add(new Jadwal(jsonArray.getJSONObject(i))); adapter.notifyDataSetChanged(); } //Toast.makeText(getContext(),jsonArray.toString(),Toast.LENGTH_SHORT).show(); }else{ } } catch (JSONException e) { } } @Override public void OnInternetTaskFailed(InternetTask internetTask) { } }); uploadTask.execute(); } public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration { private int spanCount; private int spacing; private boolean includeEdge; public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) { this.spanCount = spanCount; this.spacing = spacing; this.includeEdge = includeEdge; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); // item position int column = position % spanCount; // item column if (includeEdge) { outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing) outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing) if (position < spanCount) { // top edge outRect.top = spacing; } outRect.bottom = spacing; // item bottom } else { outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing) outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing) if (position >= spanCount) { outRect.top = spacing; // item top } } } } }
true
7afcac7612225c6d1a93418f9c2957e54839f0a4
Java
287357040/jim-framework
/modules/core/src/main/java/com/jim/framework/core/apollo/ApolloConfigurationHighestPriorityBeanProcesser.java
UTF-8
2,351
2.1875
2
[ "Apache-2.0" ]
permissive
package com.jim.framework.core.apollo; import com.ctrip.framework.apollo.core.spi.Ordered; import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.EnvironmentAware; import org.springframework.core.PriorityOrdered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.stereotype.Component; import java.util.Iterator; /** * Created by celiang.hu on 2018-11-24. */ @Component public class ApolloConfigurationHighestPriorityBeanProcesser implements BeanFactoryPostProcessor, EnvironmentAware, PriorityOrdered { private ConfigurableEnvironment environment = null; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { MutablePropertySources propertySources = environment.getPropertySources(); for (Iterator<PropertySource<?>> iterator = propertySources.iterator(); iterator.hasNext();) { PropertySource<?> next = iterator.next(); if (next.getName().equals(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) { propertySources.remove(next.getName()); propertySources.addFirst(next); } if (next.getName().equals(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) { propertySources.remove(next.getName()); if(propertySources.contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)){ propertySources.addAfter(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, next); }else{ propertySources.addFirst(next); } } } } @Override public void setEnvironment(Environment environment) { this.environment = (ConfigurableEnvironment) environment; } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1; } }
true
84301d5ed1f33d3eb29883a93b9f13f5cdc09eef
Java
PatricioAvalos/Taller-3
/Taller3/src/Taller3/Main.java
UTF-8
2,064
3.40625
3
[]
no_license
package Taller3; // Importacion de librerias import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ucn.StdOut; public class Main { public static void main(String[] args) throws IOException { App app = new App(); app.leerPersonas(); app.leerCreditos(); BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StdOut.println(" Taller 3: Banco"); StdOut.println(" (1) - RF1: Despliegue de todas las personas registradas. "); StdOut.println(" (2) - RF2: Despliegue de datos de una persona. " ); StdOut.println(" (3) - RF3: Despligue de datos y estado de un credito. " ); StdOut.println(" (4) - RF4: Eliminacion de una persona del registro. " ); StdOut.println(" (5) - RF5: Eliminacion de un credito. " ); StdOut.println(" (6) - RF6: Ingresar un nuevo credito. " ); StdOut.println(" (7) - RF7: Ingresar un nuevo cliente. " ); StdOut.println(" (8) - Salir. " ); int op; do{ StdOut.println("\nIngrese una opción del menú: " ); op = Integer.parseInt(bf.readLine()); switch(op){ case 1: app.RF1(); break; case 2: app.RF2(); break; case 3: app.RF3(); break; case 4: app.RF4(); break; case 5: app.RF5(); break; case 6: app.RF6(); break; case 7: app.RF7(); break; case 8: default: StdOut.println("\nUsted está saliendo del menú..." ); break; } }while( op != 8 ); } }
true
b6a2eb24e7993622362c2dcafc9825d46f3ef1d4
Java
hieubagiang/KIT_java04
/src/Buoi10/Bai2/Stack.java
UTF-8
1,825
3.65625
4
[]
no_license
package Buoi10.Bai2; import java.util.Scanner; public class Stack { private Node top; private int size=0; void push(int data) { size++; Node p = new Node(); // khởi tạo và cấp phát 1 node p.setItem(data); // gán giá trị cho node if(size==0) // stack rỗng { top = p; } else { p.setNext(this.top); this.top=p; } } //• pop( ): nếu ngăn xếp không rỗng, lấy phần tử trên đỉnh ngăn xếp ra khỏi ngăn xếp, // trả về giá trị của phần tử đó; nếu ngăn xếp rỗng, trả về giá trị -1. int pop() { if(size>0) { int data = top.item; // Node tmp = top; top=top.next; tmp=null; //set gia tri rong System.gc(); size--; return data; } return -1; } //isEmpty( ): trả về giá trị true nếu ngăn xếp rỗng, ngược lại trả về false. boolean isEmpty() { return size==0 ? true : false; } public int numOfElement() { return size; } public int search() { int vitri=size-1; Scanner scanner = new Scanner(System.in); System.out.println("Nhap so nguyen can tim: "); int key = scanner.nextInt(); for(Node i = top; i!=null; i= i.next) { vitri--; if(key== i.item) { return vitri; } } return 0; } //display( ): in ra danh sách các phần tử hiện có trong ngăn xếp. void display() { //duyet while (numOfElement()>0) { System.out.println(pop() +" "); } } }
true
93446991289fddf7abb04c95194c863ba4c552d0
Java
Julie0u812/OOP-2015
/Students/Others/Marton Imola/src/MainWindow.java
UTF-8
6,473
2.65625
3
[]
no_license
import java.awt.Component; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; public class MainWindow extends JFrame implements GameStateManipulator{ JPanel lifePanel=new JPanel(); JPanel columnRulePanel=new JPanel(); JPanel rowRulePanel=new JPanel(); JPanel tablePanel=new JPanel(); int life; JLabel lifeLabel=new JLabel("life",SwingConstants.CENTER); Table table; static int SQUARE_SIZE = 50; static int RULES_SIZE = 90; public void setLevel(String title, Table table) { this.table=table; this.setTitle(title); rowRulePanel.removeAll(); columnRulePanel.removeAll(); tablePanel.removeAll(); //GridLayout windowLayout=new GridLayout(2, 2); //this.setLayout(windowLayout); life=table.getNumberOfColumns()*table.getNumberOfRows(); updateLifeLabel(); GridLayout rowRulePanelLayout=new GridLayout(table.getNumberOfRows(),1); rowRulePanel.setLayout(rowRulePanelLayout); for(int row=0; row<table.getNumberOfRows(); row++) { rowRulePanel.add(new JLabel(table.getRowRule(row),SwingConstants.CENTER)); } GridLayout columnRulePanelLayout=new GridLayout(1, table.getNumberOfColumns()); columnRulePanel.setLayout(columnRulePanelLayout); for(int column=0; column<table.getNumberOfColumns(); column++) { columnRulePanel.add(new JLabel(table.getColumnRule(column),SwingConstants.CENTER)); } GridLayout grid=new GridLayout(table.getNumberOfRows(), table.getNumberOfColumns()); tablePanel.setLayout(grid); for(int row=0; row<table.getNumberOfRows(); row++) for(int column=0; column<table.getNumberOfColumns(); column++) { Square square =table.getSquare(column, row); SquareJButton buton=new SquareJButton(square); square.setLife(this); tablePanel.add(buton); } this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); //do layout int layoutTableWidth=SQUARE_SIZE*table.getNumberOfColumns(); int layoutTableHeight=SQUARE_SIZE*table.getNumberOfRows(); this.setSize(RULES_SIZE*2+layoutTableWidth, RULES_SIZE*2+layoutTableHeight); lifePanel.setBounds(0, 0, RULES_SIZE, RULES_SIZE); columnRulePanel.setBounds(RULES_SIZE, 0, layoutTableWidth, RULES_SIZE); rowRulePanel.setBounds(0, RULES_SIZE, RULES_SIZE, layoutTableHeight); tablePanel.setBounds(RULES_SIZE, RULES_SIZE, layoutTableWidth, layoutTableHeight); // TODO Auto-generated constructor stub } public MainWindow(Table table) throws HeadlessException { this.setLayout(null); this.add(lifePanel); this.add(columnRulePanel); this.add(rowRulePanel); this.add(tablePanel); this.setJMenuBar(createMenuBar()); GridLayout lifePanelLayout=new GridLayout(1, 1); lifePanel.setLayout(lifePanelLayout); lifePanel.add(lifeLabel); this.setLevel(Levels.LevelData[0].levelName, table); } private JMenuBar createMenuBar() { JMenuBar menuBar=new JMenuBar(); JMenu menu=new JMenu("Levels"); menuBar.add(menu); Level level = Levels.LevelData[0]; JMenuItem menuItem=new JMenuItem(level.levelName); menu.add(menuItem); menuItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Level level = Levels.LevelData[0]; Table table = TableCreator.CreateFromString(level.rows, level.columns, level.levelSource); MainWindow.this.setLevel(level.levelName, table); } }); level = Levels.LevelData[1]; menuItem=new JMenuItem(level.levelName); menu.add(menuItem); menuItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Level level = Levels.LevelData[1]; Table table = TableCreator.CreateFromString(level.rows, level.columns, level.levelSource); MainWindow.this.setLevel(level.levelName, table); } }); level = Levels.LevelData[2]; menuItem=new JMenuItem(level.levelName); menu.add(menuItem); menuItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Level level = Levels.LevelData[2]; Table table = TableCreator.CreateFromString(level.rows, level.columns, level.levelSource); MainWindow.this.setLevel(level.levelName, table); } }); level = Levels.LevelData[3]; menuItem=new JMenuItem(level.levelName); menu.add(menuItem); menuItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub Level level = Levels.LevelData[3]; Table table = TableCreator.CreateFromString(level.rows, level.columns, level.levelSource); MainWindow.this.setLevel(level.levelName, table); } }); return menuBar; } private void updateLifeLabel() { // TODO Auto-generated method stub lifeLabel.setText("Life: "+life); } @Override public void decrementLife(int amount) { // TODO Auto-generated method stub life-=amount; updateLifeLabel(); } @Override public int getCurrentLife() { // TODO Auto-generated method stub return life; } public boolean hasWon(){ int countGoal=0, countSuccess=0; for(int row=0; row<table.getNumberOfRows(); row++) for(int column=0; column<table.getNumberOfColumns(); column++) { Square square =table.getSquare(column, row); if(square.isGoal()) { countGoal++; } if(square.isSuccess()) { countSuccess++; } } if(countGoal==countSuccess) return true; else return false; } public boolean hasLost() { if(life<=0) return true; else return false; } @Override public void userActionPerformed() { // TODO Auto-generated method stub if(hasLost()) { disableInputs(); JOptionPane.showMessageDialog(this, "YOU FAILED!"); } else if(hasWon()) { disableInputs(); JOptionPane.showMessageDialog(this, "CONGRAAAAAAAAATS!!! :)"); } } private void disableInputs() { // TODO Auto-generated method stub Component[] components=tablePanel.getComponents(); for(int i=0; i<components.length; i++) { components[i].setEnabled(false); } } }
true
49987fe547bdd81224868c8fc13960b48d06dbb0
Java
olszewskimichal/sda-jpa
/src/main/java/pl/michal/olszewski/materialy/OneToOne/bidirectional/PostDetailsBidirectional.java
UTF-8
1,043
2.4375
2
[]
no_license
package pl.michal.olszewski.materialy.OneToOne.bidirectional; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity public class PostDetailsBidirectional { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String content; @OneToOne(mappedBy = "details", fetch = FetchType.LAZY) private PostBidirectional postBidirectional; public PostDetailsBidirectional() { } public PostDetailsBidirectional(String content) { this.content = content; } public PostBidirectional getPostBidirectional() { return postBidirectional; } public void setPostBidirectional(PostBidirectional postBidirectional) { this.postBidirectional = postBidirectional; } @Override public String toString() { return "PostDetailsBidirectional{" + "id=" + id + ", content='" + content + '\'' + '}'; } }
true
df21544dea1f67ee3a4e63c9ce1d1b727f2bba16
Java
rfc8169/SoccerTournament
/Soccer/src/States/User/FindGame.java
UTF-8
3,262
2.609375
3
[]
no_license
package States.User; import States.Role; import States.SQLstateInfo; import States.StateType; import javax.xml.transform.Result; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; public class FindGame extends States.State { StringBuilder pathAppend = new StringBuilder("FindGame/"); Scanner scanner = new Scanner(System.in); Statement statement; public FindGame(Role role, Connection connection, SQLstateInfo selectedInfo) { super(role, connection, selectedInfo); } @Override public StateType exec(StringBuilder modifiableData) { String input; modifiableData.append(pathAppend); try{ statement = connection.createStatement(); String sql = "SELECT CONCAT('Game ID: ',GAME_ID,', Location: ', LOCATION,', ', HOME_TEAM,' vs. '," + " AWAY_TEAM, ' Tournament: ', TOURNAMENT) FROM GAME WHERE TOURNAMENT = '"+selectedInfo.getTournament()+"'"; ResultSet rs = statement.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)); } statement.close(); } catch(Exception e){ e.printStackTrace(); } while (true) { System.out.println("\n"+modifiableData); help(); System.out.print("Select Game ID: "); input = scanner.nextLine(); if (input.equals("/b")) return null; else if(input.equals("/e"))return StateType.END; else{ try{ statement = connection.createStatement(); String sql = "SELECT "+input+" IN (SELECT Game_ID FROM Game)"; ResultSet rs = statement.executeQuery(sql); rs.next(); if(rs.getString(1).equals("TRUE")){ selectedInfo.setGame(input); input = "<"+input+">/"; pathAppend.append(input); modifiableData.append(input); return StateType.SELECTEDGAME; } } catch (SQLException e){ int errorInt = e.getErrorCode(); if(errorInt == 90039 || errorInt == 90067 || errorInt == 90098) { System.out.println("Your connection to our database has been close, please restart the program."); return StateType.END; }else{ System.out.println("Invalid input, try again"); continue; } } catch(Exception e){ System.out.println("Invalid input, try again"); continue; } } } } @Override public void undoDataWrite(StringBuilder modifiableData) { modifiableData.reverse().delete(0, pathAppend.length()).reverse(); pathAppend = new StringBuilder("FindGame/"); } @Override public void help() { System.out.println("use '/e' to end or '/b' to go back"); } }
true
a23aa518dcafcf2bc0fd2bf5a8c05792897cce47
Java
DSpace-Labs/dspace-sandbox
/prototypes/hibernate-prototype/trunk/dspace-api/src/main/java/org/dspace/workflow/dao/jpa/WorkflowItemDAOJPA.java
UTF-8
3,073
2.015625
2
[]
no_license
package org.dspace.workflow.dao.jpa; import java.util.List; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.Query; import org.dspace.content.Collection; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.workflow.TaskListItem; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.dao.WorkflowItemDAO; public class WorkflowItemDAOJPA extends WorkflowItemDAO { public List<TaskListItem> findTaskListItemByWorkflowId(int workflowId, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT tli FROM TaskListItem tli WHERE tli.workflowItem.id = :workflowId"); q.setParameter("workflowId", workflowId); List<TaskListItem> tli = q.getResultList(); return tli; } public List<WorkflowItem> findWorkflowItemByCollection(Collection collection, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT wi FROM WorkflowItem wi WHERE wi.collection = :collection"); q.setParameter("collection", collection); List<WorkflowItem> wis = q.getResultList(); return wis; } public List<WorkflowItem> findWorkflowItemsByOwner(EPerson eperson, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT wi FROM WorkflowItem wi WHERE wi.owner = :eperson GROUP BY wi.id"); List<WorkflowItem> wis = q.getResultList(); return wis; } public List<WorkflowItem> findWorkflowItemsBySubmitter(EPerson eperson, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT wi FROM WorkflowItem wi WHERE wi.item.submitter = :eperson ORDER BY wi.id"); List<WorkflowItem> wis = q.getResultList(); return wis; } public List<WorkflowItem> findAllWorkflowItem(Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT wi FROM WorkspaceItem wi ORDER BY wi.id"); List<WorkflowItem> wis = q.getResultList(); return wis; } public List<TaskListItem> findTaskListItemByEPerson(EPerson eperson, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT tli FROM TaskListItem tli " + "WHERE tli.eperson = :eperson AND tli.iD = tli.workflowitem.id"); q.setParameter("eperson", eperson); List<TaskListItem> tlis = q.getResultList(); return tlis; } public WorkflowItem getWorkflowItemByUUID(UUID uuid, Context context) { EntityManager em = context.getEntityManager(); Query q = em.createQuery("SELECT w FROM WorkflowItem w WHERE w.uuid = :uuid"); q.setParameter("uuid", uuid); WorkflowItem workflowItem = (WorkflowItem)q.getSingleResult(); return workflowItem; } }
true
3f91736518fe8877f515a5237b4c3ce047321f47
Java
janesch97/UDP_Example
/src/UDPServ.java
UTF-8
1,165
2.9375
3
[]
no_license
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * Created by tomek on 16.10.2017.. */ public class UDPServ { public static void main(String []agrs) throws Exception{ UDPServ udpServ = new UDPServ(); udpServ.run(); } public void run() throws Exception{ DatagramSocket serverSocket = new DatagramSocket(5001); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true){ DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String message = new String(receivePacket.getData()); System.out.println("From client: "+message); InetAddress IPAddr = receivePacket.getAddress(); int port = receivePacket.getPort(); String modifiedMessage = message.toUpperCase(); sendData = modifiedMessage.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddr, port); serverSocket.send(sendPacket); } } }
true
92ebf23f56ed2cb389075c208be98bdbbc61d43f
Java
matana/java
/BinaryTree/src/de/uni_koeln/info/java/binarytree/BTreeNode.java
UTF-8
253
2.75
3
[]
no_license
package de.uni_koeln.info.java.binarytree; public class BTreeNode { BTreeNode left; BTreeNode right; int value; public BTreeNode(int value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } }
true
920bc61a8b999d713235eae09ce4709dd991a9d3
Java
tauren44/multithreadingHW
/src/multithreading/synchronizers/cyclicbarrier/CyclicBarrierTestApp.java
UTF-8
447
2.8125
3
[]
no_license
package multithreading.synchronizers.cyclicbarrier; import multithreading.utility.ThreadSleep; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierTestApp { public static final CyclicBarrier BARRIER = new CyclicBarrier(2, new FerryBoat()); public static void main(String[] args) { for (int i = 0; i < 10; i++) { new Thread(new Car(i)).start(); ThreadSleep.sleep(500); } } }
true
3d87013c0083bce7fe7f86524c313035da990a0e
Java
cjswn10/Spring
/diTest12/src/com/bit/exam05/SystemConfig.java
UTF-8
389
2.0625
2
[]
no_license
package com.bit.exam05; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SystemConfig { @Bean(autowire=Autowire.BY_TYPE) public SystemMonitor sm() { SystemMonitor s = new SystemMonitor(); s.setPeriodTime(10); return s; } }
true
e44c30217cbda40ee9575122635fb477c857464a
Java
AdenilsonVergutz/ProjetoGestao
/src/controladores/Espacos.java
UTF-8
493
2.265625
2
[]
no_license
package controladores; import java.util.ArrayList; public class Espacos { private String NomeEspaco; private int LotacaoEspaco; public static ArrayList<Espacos> dados = new ArrayList<>(); public String getNomeEspaco() { return NomeEspaco; } public void setNomeEspaco(String NomeEspaco) { this.NomeEspaco = NomeEspaco; } public int getLotacaoEspaco() { return LotacaoEspaco; } public void setLotacaoEspaco(int LotacaoEspaco) { this.LotacaoEspaco = LotacaoEspaco; } }
true
1e7e629fe12efa29ba9f2594976a4ddf55e5f991
Java
Tuvshintur/CS544_project
/TMinstructorMS/src/main/java/com/edu/miu/cs544/tminstructor/service/TmInstructorService.java
UTF-8
525
2.09375
2
[]
no_license
package com.edu.miu.cs544.tminstructor.service; import com.edu.miu.cs544.tminstructor.dto.ResponseDTO; import com.edu.miu.cs544.tminstructor.model.TmInstructor; public interface TmInstructorService { ResponseDTO getAllTmInstructors(); ResponseDTO getTmInstructorById(int id); TmInstructor getTmInstructorByIdReturnTmInstructor(int id); ResponseDTO addTmInstructor(TmInstructor tmInstructor); ResponseDTO updateTmInstrcutor(TmInstructor tmInstructor); ResponseDTO deleteTmInstructorById(int id); }
true
5428f730f631af6e7de26d03b788a5b6b8a7949f
Java
lectoforward/forward_final
/FinalWebProject/src/main/java/com/lecto/forward/vo/ManagerVO.java
UTF-8
1,518
2.359375
2
[]
no_license
package com.lecto.forward.vo; public class ManagerVO { private String memberId; private String memberName; private String memberPhone; private String boardName; private String boardCode; public ManagerVO() { super(); // TODO Auto-generated constructor stub } public ManagerVO(String memberId, String memberName, String memberPhone, String boardName, String boardCode) { super(); this.memberId = memberId; this.memberName = memberName; this.memberPhone = memberPhone; this.boardName = boardName; this.boardCode = boardCode; } public String getMemberId() { return memberId; } public String getMemberName() { return memberName; } public String getMemberPhone() { return memberPhone; } public String getBoardName() { return boardName; } public void setMemberId(String memberId) { this.memberId = memberId; } public void setMemberName(String memberName) { this.memberName = memberName; } public void setMemberPhone(String memberPhone) { this.memberPhone = memberPhone; } public void setBoardName(String boardName) { this.boardName = boardName; } public String getBoardCode() { return boardCode; } public void setBoardCode(String boardCode) { this.boardCode = boardCode; } @Override public String toString() { return "ManagerVO [memberId=" + memberId + ", memberName=" + memberName + ", memberPhone=" + memberPhone + ", boardName=" + boardName + ", boardCode=" + boardCode + "]"; } }
true
ce413025b7b65eeb61ce02cd1a56512c0c22bc99
Java
playa92/PileOfBalls
/src/graphic/SoundsProvider.java
UTF-8
2,047
2.75
3
[]
no_license
package graphic; import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; public class SoundsProvider { private static AudioInputStream audio; private static File paused; private static Clip pausedClip; private static File play; private static Clip playClip; private static File ball; public static Clip ballClip; private static File explosion; public static Clip explosionClip; private static File drop; public static Clip dropClip; static { paused = new File("sounds/pause.wav"); play = new File("sounds/play.wav"); drop = new File("sounds/drop.wav"); ball = new File("sounds/ball.wav"); explosion = new File("sounds/explosion.wav"); } static { try { audio = AudioSystem.getAudioInputStream(paused); pausedClip = AudioSystem.getClip(); pausedClip.open(audio); audio = AudioSystem.getAudioInputStream(play); playClip = AudioSystem.getClip(); playClip.open(audio); audio = AudioSystem.getAudioInputStream(ball); ballClip = AudioSystem.getClip(); ballClip.open(audio); audio = AudioSystem.getAudioInputStream(drop); dropClip = AudioSystem.getClip(); dropClip.open(audio); audio = AudioSystem.getAudioInputStream(explosion); explosionClip = AudioSystem.getClip(); explosionClip.open(audio); } catch(Exception e) { e.printStackTrace(); } } public static void playPaused() { pausedClip.setFramePosition(0); pausedClip.start(); } public static void playMusic() { playClip.start(); playClip.loop(Clip.LOOP_CONTINUOUSLY); } public static void playBall() { if(ballClip.getFramePosition() == 0){ ballClip.setFramePosition(0); ballClip.start(); } } public static void playDrop() { dropClip.setFramePosition(0); dropClip.start(); } public static void playExplosion() { explosionClip.setFramePosition(0); explosionClip.start(); } }
true
9658351a8df87784a703c9de798d615179254ff5
Java
inabaakira/book_Head_First_Design_Patterns
/ch03/Beverage.java
UTF-8
539
2.78125
3
[]
no_license
// -*- mode: java; coding: utf-8 -*- // file: Beverage.java // Created: <2019/10/28 12:33:01> // Last Modified: <2019/11/20 10:18:33> public abstract class Beverage { public enum Size {TALL, GRANDE, VENTI}; Size size = Size.TALL; String description = "Unknown Beverage"; public String getDescription() { return description; } public void setSize(Size size) { this.size = size; } public Size getSize() { return this.size; } public abstract double cost(); }
true
d6ed3fd149240e9ff78f8fce3ea57413583b0e0d
Java
qiujun4417/diamond
/diamond-core/src/main/java/com/wonders/diamond/core/init/table/TableCreator.java
UTF-8
1,233
2.296875
2
[]
no_license
package com.wonders.diamond.core.init.table; import com.wonders.diamond.core.jdbc.SqlTemplate; import com.wonders.diamond.core.jdbc.factory.SqlTemplateFactory; import javax.sql.DataSource; import java.sql.SQLException; /** * Created by nick on 2017/1/25. */ public class TableCreator { public static void tableInit(SqlTemplate sqlTemplate) throws SQLException { String createTableA = "CREATE TABLE IF NOT EXISTS tb_diamond_app(" + "appId varchar(32) not null primary key, \n" + "appName varchar(40) NOT NULL, \n" + "createTime datetime NOT NULL default NOW(), \n" + "updateTime datetime NOT NULL default NOW())"; String createTableB = "CREATE TABLE IF NOT EXISTS tb_diamond_configuration(" + "id varchar(32) not null primary key, \n" + "appId varchar(32) not null, \n" + "profile varchar(4) not null, \n" + "configKey varchar(100) not null, \n" + "createTime datetime NOT NULL default NOW(), \n" + "updateTime datetime NOT NULL default NOW())"; sqlTemplate.createTable(createTableA); sqlTemplate.createTable(createTableB); } }
true
3da4eddde9f026c8d15cf4037624332cd2500554
Java
Ramanathan13/CucumberTest
/src/test/java/googletest/GoogleTest.java
UTF-8
279
1.695313
2
[]
no_license
package googletest; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class GoogleTest { @Test public void sampletest() { WebDriver wd=new FirefoxDriver(); wd.get("WWW.Google.com"); } }
true
87d76a7e45719a88d7345245f070c75a8213689f
Java
chenywang/Starcraft-AI
/Starcraft AI/src/Zerg/ZergData.java
UTF-8
2,188
2.359375
2
[]
no_license
package Zerg; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import bwapi.Unit; import bwapi.UnitType; import main.Data; public class ZergData extends Data{ public ZergData(){ super(); workerType = UnitType.Zerg_Drone; baseType = UnitType.Zerg_Hatchery; gasType = UnitType.Zerg_Extractor; UnitType[] armyT = new UnitType[]{UnitType.Zerg_Zergling,UnitType.Zerg_Hydralisk,UnitType.Zerg_Lurker, UnitType.Zerg_Guardian,UnitType.Zerg_Devourer,UnitType.Zerg_Mutalisk,UnitType.Zerg_Ultralisk, UnitType.Zerg_Queen,UnitType.Zerg_Defiler,UnitType.Zerg_Scourge}; UnitType[] allUnit = new UnitType[]{UnitType.Zerg_Larva,UnitType.Zerg_Drone,UnitType.Zerg_Creep_Colony, UnitType.Zerg_Spawning_Pool,UnitType.Zerg_Evolution_Chamber,UnitType.Zerg_Hydralisk_Den ,UnitType.Zerg_Spire,UnitType.Zerg_Greater_Spire,UnitType.Zerg_Queens_Nest,UnitType.Zerg_Extractor,UnitType.Zerg_Nydus_Canal ,UnitType.Zerg_Ultralisk_Cavern,UnitType.Zerg_Defiler_Mound,UnitType.Zerg_Overlord}; UnitType[] trainArmyB = new UnitType[]{UnitType.Zerg_Hive,UnitType.Zerg_Hatchery,UnitType.Zerg_Lair}; UnitType[] morphPair = new UnitType[]{UnitType.Zerg_Lair,UnitType.Zerg_Hatchery,UnitType.Zerg_Hive,UnitType.Zerg_Lair, UnitType.Zerg_Greater_Spire,UnitType.Zerg_Spire,UnitType.Zerg_Guardian,UnitType.Zerg_Mutalisk,UnitType.Zerg_Devourer, UnitType.Zerg_Mutalisk,UnitType.Zerg_Lurker,UnitType.Zerg_Hydralisk}; for(int i = 0;i < morphPair.length - 1;i += 2){ morphFrom.put(morphPair[i],morphPair[i + 1]); } for(UnitType u : armyT){ armyType.add(u); } //initialize myUnits for(UnitType u : allUnit){ myUnits.put(u, new HashMap<Integer,Unit>()); underConstructing.put(u, new HashMap<Integer,Unit>()); } for(UnitType u : armyT){ myUnits.put(u, new HashMap<Integer,Unit>()); underConstructing.put(u, new HashMap<Integer,Unit>()); } for(UnitType u : trainArmyB){ myUnits.put(u, new HashMap<Integer,Unit>()); underConstructing.put(u,new HashMap<Integer,Unit>()); } //initialize trainArmyBuilding for(UnitType u : trainArmyB){ trainArmyBuilding.add(u); } } }
true
b12d5d0e6c1d0723cf97ae8221718a962411e6fd
Java
ijdotta/ED-Java
/examen_parcial/Mi_comparador.java
UTF-8
571
3.515625
4
[]
no_license
package examen_parcial; import java.util.Comparator; public class Mi_comparador implements Comparator<Integer> { /* Las claves se ordenan en la cola con el criterio: Primero salen las impares ordenadas de mayor a menor Después salen las pares ordenadas de mayor a menor EJ: 9 7 3 1 8 6 2 */ @Override public int compare(Integer i, Integer j) { int comp; boolean i_par, j_par; i_par = i % 2 == 0; j_par = j % 2 == 0; if (!i_par && j_par) comp = -1; else if (i_par && !j_par) comp = 1; else comp = j - i; return comp; } }
true
4b30b32c9f7aadd2929b1dfdd2c50b6bc6ec4035
Java
blockparty-sh/600302-1_source_from_JADX
/sources/org/apache/commons/collections4/trie/AbstractBitwiseTrie.java
UTF-8
4,459
2.75
3
[]
no_license
package org.apache.commons.collections4.trie; import java.io.Serializable; import java.util.AbstractMap; import java.util.Map.Entry; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Trie; public abstract class AbstractBitwiseTrie<K, V> extends AbstractMap<K, V> implements Trie<K, V>, Serializable { private static final long serialVersionUID = 5826987063535505652L; private final KeyAnalyzer<? super K> keyAnalyzer; static abstract class BasicEntry<K, V> implements Entry<K, V>, Serializable { private static final long serialVersionUID = -944364551314110330L; protected K key; protected V value; public BasicEntry(K k) { this.key = k; } public BasicEntry(K k, V v) { this.key = k; this.value = v; } public V setKeyValue(K k, V v) { this.key = k; return setValue(v); } public K getKey() { return this.key; } public V getValue() { return this.value; } public V setValue(V v) { V v2 = this.value; this.value = v; return v2; } public int hashCode() { int i = 0; int hashCode = getKey() == null ? 0 : getKey().hashCode(); if (getValue() != null) { i = getValue().hashCode(); } return hashCode ^ i; } public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Entry)) { return false; } Entry entry = (Entry) obj; return AbstractBitwiseTrie.compare(this.key, entry.getKey()) && AbstractBitwiseTrie.compare(this.value, entry.getValue()); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.key); sb.append("="); sb.append(this.value); return sb.toString(); } } /* access modifiers changed from: 0000 */ public final K castKey(Object obj) { return obj; } public /* bridge */ /* synthetic */ MapIterator mapIterator() { return mapIterator(); } protected AbstractBitwiseTrie(KeyAnalyzer<? super K> keyAnalyzer2) { if (keyAnalyzer2 != null) { this.keyAnalyzer = keyAnalyzer2; return; } throw new NullPointerException("keyAnalyzer"); } /* access modifiers changed from: protected */ public KeyAnalyzer<? super K> getKeyAnalyzer() { return this.keyAnalyzer; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Trie["); sb.append(size()); sb.append("]={\n"); for (Entry entry : entrySet()) { sb.append(" "); sb.append(entry); sb.append("\n"); } sb.append("}\n"); return sb.toString(); } /* access modifiers changed from: 0000 */ public final int lengthInBits(K k) { if (k == null) { return 0; } return this.keyAnalyzer.lengthInBits(k); } /* access modifiers changed from: 0000 */ public final int bitsPerElement() { return this.keyAnalyzer.bitsPerElement(); } /* access modifiers changed from: 0000 */ public final boolean isBitSet(K k, int i, int i2) { if (k == null) { return false; } return this.keyAnalyzer.isBitSet(k, i, i2); } /* access modifiers changed from: 0000 */ public final int bitIndex(K k, K k2) { return this.keyAnalyzer.bitIndex(k, 0, lengthInBits(k), k2, 0, lengthInBits(k2)); } /* access modifiers changed from: 0000 */ public final boolean compareKeys(K k, K k2) { boolean z = true; if (k == null) { if (k2 != null) { z = false; } return z; } else if (k2 == null) { return false; } else { if (this.keyAnalyzer.compare(k, k2) != 0) { z = false; } return z; } } static boolean compare(Object obj, Object obj2) { if (obj == null) { return obj2 == null; } return obj.equals(obj2); } }
true
bf06cfcaa53a6cd43d67788de2d765ffe576f1f7
Java
EdnardoBarbosa/proj-dispositivos-moveis
/app/src/main/java/com/example/myapplication/FirstActivity.java
UTF-8
1,198
2.421875
2
[]
no_license
package com.example.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class FirstActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); Button btnPaciente = (Button) findViewById(R.id.btn_paciente); btnPaciente.setOnClickListener(this); Button btnMedico = (Button) findViewById(R.id.btn_medico); btnMedico.setOnClickListener(this); } @Override public void onClick(View view){ switch (view.getId()){ case R.id.btn_paciente: Intent telaCadastroPaciente = new Intent(this, CadastroPacienteActivity.class); startActivity(telaCadastroPaciente); break; case R.id.btn_medico: Intent telaCadastroMedico = new Intent(this, CadastroMedicoActivity.class); startActivity(telaCadastroMedico); break; } } }
true
90e49101b00ac8e6439ba05ad171ba1e65c54eed
Java
hymanlew/shirodemo
/src/main/java/hyman/demo/RealmTest.java
UTF-8
6,821
2.921875
3
[]
no_license
package hyman.demo; import org.apache.shiro.subject.Subject; import org.junit.Test; import utils.ShiroUtil; import java.util.ArrayList; import java.util.List; public class RealmTest { // 编程式授权:基于角色的访问控制 @Test public void testRoles(){ Subject currenUser = ShiroUtil.login("classpath:shiro_role.ini","hyman","hyman"); //Subject currenUser = ShiroUtil.login("classpath:shiro_role.ini","test","test"); String result = currenUser.hasRole("role2")?"有角色 1":"没有角色 1"; System.out.println(result); List<String> list = new ArrayList<>(); list.add("role2"); list.add("role3"); // 其内部实现是,一个一个角色进行判断,即 for 循环调用 hasRole 方法。 boolean[] booleans = currenUser.hasRoles(list); result = booleans[0]?"有角色 2":"无角色 2"; System.out.println(result); System.out.println(booleans[1]?"有角色 3":"无角色 3"); // 只有所有角色都为 true 时,才为 true result = currenUser.hasAllRoles(list)?"有相关角色":"没有相关角色"; System.out.println(result); currenUser.logout(); } @Test public void checkRoles(){ Subject currentUser = ShiroUtil.login("classpath:shiro_role.ini","hyman","hyman"); // 该方法没有返回值,只有当没有相关角色权限时才会抛出异常。 currentUser.checkRole("role2"); // Subject does not have role [role3] currentUser.checkRole("role3"); currentUser.logout(); } // 编程式授权:基于权限的访问控制 @Test public void isPermitted(){ //Subject currenUser = ShiroUtil.login("classpath:shiro_permission.ini","hyman","hyman"); Subject currenUser = ShiroUtil.login("classpath:shiro_permission.ini","test","test"); String result = currenUser.isPermitted("user:select")?"有查询权限":"没有查询权限"; // 如果在数据库中是没有定义相关权限,则全部角色都会没有权限 System.out.println(result); result = currenUser.isPermitted("user:update")?"有更新权限":"没有更新权限"; System.out.println(result); List<String> list = new ArrayList<>(); list.add("user:select"); list.add("user:update"); // 输出是数组类型的字符串,所以不能用 System.out.println(list.toString()); // isPermittedAll() 参数是多个字符串,其返回值与 hasAllRoles 相同。 boolean[] booleans = currenUser.isPermitted("user:select","user:update"); System.out.println(booleans[0]?"有查询权限":"没有查询权限"); System.out.println(booleans[1]?"有更新权限":"没有更新权限"); // checkPermission() 也与 checkRole() 相同。 currenUser.logout(); } // 注解式授权: public void method(){ /** * @RequiresAuthentication 要求当前 subject 已经在当前的 session中被验证通过才能被访问和调用。 * 即:SecurityUtils.getSubject().isAuthenticated()。 * * @RequiresGuest 要求当前的 subject是一个‘guest’,即他们必须是在之前的 session中没有被验证或 * 被记住才能被访问或调用。即 SecurityUtils.getSubject()..getPrincipals() = null。 * * @RequiresPermissions("user:select") 要求当前的 subject拥有相关权限才能访问。一个权限(user:select), * 多个权限(value = {"11","22"})。 * * @RequiresRoles("hyman") 要求当前登录的主体拥有相关的角色才能访问。如果没有,则会抛 authorizationexception * 异常。多个角色(value = {"hyman","test"})。 * * @RequiresUser 它需要当前的登录主体是一个应用程序用户才能访问和调用。应用程序用户是指:拥有已知身份,或在当前 * session 中由于通过验证被确认,或在之前的 session 中的 rememberme服务被记住。 */ } public static void main(String[] args) { /** * role=*:view role=user:*:1 如 “user:view” 等价于 “user:view:*” ;而 “organization” 等价于 “organization:*” 或者 “organization:*:*” 。可以 这么理解,这种方式实现了前缀匹配。 即首先根据用户名找到角色,然后根据角色再找到权限;即角色是权限集合;Shiro 同样不进行权限的维护,需要我们通过 Realm 返回相应的权限信息。只需要维护“用户— —角色”之间的关系即可。 即用户 - 角色之间是多对多关系,角色 - 权限之间是多对多关系;且用户和权限之间通过角色建立关系;在系统中验证时通过权限 验证,角色只是权限集合,即所谓的显示角色;其实权限应该对应到资源(如菜单、URL、页面按钮、Java方法等)中,即应该将权限 字符串存储到资源实体中,但是目前为了简单化,直接提取一个权限表。 用户实体包括:编号 (id)、用户名 (username)、密码(password)、盐 (salt)、是否锁定 (locked);是否锁定用于封禁用户使用, 其实最好使用 Enum 字段存储,可以实现更复杂的用户状态实现。 角色实体包括:、编号 (id)、角色标识符(role)、描述 (description)、是否可用(available);其中角色标识符用于在程序中进行隐式角色判断的,描述用于以后再前台界面显示的、 是否可用表示角色当前是否激活。 权限实体包括:编号(id)、权限标识符(permission)、描述(description)、是否可用(available);含义和角色实体类似。 另外还有两个关系实体:用户 - 角色实体(用户编号、角色编号,且组合为复合主键);角色 - 权限实体(角色编号、权限编号, 且组合为复合主键)。 性能问题: 通配符匹配方式比字符串相等匹配来说是更复杂的,因此需要花费更长时间,但是一般系统的权限不会太多,且可以配合缓存来提供其 性能,如果这样性能还达不到要求我们可以实现位操作算法实现性能更好的权限匹配。另外实例级别的权限验证如果数据量太大也不建 议使用,可能造成查询权限及匹配变慢。可以考虑比如在sql查询时加上权限字符串之类的方式在查询时就完成了权限匹配。 */ } }
true
1daf63e4f0bb649cdb7249b77dc0667a8c5ee4b7
Java
BartekOgien/Bartosz-Ogieniewski-kodilla-java
/kodilla-testing/src/main/java/com/kodilla/testing/forum/statistics/StatisticsCalculator.java
UTF-8
1,185
3.015625
3
[]
no_license
package com.kodilla.testing.forum.statistics; public class StatisticsCalculator { int forumUsers; int postsNumber; int commentsNumber; double averagePostsperUser; double averageCommentsPerUser; double averageCommentsperPost; public void calculateAdvStatistics(Statistics statistics) { forumUsers = statistics.usersNames().size(); postsNumber = statistics.postsCount(); commentsNumber = statistics.commentsCount(); averagePostsperUser = (double)postsNumber / forumUsers; averageCommentsPerUser = (double)commentsNumber / forumUsers; averageCommentsperPost = (double)commentsNumber / postsNumber; } public void showStatistics() { System.out.println("Numbers of users: " + forumUsers); System.out.println("Numbers of posts: " + postsNumber); System.out.println("Numbers of comments: " + commentsNumber); System.out.println("Average numbers of posts per user: " + averagePostsperUser); System.out.println("Numbers of comments per user: " + averageCommentsPerUser); System.out.println("Numbers of comments per post: " + averageCommentsperPost); } }
true
b892d78bf52eacf245f897990e1a2fd88ec6fb7e
Java
Sakamoto17/test
/src/tsd/String_observe.java
UTF-8
963
2.90625
3
[]
no_license
package tsd; public class String_observe { //単純だった… public static void main(String[] args) { String str1 = "hello"; String str2 = "hello"; String str3 = str1; String str4 = new String("hello"); if(str1 == str2) { System.out.println("t"); }else { System.out.println("f"); } if(str1 == str3) { System.out.println("t"); }else { System.out.println("f"); } if(str1 == str4) { System.out.println("t"); }else { System.out.println("f"); } if(str1.equals(str2)) { System.out.println("t"); }else { System.out.println("f"); } if(str1.equals(str3)) { System.out.println("t"); }else { System.out.println("f"); } if(str1.equals(str4)) { System.out.println("t"); }else { System.out.println("f"); } } } // //class StringOne{ // private String a; // private String b; // private String c; // private String d; // // } //}
true
b750aee18e59fb00ff5120f6f84caf57ddf30281
Java
HwangKC/PhoneProfilesPlus
/phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/RingerModeChangeReceiver.java
UTF-8
6,015
1.84375
2
[ "Apache-2.0" ]
permissive
package sk.henrichg.phoneprofilesplus; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Build; import android.provider.Settings; import java.util.Calendar; public class RingerModeChangeReceiver extends BroadcastReceiver { public static boolean internalChange = false; @Override public void onReceive(Context context, Intent intent) { GlobalData.logE("##### RingerModeChangeReceiver.onReceive", "xxx"); if (!internalChange) { GlobalData.logE("RingerModeChangeReceiver.onReceive", "!internalChange"); final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); setRingerMode(context, audioManager); } //setAlarmForDisableInternalChange(context); } @SuppressWarnings("deprecation") private static boolean vibrationIsOn(Context context, AudioManager audioManager) { int vibrateType = -999; if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) vibrateType = audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); int vibrateWhenRinging; if (android.os.Build.VERSION.SDK_INT < 23) // Not working in Android M (exception) vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), "vibrate_when_ringing", 0); else vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, 0); GlobalData.logE("RingerModeChangeReceiver.getRingerMode", "vibrateType="+vibrateType); GlobalData.logE("RingerModeChangeReceiver.getRingerMode", "vibrateWhenRinging="+vibrateWhenRinging); return (vibrateType == AudioManager.VIBRATE_SETTING_ON) || (vibrateType == AudioManager.VIBRATE_SETTING_ONLY_SILENT) || (vibrateWhenRinging == 1); } public static int getRingerMode(Context context, AudioManager audioManager) { int ringerMode = audioManager.getRingerMode(); int systemZenMode = -1; if (android.os.Build.VERSION.SDK_INT >= 21) systemZenMode = GlobalData.getSystemZenMode(context, -1); GlobalData.logE("RingerModeChangeReceiver.getRingerMode", "ringerMode="+ringerMode); GlobalData.logE("RingerModeChangeReceiver.getRingerMode", "systemZenMode=" + systemZenMode); // convert to profile ringerMode int pRingerMode = 0; if ((android.os.Build.VERSION.SDK_INT >= 21)/* && PPNotificationListenerService.isNotificationListenerServiceEnabled(context)*/) { if (systemZenMode == ActivateProfileHelper.ZENMODE_ALL) { switch (ringerMode) { case AudioManager.RINGER_MODE_NORMAL: if (vibrationIsOn(context, audioManager)) pRingerMode = 2; else pRingerMode = 1; break; case AudioManager.RINGER_MODE_VIBRATE: pRingerMode = 3; break; case AudioManager.RINGER_MODE_SILENT: pRingerMode = 4; break; } } else pRingerMode = 5; } else { if ((android.os.Build.VERSION.SDK_INT < 21) || (systemZenMode == ActivateProfileHelper.ZENMODE_ALL)) { switch (ringerMode) { case AudioManager.RINGER_MODE_NORMAL: if (vibrationIsOn(context, audioManager)) pRingerMode = 2; else pRingerMode = 1; break; case AudioManager.RINGER_MODE_VIBRATE: pRingerMode = 3; break; case AudioManager.RINGER_MODE_SILENT: pRingerMode = 4; break; } } else pRingerMode = 4; } GlobalData.logE("RingerModeChangeReceiver.getRingerMode", "pRingerMode=" + pRingerMode); return pRingerMode; } public static void setRingerMode(Context context, AudioManager audioManager) { int pRingerMode = getRingerMode(context, audioManager); if (pRingerMode != 0) { //Log.e("RingerModeChangeReceiver",".setRingerMode new ringerMode="+pRingerMode); GlobalData.setRingerMode(context, pRingerMode); } } public static void removeAlarm(Context context/*, boolean oneshot*/) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, DisableInernalChangeBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } } public static void setAlarmForDisableInternalChange(Context context) { removeAlarm(context); //Context context = getApplicationContext(); Intent _intent = new Intent(context, DisableInernalChangeBroadcastReceiver.class); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, _intent, PendingIntent.FLAG_CANCEL_CURRENT); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, 3); long alarmTime = calendar.getTimeInMillis(); AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime, alarmIntent); } }
true
519745413e2f19a8336f469d978c1b66f8550946
Java
m4rvin/Grizzly-thread-handling-test
/src/main/java/it/uniroma2/sdcc/file_transfer/FileMetadata.java
UTF-8
467
1.976563
2
[]
no_license
package it.uniroma2.sdcc.file_transfer; import java.io.Serializable; public class FileMetadata implements Serializable { /** * */ private static final long serialVersionUID = -8209508583389357605L; public String filename; // public Long size_in_bytes; @Override public String toString() { //return "FileMetadata [filename=" + filename + ", size_in_bytes=" //+ size_in_bytes + "]"; return "FileMetadata [filename=" + filename +"]"; } }
true
48badf9fd91ed656f070d9a2da3b5971b761845a
Java
malvern/farm-management
/egg-management-production-core/src/main/java/zw/co/malvern/api/report/ReportResponse.java
UTF-8
1,009
2.125
2
[]
no_license
package zw.co.malvern.api.report; import zw.co.malvern.utils.response.BasicResponse; import java.util.List; public class ReportResponse extends BasicResponse { private int totalPages; private int page; private List<EggDto> eggDtoList; public ReportResponse() { } public ReportResponse(String narrative, boolean success, int totalPages, int page, List<EggDto> eggDtoList) { super(narrative, success); this.totalPages = totalPages; this.page = page; this.eggDtoList = eggDtoList; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public List<EggDto> getEggDtoList() { return eggDtoList; } public void setEggDtoList(List<EggDto> eggDtoList) { this.eggDtoList = eggDtoList; } }
true
52f63b4bce1601822da372b952af18775a2ed25e
Java
Sophie-Williams/BotGame-13
/src/utils/Maps.java
UTF-8
2,033
2.953125
3
[]
no_license
package utils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public abstract class Maps { private Maps() { throw new AssertionError("Uninstantiable"); } public static Set<HexCoord> shell(int radius) { Set<HexCoord> result = new HashSet<>(); if(radius == 0) { result.add(new HexCoord(0, 0)); return result; } for(int i = 0; i < radius; i++) { result.add(new HexCoord(radius, i));//S up to SE result.add(new HexCoord(radius - i, radius)); //SE to NE result.add(new HexCoord(-i, radius - i)); //NE to N result.add(new HexCoord(-radius, -i)); //N to NW result.add(new HexCoord(i - radius, -radius)); //NW to SW result.add(new HexCoord(i, i - radius)); //SW to S } return result; } public static Set<HexCoord> fullHex(int radius) { Set<HexCoord> result = new HashSet<>(); for(int i = 0; i <= radius; i++) { result.addAll(shell(i)); } return result; } public static Map<HexCoord, Integer> yieldPatch(Set<HexCoord> coords, int period) { Map<HexCoord, Integer> result = new HashMap<>(); for(HexCoord hc: coords) { result.put(hc, period); } return result; } public static Tile makeTile(HexCoord hc, boolean hasBot, Bot bot, int actionPointPeriod) { return new Tile(new TileData(hc, hasBot, bot, actionPointPeriod, 0)); } public static Map<HexCoord, Bot> getBotsFromCoords(Set<Bot> bots) { Map<HexCoord, Bot> result = new HashMap<>(); for(Bot b: bots) { result.put(b.getLocation(), b); } return result; } public static Set<Tile> makeMap(Set<HexCoord> coords, Map<HexCoord, Integer> periods, Set<Bot> bots) { Set<Tile> result = new HashSet<>(); Map<HexCoord, Bot> botsFromCoords = getBotsFromCoords(bots); for(HexCoord hc: coords) { if(botsFromCoords.containsKey(hc)) { result.add(makeTile(hc, true, botsFromCoords.get(hc), periods.getOrDefault(hc, 0))); } else { result.add(makeTile(hc, false, null, periods.getOrDefault(hc, 0))); } } return result; } }
true
45ee49d5ea8fc49b6944eb082fe3449bb2f80988
Java
ghj1040110333/udmp
/udmp-components/udmp_mq_kafka_boot/src/main/java/cn/com/git/udmp/mq/kafka/KafkaApplication.java
UTF-8
1,342
1.851563
2
[]
no_license
package cn.com.git.udmp.mq.kafka; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.integration.config.EnableIntegration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import cn.com.git.udmp.boot.UdmpApplication; import cn.com.git.udmp.core.logging.ILog; import cn.com.git.udmp.mq.MqReceive; import cn.com.git.udmp.mq.MqReceiveRunnable; import cn.com.git.udmp.mq.MqSend; import cn.com.git.udmp.mq.kafka.test.consumer.KafkaConsumer; import cn.com.git.udmp.mq.kafka.test.producer.KafkaProducer; /** * Kafka的Spring Boot启动类 * @description * @author Spring Cao * @date 2016年10月12日 下午2:23:00 */ @EnableIntegration @SpringBootApplication public class KafkaApplication implements ILog{ /** * @title * Application直接运行的main函数 * @description * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { logger.info("Startup with Application main !"); SpringApplication.run(UdmpApplication.class, args); } }
true
00059711599c1055bd51b7ae4ddf188a0c15c65f
Java
mouse3150/blooming
/joss/src/main/java/org/javaswift/joss/client/impl/ContainerImpl.java
UTF-8
486
2.171875
2
[ "Apache-2.0" ]
permissive
package org.javaswift.joss.client.impl; import org.javaswift.joss.client.core.AbstractContainer; import org.javaswift.joss.model.StoredObject; public class ContainerImpl extends AbstractContainer { public ContainerImpl(AccountImpl account, String name, boolean allowCaching) { super(account, name, allowCaching); } @Override public StoredObject getObject(String objectName) { return new StoredObjectImpl(this, objectName, isAllowCaching()); } }
true
8d8d51c8a27b21fb065dcc66a75e1229c1de2199
Java
z0lope0z/sphere-jvm-sdk
/src/main/java/io/sphere/sdk/meta/JvmSdkFeatures.java
UTF-8
2,000
2.5625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package io.sphere.sdk.meta; import io.sphere.sdk.models.Base; /** <h3>Embracing Java 8</h3> <p>The SDK API uses:</p> <ul> <li>{@link java.util.concurrent.CompletionStage}</li> <li>{@link java.util.Optional}</li> <li>Java Date API: {@link java.time.Instant}, {@link java.time.LocalDate} and {@link java.time.LocalTime}</li> <li>{@link java.util.function.Function}</li> </ul> <h3>Good defaults for toString(), equals() and hashCode()</h3> <p>SDK implementation classes extends {@link Base} which provides default implementations for the methods by using reflection following the suggestions of <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html">Effective Java</a>.</p> <h3>Domain models are immutable</h3> <p>Domain models are no plain old Java objects, since the client does not poses control over them but needs to send update commands to SPHERE.IO, so setters would pretend a functionality which is not possible.</p> <p>Clients for <em>other</em> cloud services provide setters and synchronize the model in the background. This approach still blocks the caller thread and makes it hard to impossible to tune error handling, timeouts and recover strategies. Our approach makes it explicit, that an operation can be performed in the background, takes time and might fail.</p> <h3>Domain models are interfaces</h3> <p>Since domain models are interfaces, you can use them in design patterns or add convenience methods.</p> <h3>Testability</h3> <p>The clients and the models are interfaces, so they can be replaced with test doubles. In addition the SDK provides builders and JSON converters to create models for unit tests.</p> <h3>Domain specific languages to create requests</h3> <p>For example {@link io.sphere.sdk.queries.QueryDsl} helps to formulate valid queries and discover for which attributes can be in which way queried and sorted.</p> */ public final class JvmSdkFeatures extends Base { private JvmSdkFeatures() { } }
true
43655de629df95bc13efb1e20c7d59897a12efeb
Java
DmytroKashchenko/calculator
/src/main/java/ua/dmytrokashchenko/calculator/service/ReversePolishNotationCalculatorImpl.java
UTF-8
2,532
3.234375
3
[]
no_license
package ua.dmytrokashchenko.calculator.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ua.dmytrokashchenko.calculator.domain.Element; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BinaryOperator; public class ReversePolishNotationCalculatorImpl implements Calculator { private static final Map<Element, BinaryOperator<Double>> OPERATOR_TO_FUNCTION = new HashMap<>(); private static final Logger LOGGER = LoggerFactory.getLogger(ReversePolishNotationCalculatorImpl.class); private final ReversePolishNotationParser parser; static { OPERATOR_TO_FUNCTION.put(new Element("+"), Double::sum); OPERATOR_TO_FUNCTION.put(new Element("-"), (operand1, operand2) -> operand1 - operand2); OPERATOR_TO_FUNCTION.put(new Element("*"), (operand1, operand2) -> operand1 * operand2); OPERATOR_TO_FUNCTION.put(new Element("/"), (operand1, operand2) -> operand1 / operand2); OPERATOR_TO_FUNCTION.put(new Element("^"), Math::pow); } public ReversePolishNotationCalculatorImpl(ReversePolishNotationParser parser) { this.parser = parser; } @Override public double calculate(String expression) { List<Element> elements = parser.parse(expression); boolean isDifficult = elements.size() > 3; if (isDifficult) { LOGGER.debug("The expression for calculation: " + expression); LOGGER.debug("Reverse Polish Notation: " + elements); } while (elements.size() > 2) { for (int i = 2; i < elements.size(); i++) { if (elements.get(i).isOperand()) { double value = calculateElements(elements.get(i - 2), elements.get(i - 1), elements.get(i)); elements.set(i - 2, new Element(Double.toString(value))); elements.remove(i - 1); elements.remove(i - 1); break; } } } double result = Double.parseDouble(elements.get(0).getValue()); if (isDifficult) { LOGGER.debug("Result: " + result); } return result; } private double calculateElements(Element firstOperand, Element secondOperand, Element operator) { Double first = Double.parseDouble(firstOperand.getValue()); Double second = Double.parseDouble(secondOperand.getValue()); return OPERATOR_TO_FUNCTION.get(operator).apply(first, second); } }
true
10d4f25e54c9f361a854d02406f1cebd83b89dd9
Java
JAVA-MSDT/library_git
/Final_Project_web_stage_rest/src/com/epam/library/Main.java
UTF-8
631
2.28125
2
[]
no_license
package com.epam.library; import com.epam.library.model.service.ServiceException; import org.springframework.web.client.RestTemplate; import java.util.LinkedHashMap; import java.util.List; public class Main { private final static String SERVER_URI = "http://localhost:8284/library/"; public static void main(String[] args) throws ServiceException { getAllBooks(); } private static void getAllBooks() { RestTemplate restTemplate = new RestTemplate(); List<LinkedHashMap> bookList = restTemplate.getForObject(SERVER_URI + "books", List.class); assert bookList != null; System.out.println(bookList.size()); } }
true
c5705343213be0a5831ddefda29b1d36061c5a1c
Java
CodingMateMoon/java
/18_apiProject/src/com/equalsTest/run/Main.java
UTF-8
1,268
2.9375
3
[]
no_license
package com.equalsTest.run; import com.equalsTest.model.vo.Member; import com.equalsTest.model.vo.Person; public class Main { public static void main(String[] args) { // variables : ${string_prompt} System.out.println(args + " " + args.length); /*args[0] = "하하"; args[1] = "호호"; args[2] = "히히";*/ for (String a : args) { System.out.println(a); } args[0] = "이슬"; args[1] = "처음"; args[2] = "한라"; for (String a : args) { System.out.println(a); } Person p1 = new Person("유병승", 19, "010-3644-6259"); Person p2 = new Person("유병승", 19, "010-3644-6259"); if (p1 == p2) { p2 = null; } /*if (p1.equals(p2)) { p2 = new Person(); }*/ System.out.println(p1.equals(new Member("aaaa", "aaa", "aaa"))); System.out.println(p1 + " " + p1.hashCode()); System.out.println(p2 + " " + p2.hashCode()); Person p3 = /*(Person)*/ p1.clone(); System.out.println(p3 + " " + p3.hashCode()); Member m1 = new Member("gg123", "1234", "허허허"); Member m2 = new Member("gg123", "5678", "호호호"); System.out.println(m1.equals(m2)); System.out.println(m1 + " " + m1.hashCode()); System.out.println(m2 + " " + m2.hashCode()); } }
true
81c58c239635da2e30e3d79ce6ecf78da3485efd
Java
apache/asterixdb
/asterixdb/asterix-fuzzyjoin/src/main/java/org/apache/asterix/fuzzyjoin/invertedlist/InvertedListLengthList.java
UTF-8
3,258
2.640625
3
[ "MIT", "BSD-3-Clause", "PostgreSQL", "Apache-2.0" ]
permissive
/** * 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 org.apache.asterix.fuzzyjoin.invertedlist; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; public class InvertedListLengthList implements InvertedList { /** * @author rares * assumes that ListLength(s) are not empty inside the * InvertedListLength */ private class ListIterator implements Iterator<int[]> { private final Iterator<ListLength> iteratorLength; private Iterator<int[]> iteratorList; public ListIterator() { iteratorLength = list.iterator(); iteratorList = null; } public boolean hasNext() { return (iteratorList != null && iteratorList.hasNext()) || iteratorLength.hasNext(); } public int[] next() { if (iteratorList != null && iteratorList.hasNext()) { return iteratorList.next(); } iteratorList = iteratorLength.next().list.iterator(); return iteratorList.next(); } public void remove() { throw new UnsupportedOperationException(); } } private class ListLength { public int length; public ArrayList<int[]> list = new ArrayList<int[]>(); @Override public String toString() { StringBuffer l = new StringBuffer("("); for (int[] i : list) { l.append(Arrays.toString(i)); l.append(","); } l.append(")"); return "(length:" + length + "," + l + ")"; } } private LinkedList<ListLength> list; public InvertedListLengthList() { list = new LinkedList<ListLength>(); } public void add(int[] element) { if (!list.isEmpty() && list.getLast().length == element[2]) { list.getLast().list.add(element); } else { ListLength listLength = new ListLength(); listLength.length = element[2]; listLength.list.add(element); list.add(listLength); } } public Iterator<int[]> iterator() { return new ListIterator(); } public void setMinLength(int minLength) { while (!list.isEmpty() && list.getFirst().length < minLength) { list.removeFirst(); } } @Override public String toString() { return list.toString(); } }
true
d0294accdc614f20ba3f0e1a955315d7ffa5d59f
Java
trannamtrung1st/PetID
/PetID.Helper/src/petid/helper/StringHelper.java
UTF-8
622
2.4375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package petid.helper; /** * * @author TNT */ public class StringHelper { public static String escape(String s) { return s.replace("\\", "\\\\") .replace("\t", "\\t") .replace("\b", "\\b") .replace("\n", "\\n") .replace("\r", "\\r") .replace("\f", "\\f") .replace("\'", "\\'") .replace("\"", "\\\""); } }
true
ee297dce17739c579833e012848503b04d753be4
Java
raijinthunderkegll/mmall_learnning
/src/main/java/com/mmall/dao/UserMapper.java
UTF-8
982
2.015625
2
[]
no_license
package com.mmall.dao; import com.mmall.pojo.User; import org.apache.ibatis.annotations.Param; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); int checkUserName(String username); int checkUserNameById(@Param("username")String username,@Param("userId")Integer userId); User selectLogin(@Param("username") String username, @Param("password") String password); int checkEmail(String email); int checkEmailById(@Param("email")String email,@Param("userId")Integer userId); int checkPhone(String phone); int checkPhoneById(@Param("phone")String phone,@Param("userId")Integer userId); User selectUserByUsername(String username); int checkPassword(@Param("password")String password, @Param("userId")Integer userId); }
true
66300f083aaeabe7b29cc9cae8ffd8edf7f2b395
Java
andr3m0ur4/Exercicios_LP
/Lista 6/Ex15.java
UTF-8
654
3.734375
4
[]
no_license
import java.util.Scanner; public class Ex15 { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); System.out.print("Digite um numero: "); int a = entrada.nextInt(); System.out.print("Digite outro numero: "); int b = entrada.nextInt(); int soma = 0; if (a < b) { for (int i = a; i <= b; i++) { soma += i; } } else { for (int i = b; i <= a; i++) { soma += i; } } System.out.println("Soma dos numeros = " + soma); entrada.close(); } }
true
8eb1f6686e27aa1e441c00bf45667db9227fe79f
Java
mxzenf/concurrentlearn
/src/main/java/com/yx/concurrentlearn/ex8/FutureDemo.java
UTF-8
1,880
3.359375
3
[]
no_license
package com.yx.concurrentlearn.ex8; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.lang3.RandomUtils; /** * * @author yangxin 2019年2月22日 上午9:42:07 */ public class FutureDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(3000); return RandomUtils.nextInt(100,200); } }; Future<Integer> future = executorService.submit(callable); Thread.sleep(1000); System.out.println("1000毫秒后任务是否完成:" + future.isDone()); System.out.println("1000毫秒后任务是否完成:" + future.isCancelled()); future.cancel(true); Thread.sleep(3000); System.out.println("cancle后任务是否完成:" + future.isDone()); System.out.println("cancle后任务是否完成:" + future.isCancelled()); future = executorService.submit(callable); try { future.get(2, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException e) { System.out.println("等待2秒超时未获取结果"); System.out.println("超时等待任务是否完成:" + future.isDone()); System.out.println("超时等待任务是否完成:" + future.isCancelled()); } Thread.sleep(2000); System.out.println("继续等待2秒后获取等待结果:" + future.get()); executorService.shutdown(); } }
true
d19d25173ed28563a8d0033b7eca3188b3f6989a
Java
gksxodnd007/bbkk
/src/main/java/org/seoul/kk/controller/TravelerController.java
UTF-8
2,030
2.21875
2
[]
no_license
package org.seoul.kk.controller; import org.seoul.kk.common.model.ApiResponseModel; import org.seoul.kk.dto.traveler.RegisterTravelerDto; import org.seoul.kk.entity.Traveler; import org.seoul.kk.entity.constant.TravelProperty; import org.seoul.kk.exception.BadRequestException; import org.seoul.kk.service.TravelerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping(value = "/v1/traveler") public class TravelerController { @Autowired private TravelerService travelerService; @GetMapping(value = "/confirm") public ApiResponseModel<Traveler> confirmTraveler(@RequestHeader("uuid") String uuid) { return ApiResponseModel.<Traveler>builder() .code(HttpStatus.CONFLICT.value()) .msg(HttpStatus.CONFLICT.getReasonPhrase()) .result(travelerService.getTravelerByUuid(uuid)) .build(); } @PostMapping(value = "/register") public ApiResponseModel<Traveler> registerTraveler(@RequestHeader("uuid") String uuid, @Valid @RequestBody RegisterTravelerDto requestBody, BindingResult bindingResult) { if (bindingResult.hasErrors()) { throw new BadRequestException(); } try { TravelProperty.valueOf(requestBody.getProperty()); } catch (IllegalArgumentException e) { throw new BadRequestException("여행자 타입 enum값이 형식이 맞지 않습니다."); } return ApiResponseModel.<Traveler>builder() .code(HttpStatus.OK.value()) .msg(HttpStatus.OK.getReasonPhrase()) .result(travelerService.registerTraveler(requestBody, uuid)) .build(); } }
true
e657185984f4e7b108e78f9d09ee756c3468d2c3
Java
olivier741/schoolAlert
/src/main/java/com/tatsinktech/web/repository/ManageTableRepository.java
UTF-8
4,761
2.1875
2
[ "MIT" ]
permissive
/* * 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 com.tatsinktech.web.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author olivier.tatsinkou */ @Repository public class ManageTableRepository { @PersistenceUnit private EntityManagerFactory entityManagerFactory; @Transactional public void createTable(String tableName) { String s = "CREATE TABLE %s (MSISDN VARCHAR(100) NOT NULL UNIQUE)"; String sql = String.format(s, tableName.toLowerCase()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createNativeQuery(sql).executeUpdate(); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); System.out.println(sql); } @Transactional public void insertTable(String tableName, String msisdn) { String s = "INSERT INTO %s (MSISDN) VALUES ( %s )"; String sql = String.format(s, tableName.toLowerCase(), msisdn); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createNativeQuery(sql).executeUpdate(); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); } @Transactional public void updateTable(String tableName, String msisdn_old, String msisdn_new) { String s = "UPDATE %s SET msisdn = %s WHERE msisdn = %s "; String sql = String.format(s, tableName.toLowerCase(), msisdn_new, msisdn_old); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createNativeQuery(sql).executeUpdate(); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); } @Transactional public void deleteTable(String tableName, String msisdn) { String s = "DELETE FROM %s WHERE msisdn = %s "; String sql = String.format(s, tableName.toLowerCase(), msisdn); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createNativeQuery(sql).executeUpdate(); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); } @Transactional public void dropTable(String tableName) { String s = " DELETE FROM %s "; String sql = String.format(s, tableName.toLowerCase()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createNativeQuery(sql).executeUpdate(); entityManager.flush(); entityManager.getTransaction().commit(); entityManager.close(); } @Transactional public List<String> getTable(String tableName) { List<String> result = null; try { String s = "SELECT * FROM %s "; String sql = String.format(s, tableName.toLowerCase()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); result = entityManager.createNativeQuery(sql).getResultList(); entityManager.close(); } catch (Exception e) { } return result; } @Transactional public List<String> getTableByMsisdn(String tableName, String msisdn) { List<String> result = null; try { String s = "SELECT * FROM %s WHERE msisdn LIKE '%s'"; String sql = String.format(s, tableName.toLowerCase(), msisdn); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); result = entityManager.createNativeQuery(sql).getResultList(); entityManager.close(); } catch (Exception e) { } return result; } }
true
ca3287ed57d914e3226a0c3700a879bcf4d89429
Java
therajanmaurya/Github-Client
/app/src/main/java/opensource/github/android/client/data/GitHubInterceptor.java
UTF-8
1,116
2.21875
2
[]
no_license
package opensource.github.android.client.data; import java.io.IOException; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Request.Builder; import okhttp3.Response; public class GitHubInterceptor implements Interceptor { public static final String HEADER_ACCEPT = "Accept"; public static final String CLIENT_ID = "4a9df6f27b10c5ab8f43"; public static final String CLIENT_SECRET = "785c47918f4a8f04955f938f557bfe55064a882e"; public GitHubInterceptor() { } @Override public Response intercept(Chain chain) throws IOException { Request chianrequest = chain.request(); Builder builder = chianrequest.newBuilder(); HttpUrl originalHttpUrl = chianrequest.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("client_id", CLIENT_ID) .addQueryParameter("client_secret", CLIENT_SECRET) .build(); builder.url(url); builder.header(HEADER_ACCEPT, "application/vnd.github.v3+json"); Request request = builder.build(); return chain.proceed(request); } }
true
7daee31c7a83b1a7be10b8821d10caf3ea38ad17
Java
iantal/AndroidPermissions
/apks/banking_set2_qark/com.advantage.RaiffeisenBank/classes_dex2jar/com/bumptech/glide/load/resource/bitmap/ImageVideoBitmapDecoder.java
UTF-8
2,193
1.9375
2
[ "Apache-2.0" ]
permissive
package com.bumptech.glide.load.resource.bitmap; import android.graphics.Bitmap; import android.os.ParcelFileDescriptor; import android.util.Log; import com.bumptech.glide.load.ResourceDecoder; import com.bumptech.glide.load.engine.Resource; import com.bumptech.glide.load.model.ImageVideoWrapper; import java.io.IOException; import java.io.InputStream; public class ImageVideoBitmapDecoder implements ResourceDecoder<ImageVideoWrapper, Bitmap> { private static final String TAG = "ImageVideoDecoder"; private final ResourceDecoder<ParcelFileDescriptor, Bitmap> fileDescriptorDecoder; private final ResourceDecoder<InputStream, Bitmap> streamDecoder; public ImageVideoBitmapDecoder(ResourceDecoder<InputStream, Bitmap> paramResourceDecoder, ResourceDecoder<ParcelFileDescriptor, Bitmap> paramResourceDecoder1) { this.streamDecoder = paramResourceDecoder; this.fileDescriptorDecoder = paramResourceDecoder1; } public Resource<Bitmap> decode(ImageVideoWrapper paramImageVideoWrapper, int paramInt1, int paramInt2) throws IOException { InputStream localInputStream = paramImageVideoWrapper.getStream(); localObject = null; if (localInputStream != null) {} try { Resource localResource = this.streamDecoder.decode(localInputStream, paramInt1, paramInt2); localObject = localResource; } catch (IOException localIOException) { for (;;) { ParcelFileDescriptor localParcelFileDescriptor; boolean bool = Log.isLoggable("ImageVideoDecoder", 2); localObject = null; if (bool) { Log.v("ImageVideoDecoder", "Failed to load image from stream, trying FileDescriptor", localIOException); localObject = null; } } } if (localObject == null) { localParcelFileDescriptor = paramImageVideoWrapper.getFileDescriptor(); if (localParcelFileDescriptor != null) { localObject = this.fileDescriptorDecoder.decode(localParcelFileDescriptor, paramInt1, paramInt2); } } return localObject; } public String getId() { return "ImageVideoBitmapDecoder.com.bumptech.glide.load.resource.bitmap"; } }
true
5ba4a5e6d5420fe07b30b232853bfb982bbc1142
Java
TometoTom/MonkyGams
/MonkyGams/src/games/game/kitpvp/Kit.java
UTF-8
3,375
2.703125
3
[]
no_license
package games.game.kitpvp; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; public enum Kit { AGILE("Agile", "Rush", 15, "Right click with your sword to get 3x speed.", Material.FEATHER, true), SNEAK("Sneak", "Flash", 5, "Right click with your sword to flash to the place you're looking at.", Material.INK_SAC, true), EXPLOSIVE("Explosive", "Explosive Arrow", 15, "Left click with your bow to charge Explosive Arrow.", Material.TNT, true), ICE("Ice", "Freeze", 10, "Right click with your sword on a player to freeze them for 3 seconds.", Material.PACKED_ICE, true), FAT("Fat", "Stomp", 15, "Double jump to stomp the ground and damage players around you.", Material.CAKE, true), PUMPKIN("Pumpkin", "Pumpkin Throw", 10, "Use your pumpkin to temporarily blind people.", Material.PUMPKIN, true), GYMLAD("Gym Lad", "I'm Hench", 15, "Right click your sword to have no knockback.", Material.BONE, true), CLINTON("Hillary Clinton", "Pneumonia", 12, "Right click your sword on someone to give them pneumonia", Material.RED_BED, true), CAMERON("David Cameron", "Resign", 3, "Right click your sword to resign and let them get on with Brexit!", Material.DARK_OAK_DOOR, true), FARAGE("Nigel Farage", "Shoot the Immigrants", 12, "Hold right click on your sword to shoot immigrants out of your country.", Material.FIRE_CHARGE, true), KEEMSTAR("Keemstar", "Popcorn Gun", 12, "Hold right click on your sword to spread the news.", Material.CHAINMAIL_HELMET, true), KHAN("Sadiq Khan", "Night Tube", 12, "Right click on someone to travel using the night tube.", Material.TNT_MINECART, true), CORBYN("Jeremy Corbyn", "I Will Never Leave", 15, "Right click on your sword to avoid death by Cameron.", Material.BARRIER, true), HUNT("Jeremy Hunt", "I'm Selling the NHS", 15, "Right click on someone to get rid of their healthcare.", Material.POTION, true), JARVIS("Jarvis", "Network Ban", 1, "Right click on someone to network ban them!", Material.CARROT, true), JOHNSON("Boris Johnson", "I'm a big friendly buffoon", 17, "Right click on your sword to bounce around like a big friendly buffoon.", Material.ANVIL, true), MAY("Theresa May", "Brexit means Brexit", 12, "Right click your sword to go invisible and pretend Brexit doesn't exist.", Material.MAP, true), TRUMP("Donald Trump", "Build a Wall", 15, "Right click your sword to build a wall", Material.COBBLESTONE_WALL, true); private final String name; private final String skillName; private final int cooldown; private final String description; private final Material material; private final boolean enabled; Kit(String name, String skillName, int cooldown, String description, Material material, boolean enabled){ this.name = name; this.skillName = skillName; this.cooldown = cooldown; this.description = description; this.material = material; this.enabled = enabled; } public static HashMap<Player, Kit> kits = new HashMap<Player, Kit>(); public String getName(){ return name; } public String getSkillName(){ return ChatColor.GRAY + "" + ChatColor.BOLD + skillName + ChatColor.RESET + "" + ChatColor.GRAY; } public int getCooldown(){ return cooldown; } public String getDescription(){ return description; } public Material getMaterial(){ return material; } public boolean isEnabled(){ return enabled; } }
true
abaa956e39451924125f3df35365f6b8cb0a0509
Java
pedramkho/HearthStone
/src/ItemsAndAmulets/Amulets/GoldPendant.java
UTF-8
447
3.015625
3
[]
no_license
package ItemsAndAmulets.Amulets; import ItemsAndAmulets.Amulet; import Player.Player; public class GoldPendant extends Amulet { public GoldPendant() { super.price = 4000; super.name = "Gold Pendant"; super.details = "Increase Player’s Max HP by 1000."; } public void action(Player player){ player.MaxHP += 1000; } public void remove(Player player) { player.MaxHP -= 1000; } }
true
baf992baecf5e11fed3c34ef25001176ec204704
Java
ShingTse/owlsim-v3
/owlsim-services/src/main/java/org/monarchinitiative/owlsim/services/modules/MatcherMapModule.java
UTF-8
2,085
2.359375
2
[]
no_license
package org.monarchinitiative.owlsim.services.modules; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.monarchinitiative.owlsim.compute.matcher.ProfileMatcher; import com.google.common.reflect.ClassPath; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Provides; public class MatcherMapModule extends AbstractModule { private Logger LOG = Logger.getLogger(MatcherMapModule.class); // The package containing ProfileMatcher implementations private static final String matcherPackage = "org.monarchinitiative.owlsim.compute.matcher.impl"; @Override protected void configure() { } /*** * Gets of map of ProfileMatchers. * * <p> * A convenience method to obviate maintaining hard coded instances of * ProfileMatchers. <em>matcherPackage</em> is inspected for any * non-abstract class that implements ProfileMatcher and a map is created * between that ProfileMatcher's shortName and an instance of the matcher. * * <p> * <em>Note:</em> The class must be injectable by Guice. * * @param injector * @return A mapping of ProfileMatchers * @throws IOException */ @Provides Map<String, ProfileMatcher> getMatchers(Injector injector) throws IOException { ClassPath classpath = ClassPath.from(getClass().getClassLoader()); LOG.info("Fetchig classes from: " + classpath.getClass()); LOG.info("top level of :" + matcherPackage); Map<String, ProfileMatcher> matcherMap = new HashMap<>(); for (ClassPath.ClassInfo info : classpath.getTopLevelClasses(matcherPackage)) { Class<?> clazz = info.load(); LOG.info(" Adding: " + info + " class: " + clazz + " ISAB:" + Modifier.isAbstract(clazz.getModifiers())); if (!Modifier.isAbstract(clazz.getModifiers()) && ProfileMatcher.class.isAssignableFrom(info.load())) { ProfileMatcher matcher = (ProfileMatcher) injector.getInstance(clazz); matcherMap.put(matcher.getShortName(), matcher); } } return matcherMap; } }
true
cffcbf0221c3d7b1b6ea342b409e4e8a9b0a15bd
Java
kesharwanichirag/itech.github.io
/WEB-INF/src/controllers/users/profile/FollowersUsersListServlet.java
UTF-8
852
2.28125
2
[]
no_license
package controllers.users.profile; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import com.google.gson.Gson; import models.User; import models.UserFollower; public class FollowersUsersListServlet extends HttpServlet{ public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{ HttpSession session = request.getSession(); int userId = Integer.parseInt(request.getParameter("user_id")); ArrayList<UserFollower> list = UserFollower.followersUsersList(userId); Gson gson = new Gson(); String resp = gson.toJson(list); response.getWriter().write(resp); } }
true
164207e9f9d4e44dc9cb7ad176071e713d3f6b33
Java
13141358184/distributed-service
/hello-client/src/main/java/com/xiaoheiwu/service/hello_client/HelloClient.java
UTF-8
916
2.234375
2
[]
no_license
package com.xiaoheiwu.service.hello_client; import com.xiaoheiwu.service.client.services.ServiceFactory; import com.xiaoheiwu.service.common.component.ComponentProvider; import com.xiaoheiwu.service.hello_api.HelloAPI; public class HelloClient{ public static void main(String[] args) throws InterruptedException { ComponentProvider.startComponent(); HelloClient client=new HelloClient(); HelloAPI helloWorld=ServiceFactory.getInstance().getService(HelloAPI.class); Object result=helloWorld.hello("yuanxiaodong123"); System.out.println(result); // Thread.sleep(15000); // result=helloWorld.hello("yuanxiaodong123","wbd"); // System.out.println(result); // result=helloWorld.hello("yuanxiaodong123"); // System.out.println(result); // HelloWorld hw=ServiceFactory.getInstance().getService(HelloWorld.class); // result=hw.helloWorld("yuanxiaodong"); // System.out.println(result); } }
true
6300982235a311c90c52a097982c267bec58f62f
Java
zongyl/WEB
/src/main/java/com/longlong/beanutils/Bean1.java
UTF-8
353
2.203125
2
[]
no_license
/** * */ package com.longlong.beanutils; /** * @author zongyl * */ public class Bean1 { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
true
f24c2e1143d53df08493c75660d5b531ae44ec28
Java
illyric/freeMotherJavaKata
/src/test/java/FreeMotherJavaTest.java
UTF-8
1,935
3.109375
3
[]
no_license
import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class FreeMotherJavaTest { private FreeMotherJava freeMotherJava; @Before public void setUp() throws Exception { //Arrange freeMotherJava = new FreeMotherJava(); } @Test public void biggestTwoDigitNumber() { //Act int result = freeMotherJava.biggestDifferentDigitNumber(2); //Assert assertThat(result, is(98)); } @Test public void biggestThreeDigitNumber() { //Act int result = freeMotherJava.biggestDifferentDigitNumber(3); //Assert assertThat(result, is(987)); } @Test public void biggestFourDigitNumber() throws Exception { int result = freeMotherJava.biggestDifferentDigitNumber(4); assertThat(result, is(9876)); } @Test public void biggestSingleDigitNumber() throws Exception { int result = freeMotherJava.biggestDifferentDigitNumber(1); assertThat(result, is(9)); } @Test public void biggestFiveDigitNumber() throws Exception { int result = freeMotherJava.biggestDifferentDigitNumber(5); assertThat(result, is(98765)); } @Test public void rightToLeft12() throws Exception { int result = freeMotherJava.rightToLeft(12); assertThat(result, is(21)); } @Test public void rightToLeft65() throws Exception { int result = freeMotherJava.rightToLeft(65); assertThat(result, is(56)); } @Test public void rightToLeft987654() throws Exception { int result = freeMotherJava.rightToLeft(987654); assertThat(result, is(456789)); } @Test public void isSquareNumber() throws Exception { boolean result = freeMotherJava.isSquareNumber(4); assertThat(result, is(true)); } }
true
c5b5e30bd03a0b0ebf095b5d19f727dd81c9fbd5
Java
VlTrif/SeleniumLearningAllTasksFromSecond
/src/main/java/pages/PersonsPage.java
UTF-8
4,182
2.25
2
[]
no_license
package pages; //import com.sun.org.apache.xpath.internal.operations.String; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import steps.BaseSteps; import static org.junit.Assert.assertEquals; public class PersonsPage extends AbstractPage{ @FindBy(xpath = "//*[contains(text(),'Оформление')]") WebElement title; @FindBy(name = "insured0_surname") WebElement insSurname; @FindBy(name = "insured0_name") WebElement insName; @FindBy(name = "insured0_birthDate") WebElement insBirthDate; @FindBy(name = "surname") WebElement personSurname; @FindBy(name = "name") WebElement personName; @FindBy(name = "middlename") WebElement personMiddleName; @FindBy(name = "birthDate") WebElement personBirthDate; @FindBy(name = "passport_series") WebElement passSeries; @FindBy(name = "passport_number") WebElement passNumber; @FindBy(name = "issueDate") WebElement issueDate; @FindBy(name = "issuePlace") WebElement issuePlace; @FindBy(xpath = "//*[contains(text(),'Продолжить')]") public WebElement cntButton; public PersonsPage() { PageFactory.initElements(BaseSteps.getDriver(), this); (new WebDriverWait(BaseSteps.getDriver(), 10)) .until(ExpectedConditions.visibilityOf(title)); } /*protected void fillField(WebElement element, String value) { element.clear(); element.sendKeys(value); }*/ public void fillField(String fieldName, String value){ switch (fieldName){ case "Фамилия застрахованного": fillField(insSurname, value); break; case "Имя застрахованного": fillField(insName, value); break; case "Дата рождения застрахованного": fillField(insBirthDate, value); break; case "Фамилия": fillField(personSurname, value); break; case "Имя": fillField(personName, value); break; case "Отчество": fillField(personMiddleName, value); break; case "Дата рождения": fillField(personBirthDate, value); break; case "Серия паспорта": fillField(passSeries, value); break; case "Номер паспорта": fillField(passNumber, value); break; case "Дата выдачи": fillField(issueDate, value); break; case "Кем выдан": fillField(issuePlace, value); break; default: throw new AssertionError("Поле '"+fieldName+"' не объявлено на странице"); } } public void checkFieldErrorMessage(){ //String xpath = "//*[text()='"+field+"']/..//*[@class='validation-error']"; String actualValue = BaseSteps.getDriver().findElement(By.xpath("//div[contains(@ng-show,'tryNext && myForm.$invalid')]")).getText(); assertEquals("Заполнены не все обязательные поля",actualValue); //Assert.assertTrue(String.format("Получено значение [%s]. Ожидалось [%s]", actualValue, errorMessage), // actualValue.contains(errorMessage)); } /*public void checkError (String errorMessage){ String xpath = "//div[contains(@ng-show,'tryNext && myForm.$invalid')]"; //div[contains(@class,'b-form-center-pos b-form-error-message')]//*[contains(text(),'')]"; String actualValue = driver.findElement(By.xpath(xpath)).getText(); Assert.assertTrue(actualValue, actualValue.contains(errorMessage)); }*/ }
true
86b7ee24ce39ba2f45a678e5ca7b75de72f2a04c
Java
open-ssl/Diplom
/app/src/main/java/com/example/stanislavlukanov/td/Navigation_Menu_Fragments/DevRes/Tab1.java
UTF-8
12,962
1.765625
2
[]
no_license
package com.example.stanislavlukanov.td.Navigation_Menu_Fragments.DevRes; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.example.stanislavlukanov.td.R; import com.example.stanislavlukanov.td.SQL.SQL_MyDividerItemDecoration; import com.example.stanislavlukanov.td.SQL.SQL_RecyclerTouchListener; import com.example.stanislavlukanov.td.SQL.SQL_Tab1; import com.example.stanislavlukanov.td.SQL.SQL_Tab1Adapter; import com.example.stanislavlukanov.td.SQL.SQL_Tab1_DatabaseHelper; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class Tab1 extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; private Calendar mCurrentDate; SQL_Tab1Adapter mAdapter; List<SQL_Tab1> devsList = new ArrayList<>(); CoordinatorLayout coordinatorLayout; RecyclerView recyclerView; TextView noDevsView; SQL_Tab1_DatabaseHelper db; private OnFragmentInteractionListener mListener; public Tab1() { } public static Tab1 newInstance(String param1, String param2) { Tab1 fragment = new Tab1(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fr_dev_tab1, container, false); coordinatorLayout = v.findViewById(R.id.coordinator_tab1); recyclerView = v.findViewById(R.id.tab1_recycler); noDevsView = v.findViewById(R.id.empty_devs_view); AppCompatActivity activity = (AppCompatActivity) getActivity(); assert activity.getSupportActionBar() != null; FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab_tab1); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDevsDialog(false, null, -1); } }); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); db = new SQL_Tab1_DatabaseHelper(getContext()); devsList.addAll(db.getAll()); mAdapter = new SQL_Tab1Adapter(getContext(), devsList); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new SQL_MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL, 16)); recyclerView.setAdapter(mAdapter); toggleEmptyDevs(); recyclerView.addOnItemTouchListener(new SQL_RecyclerTouchListener(getContext(), recyclerView, new SQL_RecyclerTouchListener.ClickListener() { @Override public void onClick(View view, final int position) { } @Override public void onLongClick(View view, int position) { showActionsDialog(position); } })); } private void createDev(String name, String time, Calendar mCurrentDate){ int year = mCurrentDate.get(Calendar.YEAR); int month = mCurrentDate.get(Calendar.MONTH); int day = mCurrentDate.get(Calendar.DAY_OF_MONTH); long id = db.insertDev(name,time,year,month,day); SQL_Tab1 n = db.getDev(id); if(n != null){ devsList.add(0,n); mAdapter.notifyDataSetChanged(); toggleEmptyDevs(); } } private void updateDev(String name, String time, Calendar mCurrentDate, int position) { SQL_Tab1 n = devsList.get(position); int year = mCurrentDate.get(Calendar.YEAR); int month = mCurrentDate.get(Calendar.MONTH); int day = mCurrentDate.get(Calendar.DAY_OF_MONTH); n.setName(name); n.setTime(time); n.setDay(day); n.setMonth(month); n.setYear(year); db.updateDev(n); devsList.set(position, n); mAdapter.notifyItemChanged(position); toggleEmptyDevs(); } private void deleteDevs(int position) { db.deleteDev(devsList.get(position)); devsList.remove(position); mAdapter.notifyItemRemoved(position); toggleEmptyDevs(); } private void showActionsDialog(final int position) { CharSequence colors[] = new CharSequence[]{"Редактировать событие", "Удалить"}; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("Выберите действие"); builder.setItems(colors, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { showDevsDialog(true, devsList.get(position), position); } else { deleteDevs(position); } } }); builder.show(); } private void showDevsDialog(final boolean shouldUpdate, final SQL_Tab1 dev, final int position) { LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getContext()); View view = layoutInflaterAndroid.inflate(R.layout.sql_tab1_dialog, null); AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(getContext()); alertDialogBuilderUserInput.setView(view); final EditText inputDev = view.findViewById(R.id.etName_tab1); EditText inputTime = (EditText) view.findViewById(R.id.etTime_tab1); inputTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentDate = Calendar.getInstance(); int hour = mCurrentDate.get(Calendar.HOUR_OF_DAY); int minute = mCurrentDate.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), android.app.AlertDialog.THEME_HOLO_LIGHT, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String str = hourOfDay + ":" + minute; if(hourOfDay < 10){ if (minute < 10){ str = "0" + hourOfDay + ":" + "0" + minute; } else { str = "0" + hourOfDay + ":" + minute; } } inputTime.setText(str); mCurrentDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mCurrentDate.set(Calendar.MINUTE, minute); } }, hour ,minute, true); timePickerDialog.show(); } }); EditText inputCalendar = (EditText) view.findViewById(R.id.txtDateEntered); inputCalendar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // получили текущую дату mCurrentDate = Calendar.getInstance(); int year = mCurrentDate.get(Calendar.YEAR); int month = mCurrentDate.get(Calendar.MONTH); int day = mCurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { inputCalendar.setText(dayOfMonth+ "-" + (month+1) + "-" + year); mCurrentDate.set(year, month, dayOfMonth); } }, year, month, day); mDatePicker.show(); } }); TextView dialogTitle = view.findViewById(R.id.tab1_dialog_title); dialogTitle.setText(!shouldUpdate ? getString(R.string.msg_new_dev) : getString(R.string.lbl_edit_dev_title)); if (shouldUpdate && dev != null) { // место для восстановления данных при редактировании inputDev.setText(dev.getName()); inputTime.setText(dev.getTime()); int year = dev.getYear(); int month = dev.getMonth(); int day = dev.getDay(); inputCalendar.setText(day+ "-" + (month+1) + "-" + year); } alertDialogBuilderUserInput .setCancelable(false) .setPositiveButton(shouldUpdate ? "Изменить" : "Сохранить", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogBox, int id) { } }) .setNegativeButton("Отмена", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogBox, int id) { dialogBox.cancel(); } }); final AlertDialog alertDialog = alertDialogBuilderUserInput.create(); alertDialog.show(); alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(inputDev.getText().toString()) || TextUtils.isEmpty(inputCalendar.getText())) { Toast.makeText(getActivity(), "Введите данные!", Toast.LENGTH_SHORT).show(); return; } else { alertDialog.dismiss(); } if (shouldUpdate && dev != null) { updateDev(inputDev.getText().toString(), inputTime.getText().toString(), mCurrentDate, position); } else { createDev(inputDev.getText().toString(),inputTime.getText().toString(), mCurrentDate); } } }); } private void toggleEmptyDevs() { if (db.getDevsCount() > 0) { noDevsView.setVisibility(View.GONE); } else { noDevsView.setVisibility(View.VISIBLE); } } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
true
2b421b9c507dedbc9a2ba177394fda00905a08b1
Java
nachom96/EjerciciosHerencia
/src/ejer3/APP.java
UTF-8
223
2.3125
2
[]
no_license
package ejer3; public class APP { public static void main(String[] args) { // TODO Auto-generated method stub Circulo circ = new Circulo(1,2,2); System.out.println(circ.calcular_area()); } }
true
2918ca947b10451d51ae42e781f347652c41479b
Java
Muppallasrihari/User_Registration
/RegistrationLogin/src/test/java/com/sr/user/UserRepositoryTests.java
UTF-8
1,342
2.09375
2
[]
no_license
package com.sr.user; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.annotation.Rollback; @DataJpaTest @AutoConfigureTestDatabase(replace=Replace.NONE) @Rollback(false) public class UserRepositoryTests { @Autowired private UserRepository userRepo; @Autowired private TestEntityManager entityManager; @Test public void testCreateUser() { User user=new User(); user.setEmail("sri123@gmail.com"); user.setPassword("sri1723"); user.setFirstName("Srihari"); user.setLastName("Muppalla"); User savedUser=userRepo.save(user); User existUser=entityManager.find(User.class, savedUser.getId()); assertThat(existUser.getEmail()).isEqualTo(user.getEmail()); } @Test public void testFindUser() { String email="sri@gmail.com"; User user=userRepo.findUserByEmail(email); assertThat(user).isNotNull(); } }
true
85e278f6f9b3d6d671ba8a6ddd767dddf6e8f849
Java
subhasis-mohanty/repo5
/POMDemo/src/com/actitime/homeTest/HomeTest.java
UTF-8
284
1.765625
2
[]
no_license
package com.actitime.homeTest; import org.testng.annotations.Test; import com.actitime.genericlibrary.BaseClass; public class HomeTest extends BaseClass { @Test() public void homePageTest() { System.out.println("======WE ARE IN HOME PAGE NOW========"); } }
true
99fcaa3badaeb13a5efb7b5b5b0790a0565bdbc1
Java
samonysh/PeiNi2
/app/src/main/java/com/peini/peini2/LoginActivity.java
UTF-8
3,400
2.3125
2
[]
no_license
package com.peini.peini2; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { private String name=null; private String password=null; private EditText nameText; private EditText passwordText; private TextView registerButton; private Button loginButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login2); initViews(); registerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent registerIntent = new Intent(LoginActivity.this,RegisterActivity.class); name = nameText.getText().toString(); registerIntent.putExtra("registerName",name); startActivity(registerIntent); } }); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = nameText.getText().toString(); password = passwordText.getText().toString(); User loginUser = new User(name,password); SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString("name",name); editor.commit(); new LoginTask().execute(loginUser); } }); } private void initViews(){ nameText = (EditText) findViewById(R.id.loginName); passwordText = (EditText) findViewById(R.id.loginPassword); registerButton = (TextView) findViewById(R.id.loginRsgister2); loginButton = (Button) findViewById(R.id.loginLogin); SharedPreferences preferences = getSharedPreferences("user",Context.MODE_PRIVATE); nameText.setText(preferences.getString("name","")); } public class LoginTask extends AsyncTask<User,Void,Integer>{ @Override protected Integer doInBackground(User... params) { Integer result = UserService.login(params[0]); return result; } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); switch (integer) { case 1: Intent oldIntent = new Intent(LoginActivity.this,OldIndexActivity.class); startActivity(oldIntent); finish(); break; case 2: Intent youngIntent = new Intent(LoginActivity.this,YoungIndexActivity.class); startActivity(youngIntent); finish(); break; default: Toast.makeText(LoginActivity.this, "登录错误,请检查用户名与密码", Toast.LENGTH_SHORT).show(); break; } } } }
true
ff14f687824f809b1a6f3803ed0f23d2fc44f0e0
Java
Happy-sc/Doris-api
/admin/doris.admin.service.failover/src/main/java/com/alibaba/doris/admin/service/failover/node/check/NodeCheckManager.java
UTF-8
8,242
2.078125
2
[ "MIT", "LicenseRef-scancode-public-domain-disclaimer", "FSFAP", "Apache-2.0" ]
permissive
/** * Project: doris.admin.service.common-0.1.0-SNAPSHOT * * File Created at 2011-5-24 * $Id$ * * Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. * * This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Alibaba.com. */ package com.alibaba.doris.admin.service.failover.node.check; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.alibaba.doris.admin.service.common.Managerable; import com.alibaba.doris.admin.service.common.node.NodesManager; import com.alibaba.doris.client.net.Connection; import com.alibaba.doris.client.net.OperationFuture; import com.alibaba.doris.client.net.command.CheckCommand.CheckType; import com.alibaba.doris.client.net.command.CheckCommand.Type; import com.alibaba.doris.client.net.command.result.CheckResult; import com.alibaba.doris.common.StoreNode; /** * check the node status. * * @author mian.hem */ public class NodeCheckManager implements Managerable { private static NodeCheckManager instance = new NodeCheckManager(); private Map<String, NodeHealth> nodeHealthStatuses = new ConcurrentHashMap<String, NodeHealth>(); private static final Log log = LogFactory .getLog(NodeCheckManager.class); private ReentrantLock lock = new ReentrantLock(); private NodeCheckThread checkThread = null; private NodeCheckManager() { super(); checkThread = new NodeCheckThread(this); } public static NodeCheckManager getInstance() { return instance; } /** * Case 1: needRealAccessing == true <br/> * Check the node health status. This method will really invoke node if the * current cache indicates this node is OK for accessing real state. If * returns NG, then it's might be from cache. <br/> * Case 2: needRealAccessing == false<br/> * Get the node heal status from cache. */ public NodeHealth checkNode(StoreNode node, boolean needRealAccessing) { if (node == null) { return null; } lock.lock(); NodeHealth health = null; try { health = nodeHealthStatuses.get(node.getPhId()); if (needRealAccessing && health == NodeHealth.OK) { health = accessAndCacheResult(node); } } finally { lock.unlock(); } if (health == null) { health = accessAndCacheResult(node); } return health; } private NodeHealth accessAndCacheResult(StoreNode node) { NodeHealth health; health = verifyNodeAcess(node); //cache health result. nodeHealthStatuses.put(node.getPhId(), health); return health; } /** * Check the node health status. This method will really invoke node if the * current cache indicates this node is OK for accessing real state. If * returns NG, then it's might be from cache. */ public NodeHealth checkNode(StoreNode node) { return checkNode(node, true); } /** * Check the node health status. This method will really invoke node if the * current cache indicates this node is OK for accessing real state. If * returns NG, then it's might be from cache. */ public NodeHealth checkNode(String physicalId) { StoreNode storeNode = NodesManager.getInstance().getStoreNode(physicalId); return checkNode(storeNode); } /** * Check the node health status. This method will really invoke node if the * current cache indicates this node is OK for accessing real state. If * returns NG, then it's might be from cache. */ public NodeHealth checkNode(String physicalId, boolean needRealAccessing) { StoreNode storeNode = NodesManager.getInstance().getStoreNode(physicalId); return checkNode(storeNode, needRealAccessing); } public NodeHealth verifyNodeAcess(String physicalId) { StoreNode storeNode = NodesManager.getInstance().getStoreNode(physicalId); return verifyNodeAcess(storeNode); } public NodeHealth verifyNodeAcess(StoreNode node, Connection conn) { NodeHealth nodeHealth = NodeHealth.NG; try { Type checkType = null; switch (node.getSequence()) { case TEMP_SEQUENCE: // 临时节点 checkType = CheckType.CHECK_TEMP_NODE; break; case STANDBY_SEQUENCE: // 备用接地那 checkType = CheckType.CHECK_STANDBY_NODE; break; case UNUSE_SEQUENCE: // 待用节点 checkType = null; break; default: //正常(Data)节点 checkType = CheckType.CHECK_NORMAL_NODE; break; } OperationFuture<CheckResult> future = conn.check(checkType); CheckResult checkResult = null; try { checkResult = future.get(NodeCheckThread.nodeCheckTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("check failed for node :" + node.getPhId()); log.error(e.getMessage(), e); checkResult = null; } if (checkResult == null) { nodeHealth = NodeHealth.NG; if (checkResult == null) { log.warn("Check result is null for node :" + node.getPhId()); } } else if (checkResult.isSuccess()) { nodeHealth = NodeHealth.OK; } else { nodeHealth = NodeHealth.NG; log.warn("Check result is NG for node :" + node.getPhId() + ", Message:" + checkResult.getMessage()); } } catch (Exception e) { log.debug("fail to check node :" + node.getPhId(), e); updateNodeHealth(node, NodeHealth.NG); return NodeHealth.NG; } updateNodeHealth(node, nodeHealth); return nodeHealth; } /** * Make put and get invocation to node for it's health state. */ public NodeHealth verifyNodeAcess(StoreNode node) { if (node == null ) { return null; } try { Connection conn = NodesManager.getInstance().getNodeConnection(node); return verifyNodeAcess(node, conn); } catch (Exception e) { log.debug("fail to check node :" + node.getPhId(), e); updateNodeHealth(node, NodeHealth.NG); return NodeHealth.NG; } } public void updateNodeHealth(StoreNode node, NodeHealth nodeHealth) { lock.lock(); try { nodeHealthStatuses.put(node.getPhId(), nodeHealth); } finally { lock.unlock(); } } public void updateNodeHealth(String physicalId, NodeHealth nodeHealth) { lock.lock(); try { nodeHealthStatuses.put(physicalId, nodeHealth); } finally { lock.unlock(); } } /** * Returns node health snapshot of all nodes. */ public Map<String, NodeHealth> getNodeHealthStatuses() { return nodeHealthStatuses; } public void start() { checkThread.start(); } public void stop() { checkThread.over(); } }
true
8ab6b6e1797d406e2ecb7130d073b03a5958c44f
Java
EvanWn2015/AndroidEx
/fileupex/src/main/java/app/inspection/com/fileupex/MainActivity.java
UTF-8
13,220
1.960938
2
[]
no_license
package app.inspection.com.fileupex; import android.Manifest; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * 實作拍照取得File & 錄音取得File, * okHttp 實作 post FromData 上傳 file, * okHttp 實作 忽略 SSL 協議 * Android 6.0 權限 */ public class MainActivity extends AppCompatActivity { private final static String TAG = "MainActivity"; private Context context; private ImageView ivPic; private Display display; private Toolbar toolbar; private FloatingActionButton fab; // MENU private final static int UPLOAD_IMAGE_MENU_ID = 1; private final static int UPLOAD_MP3_MENU_ID = 2; // onActivityResult ResultId // private final static int REQUEST_TAKE_RECORD = 999999; private final static int REQUEST_TAKE_PIC = 0; private OkHttpGet okHttpGet = new OkHttpGet(); private OkHttpPost okHttpPost = new OkHttpPost(""); private File file, dir; // 錄音 private final static int RECORD_AUDIO_REQUEST_CODE = 669; private MediaRecorder mediaRecorder; private Dialog dialog; private TextView tv_path; private ImageView iv_start, iv_stop, iv_upload; private String path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; display = getWindowManager().getDefaultDisplay(); findViews(); setSupportActionBar(toolbar); // 6.0 權限 // if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) // != PackageManager.PERMISSION_GRANTED) { // // 申請 RECORD_AUDIO 權限 // ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_REQUEST_CODE); // } // 上傳圖片 fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (file != null) { String url = "https://172.16.0.106:443/IS-AS/sit/1/backend/check/upload_image?apsystem=SIT&user_id=1&check_result_id=308"; String file_name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date().getTime()) + ".jpg"; new RunUpLoad(url, file, "image_file", file_name, "image/png").start(); setTitle(" " + file_name); } else { Log.i(TAG, "file == null"); } } }); // 開始錄音 iv_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // android 6.0 錄音權限 if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { // 申請 RECORD_AUDIO 權限 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, RECORD_AUDIO_REQUEST_CODE); } dir = getRecordDir(); if (dir == null) { tv_path.setText("audio file does not exist"); return; } String name = String.format("%tY%<tm%<td_%<tH%<tM%<tS", new Date()) + ".mp3"; Log.i(TAG, "name : " + name); path = new File(dir, name).getPath(); if (recordAudio(path)) { tv_path.setText("Recording..."); iv_start.setEnabled(false); } // 觀察 dir size final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { Log.i(TAG, new File(path).length() + ""); handler.postDelayed(this, 500); } }); } }); // 停止錄音 iv_stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mediaRecorder != null) { mediaRecorder.stop(); mediaRecorder.release(); mediaRecorder = null; tv_path.setText("File saved: " + path); iv_start.setEnabled(true); dir = new File(path); Toast.makeText(context, dir.length() + "", Toast.LENGTH_SHORT).show(); } } }); // 上傳 錄音 file iv_upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "https://172.16.0.106:443/IS-AS/sit/1/backend/check/upload_audio?apsystem=SIT&user_id=1&check_result_id=308"; String file_name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date().getTime()) + ".mp3"; if (dir != null) { Log.i(TAG, "dir != null"); new RunUpLoad(url, dir, "audio_file", file_name, "audio/mp3").start(); } else { Log.i(TAG, "dir == null"); } } }); } public void findViews() { toolbar = (Toolbar) findViewById(R.id.toolbar); fab = (FloatingActionButton) findViewById(R.id.fab); ivPic = (ImageView) findViewById(R.id.ivPic); // 錄音 dialog dialog = new Dialog(context); LayoutInflater inflater = getLayoutInflater(); inflater.inflate(R.layout.dialog_record, null); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.width = (int) (display.getWidth() * 0.8); params.height = display.getHeight() / 3; dialog.addContentView(inflater.inflate(R.layout.dialog_record, null), params); tv_path = (TextView) dialog.findViewById(R.id.tv_path); iv_start = (ImageView) dialog.findViewById(R.id.iv_start); iv_stop = (ImageView) dialog.findViewById(R.id.iv_stop); iv_upload = (ImageView) dialog.findViewById(R.id.iv_upload); } private boolean mediaMounted() { String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED); } private File getRecordDir() { if (!mediaMounted()) { return null; } return getExternalFilesDir(Environment.DIRECTORY_MUSIC); } // 錄音相關設定 private boolean recordAudio(String path) { if (mediaRecorder == null) { mediaRecorder = new MediaRecorder(); } else { mediaRecorder.reset(); } try { // 指定錄音來源 (MIC為麥克風) mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 指定錄音檔輸出格式 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 指定錄音編碼格式 mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 指定錄音檔存放位置 mediaRecorder.setOutputFile(path); mediaRecorder.prepare(); mediaRecorder.start(); } catch (Exception e) { Log.e(TAG, e.toString()); return false; } return true; } // android 6.0 權限 @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); doNext(requestCode, grantResults); } private void doNext(int requestCode, int[] grantResults) { if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted } else { // Permission Denied } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_TAKE_PIC: Log.i(TAG, file.getPath() + ""); Bitmap bitmapPic = BitmapFactory.decodeFile(file.getPath()); final int maxSize = 1024; //dp int outWidth; int outHeight; int inWidth = bitmapPic.getWidth(); int inHeight = bitmapPic.getHeight(); if (inWidth > inHeight) { outWidth = maxSize; outHeight = (inHeight * maxSize) / inWidth; } else { outHeight = maxSize; outWidth = (inWidth * maxSize) / inHeight; } bitmapPic = Bitmap.createScaledBitmap(bitmapPic, outWidth, outHeight, false); ivPic.setImageBitmap(bitmapPic); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // bitmapPic.compress(Bitmap.CompressFormat.JPEG, 100, baos); // // pic = baos.toByteArray(); break; case 333: Log.i(TAG, file.getPath() + ""); break; } } else { Log.i(TAG, "resultCode != OK"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // getMenuInflater().inflate(R.menu.menu_main, menu); menu.add(Menu.NONE, UPLOAD_IMAGE_MENU_ID, Menu.NONE, "Upload Image"); menu.add(Menu.NONE, UPLOAD_MP3_MENU_ID, Menu.NONE, "Upload mp3"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case UPLOAD_IMAGE_MENU_ID: Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); file = new File(file, "upload_image.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); if (isIntentAvailable(this, intent)) { startActivityForResult(intent, REQUEST_TAKE_PIC); } else { Toast.makeText(this, "", Toast.LENGTH_SHORT).show(); } break; case UPLOAD_MP3_MENU_ID: dialog.show(); break; } return super.onOptionsItemSelected(item); } public boolean isIntentAvailable(Context context, Intent intent) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } // UpLoad Thread class RunUpLoad extends Thread { String url; String json; File file; String file_key, file_name, file_type; RunUpLoad(String url, File file, String file_key, String file_name, String file_type) { this.url = url; this.file = file; this.file_key = file_key; this.file_name = file_name; this.file_type = file_type; } Runnable r = new Runnable() { @Override public void run() { } }; @Override public void run() { Log.i(TAG, "Thread In"); try { json = okHttpPost.postFile(url, file, file_key, file_name, file_type); Log.i(TAG, json); } catch (Exception e) { Log.i(TAG, e.getMessage()); } } } }
true
82df83c403135fcb2df4310cb2cb09d716a91fa2
Java
Dmitryyyyo/java_1_tuesday_2020_online
/src/main/java/student_aleksandra_maksimovic/lesson_5/level_4/Task27.java
UTF-8
924
3.46875
3
[]
no_license
package student_aleksandra_maksimovic.lesson_5.level_4; import java.util.Random; /* - создайте массив произвольной длины - заполните массив случайными числами - распечатайте на консоль все элементы массива - найдите наибольшее число в массиве и выведети его на консоль. */ public class Task27 { public static void main(String[] args) { int[] arr = new int[8]; Random random = new Random(); for (int i = 0; i < arr.length; i++) { arr[i] = random.nextInt(70); System.out.println("[" + i + "] = " + arr[i]); } int max = arr[0]; for (int element : arr) { if (element > max) { max = element; } } System.out.println("Max = " + max); } }
true
f4b2dc27165a95557c6699c61465ea1526f74a93
Java
hetianlong0/hookTest
/hookTest/mylibrary/src/com/lingcloud/apptrace/sdk/TaskQueue.java
UTF-8
877
2.734375
3
[]
no_license
package com.lingcloud.apptrace.sdk; import java.util.concurrent.LinkedBlockingQueue; public class TaskQueue { private LinkedBlockingQueue<String> _queue = new LinkedBlockingQueue<String>(); private static class SingletonHolder { static final TaskQueue instance = new TaskQueue(); } /** * Returns the DclingCloudAgent singleton. */ public static TaskQueue getInstance() { return SingletonHolder.instance; } public void addTask(String task) { try { _queue.put(task); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String takeTask() { String ret = null; try { ret = _queue.take(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ret; } public int getCount() { int count = _queue.size(); return count; } }
true
2af2ca89c727e0cd0e5bd072820651028b17b3e5
Java
Namami1011/Onilne-Fee-Payment
/FMS/src/com/project/servlet/DelStudad.java
UTF-8
724
2.109375
2
[]
no_license
package com.project.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.project.db.StudDb; /** * Servlet implementation class DelStudad */ @WebServlet("/DelStudad") public class DelStudad extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String srollno=request.getParameter("rollno"); int rollno=Integer.parseInt(srollno); StudDb.delete(rollno); response.sendRedirect("ViewStudad"); } }
true
946ac7f145f53ca0723e6520d9ccee97b0f7a3e3
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_06c2c9377ac6e5f1ed8ae49810ad5d4dc910da86/UnbindAction/2_06c2c9377ac6e5f1ed8ae49810ad5d4dc910da86_UnbindAction_s.java
UTF-8
15,684
1.640625
2
[]
no_license
package com.chinarewards.qqgbvpn.mgmtui.struts.action; import java.io.File; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.configuration.Configuration; import org.apache.struts2.StrutsStatics; import com.chinarewards.qqgbvpn.core.mail.MailService; import com.chinarewards.qqgbvpn.domain.Agent; import com.chinarewards.qqgbvpn.domain.PageInfo; import com.chinarewards.qqgbvpn.domain.Pos; import com.chinarewards.qqgbvpn.domain.ReturnNote; import com.chinarewards.qqgbvpn.mgmtui.exception.SaveDBException; import com.chinarewards.qqgbvpn.mgmtui.exception.UnUseableRNException; import com.chinarewards.qqgbvpn.mgmtui.logic.GroupBuyingUnbindManager; import com.chinarewards.qqgbvpn.mgmtui.struts.BaseAction; import com.chinarewards.qqgbvpn.mgmtui.vo.ReturnNoteInfo; import com.chinarewards.qqgbvpn.qqapi.exception.MD5Exception; import com.chinarewards.qqgbvpn.qqapi.exception.ParseXMLException; import com.chinarewards.qqgbvpn.qqapi.exception.SendPostTimeOutException; import com.chinarewards.utils.StringUtil; import com.opensymphony.xwork2.ActionContext; /** * pos unbind action * * @author iori * */ public class UnbindAction extends BaseAction { private static final long serialVersionUID = -4872248136823406437L; private static final int initPageSize = 10; private GroupBuyingUnbindManager groupBuyingUnbindMgr; private MailService mailService; protected Configuration configuration; private HttpServletRequest request; private Agent agent; private String agentId; private String agentEmail; private PageInfo pageInfo; private String posIds; private String posId; private String rnId; private String rnNum; private String status; private Date rnTime; private Integer posCount; private String inviteCode; private String agentName; private String posCondition; private List<Pos> posList; private List<Agent> agentList; private String isAgent; private Date sendTime; private String passTime; private ReturnNoteInfo rnInfo; private String errorMsg; private String successMsg; private GroupBuyingUnbindManager getGroupBuyingUnbindManager() { groupBuyingUnbindMgr = super.getInstance(GroupBuyingUnbindManager.class); return groupBuyingUnbindMgr; } private MailService getMailService() { mailService = super.getInstance(MailService.class); return mailService; } private Configuration getConfiguration() { configuration = super.getInstance(Configuration.class); return configuration; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPassTime() { return passTime; } public void setPassTime(String passTime) { this.passTime = passTime; } public Integer getPosCount() { return posCount; } public void setPosCount(Integer posCount) { this.posCount = posCount; } public String getIsAgent() { return isAgent; } public void setIsAgent(String isAgent) { this.isAgent = isAgent; } public Date getRnTime() { return rnTime; } public void setRnTime(Date rnTime) { this.rnTime = rnTime; } public ReturnNoteInfo getRnInfo() { return rnInfo; } public void setRnInfo(ReturnNoteInfo rnInfo) { this.rnInfo = rnInfo; } public String getInviteCode() { return inviteCode; } public void setInviteCode(String inviteCode) { this.inviteCode = inviteCode; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getRnNum() { return rnNum; } public void setRnNum(String rnNum) { this.rnNum = rnNum; } public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId; } public List<Agent> getAgentList() { return agentList; } public void setAgentList(List<Agent> agentList) { this.agentList = agentList; } public String getAgentEmail() { return agentEmail; } public void setAgentEmail(String agentEmail) { this.agentEmail = agentEmail; } public String getSuccessMsg() { return successMsg; } public void setSuccessMsg(String successMsg) { this.successMsg = successMsg; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getPosId() { return posId; } public void setPosId(String posId) { this.posId = posId; } public List<Pos> getPosList() { return posList; } public void setPosList(List<Pos> posList) { this.posList = posList; } public String getPosCondition() { return posCondition; } public void setPosCondition(String posCondition) { this.posCondition = posCondition; } public String getAgentName() { return agentName; } public void setAgentName(String agentName) { this.agentName = agentName; } public String getRnId() { return rnId; } public void setRnId(String rnId) { this.rnId = rnId; } public String getPosIds() { return posIds; } public void setPosIds(String posIds) { this.posIds = posIds; } public PageInfo getPageInfo() { return pageInfo; } public void setPageInfo(PageInfo pageInfo) { this.pageInfo = pageInfo; } public Agent getAgent() { return agent; } public void setAgent(Agent agent) { this.agent = agent; } @Override public String execute() { agent = new Agent(); pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); return SUCCESS; } public String search() { posIds = ""; if (!StringUtil.isEmptyString(agentName)) { Agent a = getGroupBuyingUnbindManager().getAgentByName(agentName.trim()); if (a != null) { pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); pageInfo = getGroupBuyingUnbindManager().getPosByAgentId(pageInfo, a.getId()); this.setAgentId(a.getId()); this.setAgent(a); } else { //这里应该报找不到的提示 this.errorMsg = "第三方信息找不到!"; } } return SUCCESS; } public String request() { posIds = ""; if (!StringUtil.isEmptyString(inviteCode)) { Agent a = getGroupBuyingUnbindManager().getAgentByInviteCode(inviteCode.trim()); if (a != null) { log.debug("a.getId() : {}",a.getId()); pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); pageInfo = getGroupBuyingUnbindManager().getPosByAgentId(pageInfo, a.getId()); List<Pos> posList = pageInfo.getItems(); for (Pos p : posList) { log.debug("p.getDstatus() : {}",p.getDstatus()); } this.setAgentId(a.getId()); this.setAgentName(a.getName()); this.setAgent(a); } else { //这里应该报找不到的提示 this.errorMsg = "无可用邀请!"; } } return SUCCESS; } public String goPage() { if (pageInfo == null) { pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); } pageInfo = getGroupBuyingUnbindManager().getPosByAgentId(pageInfo, this.getAgentId().trim()); return SUCCESS; } public String createInvite() { if (!StringUtil.isEmptyString(this.getAgentId())) { //生成邀请单 String inviteCode = getGroupBuyingUnbindManager().createInviteCode(this.getAgentId().trim()); if (inviteCode != null) { //发送邮件 String path = getInviteEmailPath(inviteCode); String[] toAdds = {this.getAgentEmail()}; String subject = "邀请填写申请表"; Object[] params = {path}; try { getMailService().sendMail(toAdds, null, subject, "/mailtemplate/createInviteMailTemplate" , "createInvite", params); } catch (AddressException e) { this.errorMsg = "邮件地址为空,请确认地址是否正确后重试或联系管理员!"; return ERROR; } catch (MessagingException e) { this.errorMsg = "邮件地址有误,发送失败,请确认地址是否正确后重试或联系管理员!"; return ERROR; } this.setAgentName(this.getAgentName()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); this.setPassTime(sdf.format(new Date())); return SUCCESS; } } //这里应该报第三方不能为空的提示 this.errorMsg = "第三方信息找不到!"; return ERROR; } public String confirmRnNumber() throws SaveDBException { if (inviteCode == null) { inviteCode = ""; } if (posIds != null && !"".equals(posIds.trim())) { List<String> posList = splitPosIds(posIds.trim()); ReturnNote rn = null; String errInfo = ""; try { rn = getGroupBuyingUnbindManager().confirmReturnNote( this.getAgentId(), inviteCode.trim(), posList); } catch (UnUseableRNException e1) { errInfo = e1.getMessage(); } if (rn != null) { //受邀者填写完后发邮件给我方 if (!StringUtil.isEmptyString(inviteCode)) { String[] toAdds = {getConfiguration().getString("company.email")}; String subject = "第三方成功填写申请表"; String path = getRnDetailPath(rn.getId()); Object[] params = {this.getAgentName(),posList.size(),path}; try { getMailService().sendMail(toAdds, null, subject, "/mailtemplate/confirmRnNumberMailTemplate" , "confirmRnNumber", params); } catch (Throwable e) { } this.setIsAgent("true"); } this.setPosCount(splitPosIds(posIds.trim()).size()); this.setRnId(rn.getId()); this.setRnNum(rn.getRnNumber()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); this.setPassTime(sdf.format(rn.getCreateDate())); return SUCCESS; }else { this.errorMsg = "第三方信息找不到!"; } } else { // 这里应该报POS机不能为空的提示 this.errorMsg = "POS机信息找不到!"; } return ERROR; } public String confirmSuccess() { return SUCCESS; } public String unbindSuccess() { return SUCCESS; } public String confirmAllRnNumber() throws SaveDBException { if (!StringUtil.isEmptyString(agentId)) { ReturnNoteInfo rnInfo = getGroupBuyingUnbindManager().confirmAllReturnNote(agentId.trim()); if (rnInfo != null) { this.setPosCount(rnInfo.getPosList() != null ? rnInfo.getPosList().size() : 0); this.setRnId(rnInfo.getRn().getId()); this.setRnNum(rnInfo.getRn().getRnNumber()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); this.setPassTime(sdf.format(rnInfo.getRn().getCreateDate())); return SUCCESS; } } this.errorMsg = "第三方信息找不到!"; return ERROR; } public String posSearch() { if (!StringUtil.isEmptyString(posCondition)) { posList = getGroupBuyingUnbindManager().getPosByPosInfo(posCondition.trim()); if (posList == null || posList.size() == 0) { this.errorMsg = "POS机信息找不到!"; } } return SUCCESS; } public String unbind(){ if (!StringUtil.isEmptyString(posId)) { HashMap<String, Object> params = new HashMap<String, Object>(); params.put("posId", new String[] { posId.trim() }); params.put("key", getConfiguration().getString("txserver.key")); try { HashMap<String, Object> result = getGroupBuyingUnbindManager().groupBuyingUnbind(params); String resultCode = (String) result.get("resultCode"); if ("0".equals(resultCode)) { this.successMsg = posId + "解绑成功!"; } else { switch (Integer.valueOf(resultCode)) { case -1: this.errorMsg = "服务器繁忙!"; break; case -2: this.errorMsg = "MD5校验失败!"; break; case -3: this.errorMsg = "没有权限!"; break; default: this.errorMsg = "未知错误!"; break; } } } catch (MD5Exception e) { this.errorMsg = "生成MD5校验位出错!"; e.printStackTrace(); } catch (ParseXMLException e) { this.errorMsg = "解析XML出错!"; e.printStackTrace(); } catch (SendPostTimeOutException e) { this.errorMsg = "POST连接出错!"; e.printStackTrace(); } catch (SaveDBException e) { this.errorMsg = "后台保存数据库出错!"; e.printStackTrace(); } } return SUCCESS; } public String sendURL() { if (agentName == null) { agentName = ""; } List<Agent> list = getGroupBuyingUnbindManager().getAgentLikeName(agentName.trim()); if (list != null && list.size() > 0) { this.setAgentList(list); } else { //这里应该报找不到的提示 this.errorMsg = "第三方机信息找不到!"; } return SUCCESS; } public String sendURLSuccess() { return SUCCESS; } public String getReturnNoteList() { if (rnNum == null) { rnNum = ""; } if (status == null) { status = ""; } pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); pageInfo = getGroupBuyingUnbindManager().getReturnNoteLikeRnNumber(rnNum.trim(), status.trim(), pageInfo); return SUCCESS; } public String goPageForRnList() { if (rnNum == null) { rnNum = ""; } if (pageInfo == null) { pageInfo = new PageInfo(); pageInfo.setPageId(1); pageInfo.setPageSize(initPageSize); } pageInfo = getGroupBuyingUnbindManager().getReturnNoteLikeRnNumber(rnNum.trim(), status.trim(), pageInfo); return SUCCESS; } public String getReturnNoteInfo() { if (!StringUtil.isEmptyString(rnId)) { rnInfo = getGroupBuyingUnbindManager().getReturnNoteInfoByRnId(rnId.trim()); } return SUCCESS; } protected List<String> splitPosIds(String ids) { return Arrays.asList(ids.split(",")); } private String getInviteEmailPath(String inviteCode) { String path = getRequest().getRequestURL().toString(); String ctx = getRequest().getContextPath(); path = path.substring(0, path.indexOf(ctx)) + ctx + "/returnnote/request?inviteCode=" + inviteCode; return path; } private String getRnDetailPath(String rnId) { String path = getRequest().getRequestURL().toString(); String ctx = getRequest().getContextPath(); path = path.substring(0, path.indexOf(ctx)) + ctx + "/unbind/getReturnNoteInfo?rnId=" + rnId; return path; } private HttpServletRequest getRequest() { if (request == null) { request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST); } return request; } }
true