blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a47b40d57f176d432e4f68a3dbded675ff5ca8a5 | 20,529,943,734,365 | 583da26791b819e6078bc053c9ffad02e11f291a | /core/src/net/mostlyoriginal/game/component/buildings/ResourceNode.java | 6382402c879733466e3fcaf747f3e6371687a3cf | [
"MIT"
]
| permissive | DaanVanYperen/ns2-scc-profiler | https://github.com/DaanVanYperen/ns2-scc-profiler | 4d900d3218ad4f63c59227d51904bd315d81295a | d046d7255c71c97a9a334b678516c35e3fd9614e | refs/heads/master | 2020-05-19T09:02:02.558000 | 2015-01-31T15:20:03 | 2015-01-31T15:20:03 | 28,547,917 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.mostlyoriginal.game.component.buildings;
import com.artemis.Component;
/**
* @author Daan van Yperen
*/
public class ResourceNode extends Component {
}
| UTF-8 | Java | 168 | java | ResourceNode.java | Java | [
{
"context": "gs;\n\nimport com.artemis.Component;\n\n/**\n * @author Daan van Yperen\n */\npublic class ResourceNode extends Component {",
"end": 115,
"score": 0.9998571276664734,
"start": 100,
"tag": "NAME",
"value": "Daan van Yperen"
}
]
| null | []
| package net.mostlyoriginal.game.component.buildings;
import com.artemis.Component;
/**
* @author <NAME>
*/
public class ResourceNode extends Component {
}
| 159 | 0.767857 | 0.767857 | 9 | 17.666666 | 19.595919 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 2 |
a33901417e4a92f7cfeda1ff8c6a46fa904d8077 | 23,596,550,393,394 | 02c17c0c5f865639f086624baa5f999a1fff487d | /src/com/wangyang/dao/IYbUserDao.java | f06262d7e61a7dcfef53c8a2a379a11350a03fb8 | []
| no_license | wangyang1749/classtable | https://github.com/wangyang1749/classtable | b6febf5634fd64518bdf2239ba3d9b9baac73548 | c7e046d13a2edff35ca1d51b17c17fcf35294fd3 | refs/heads/master | 2020-03-28T10:39:23.582000 | 2018-09-10T09:33:19 | 2018-09-10T09:33:19 | 148,130,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wangyang.dao;
import com.wangyang.model.Pager;
import com.wangyang.model.YbUser;
public interface IYbUserDao {
void add(YbUser user);
Pager<YbUser> find(String condition,int pagesize,int currentpage);
YbUser load(int id);
void type(int id,int type);
void state(int id,int state);
}
| UTF-8 | Java | 301 | java | IYbUserDao.java | Java | []
| null | []
| package com.wangyang.dao;
import com.wangyang.model.Pager;
import com.wangyang.model.YbUser;
public interface IYbUserDao {
void add(YbUser user);
Pager<YbUser> find(String condition,int pagesize,int currentpage);
YbUser load(int id);
void type(int id,int type);
void state(int id,int state);
}
| 301 | 0.76412 | 0.76412 | 12 | 24.083334 | 17.708088 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 2 |
7fa6a1c585e544a788cceedcd1604edbab7432ec | 18,966,575,647,628 | 484fbbd022d623eb0ffadd42649a3b7601ab0855 | /kongcv/src/com/kongcv/global/LocationInfo.java | a19d910acb59a87965aa5d6cdfa8609ff80e2a9b | []
| no_license | kongcv/kongcv_android | https://github.com/kongcv/kongcv_android | 56a1fb1bc57f3a20dc7f714f46e404864b3283b1 | b1134effb0761a25800ec6a83644f43b8af094ec | refs/heads/master | 2021-01-10T08:32:42.488000 | 2016-04-11T10:37:00 | 2016-04-11T10:37:00 | 54,869,366 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright 2016 aTool.org
*/
package com.kongcv.global;
import java.io.Serializable;
/**
* Auto-generated: 2016-01-07 10:18:55
*
* @author aTool.org (i@aTool.org)
* @website http://www.atool.org/json2javabean.php
*/
public class LocationInfo implements Serializable{
private static final long serialVersionUID = 3593573094445487940L;
private String __type;
private double latitude;
private double longitude;
public void set_type(String _type) {
this.__type = _type;
}
public String get_type() {
return __type;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLatitude() {
return latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLongitude() {
return longitude;
}
} | UTF-8 | Java | 901 | java | LocationInfo.java | Java | [
{
"context": " Auto-generated: 2016-01-07 10:18:55\n *\n * @author aTool.org (i@aTool.org)\n * @website http://www.atool.org/js",
"end": 163,
"score": 0.8270072937011719,
"start": 154,
"tag": "EMAIL",
"value": "aTool.org"
},
{
"context": "ted: 2016-01-07 10:18:55\n *\n * @author aTool.org (i@aTool.org)\n * @website http://www.atool.org/json2javabean.p",
"end": 176,
"score": 0.9999158978462219,
"start": 165,
"tag": "EMAIL",
"value": "i@aTool.org"
}
]
| null | []
| /**
* Copyright 2016 aTool.org
*/
package com.kongcv.global;
import java.io.Serializable;
/**
* Auto-generated: 2016-01-07 10:18:55
*
* @author <EMAIL> (<EMAIL>)
* @website http://www.atool.org/json2javabean.php
*/
public class LocationInfo implements Serializable{
private static final long serialVersionUID = 3593573094445487940L;
private String __type;
private double latitude;
private double longitude;
public void set_type(String _type) {
this.__type = _type;
}
public String get_type() {
return __type;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLatitude() {
return latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLongitude() {
return longitude;
}
} | 895 | 0.63929 | 0.597114 | 41 | 21 | 17.951153 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.341463 | false | false | 2 |
20aa0bb31ea0086681c0e3330e4148d3b2038b56 | 1,125,281,488,625 | 9aa8f7174f402cdff93da7d216c88540f79f7d8e | /Spring/ClinicManagement/src/com/ust/model/Login.java | 86c6ec12f27afdbecb23786124da58f4d5724589 | []
| no_license | nikhilrainz/Clinic-Management | https://github.com/nikhilrainz/Clinic-Management | f3a071cd540ba1bae7ac799c63b57d83a8c3f8a3 | 0ab41e2b87742794b55d9c4ab87535dd27737c18 | refs/heads/master | 2023-05-10T23:58:46.911000 | 2019-09-23T07:45:06 | 2019-09-23T07:45:06 | 209,997,219 | 0 | 0 | null | false | 2023-05-06T20:17:52 | 2019-09-21T14:14:47 | 2019-09-23T07:45:23 | 2023-05-06T20:17:50 | 45,702 | 0 | 0 | 7 | Java | false | false | package com.ust.model;
import java.util.Date;
public class Login {
private int sId;
private int roleId;
private String sName;
private Date sDOB;
private String sGender;
private String sAddr;
private String sExp;
private String sPhNo;
private String sEmail;
private String username;
private String password;
private String isActiveS;
private Date createdDateS;
public Login() {
super();
// TODO Auto-generated constructor stub
}
public Login(int sId, int roleId, String sName, Date sDOB, String sGender,
String sAddr, String sExp, String sPhNo, String sEmail,
String username, String password, String isActiveS,
Date createdDateS) {
super();
this.sId = sId;
this.roleId = roleId;
this.sName = sName;
this.sDOB = sDOB;
this.sGender = sGender;
this.sAddr = sAddr;
this.sExp = sExp;
this.sPhNo = sPhNo;
this.sEmail = sEmail;
this.username = username;
this.password = password;
this.isActiveS = isActiveS;
this.createdDateS = createdDateS;
}
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public Date getsDOB() {
return sDOB;
}
public void setsDOB(Date sDOB) {
this.sDOB = sDOB;
}
public String getsGender() {
return sGender;
}
public void setsGender(String sGender) {
this.sGender = sGender;
}
public String getsAddr() {
return sAddr;
}
public void setsAddr(String sAddr) {
this.sAddr = sAddr;
}
public String getsExp() {
return sExp;
}
public void setsExp(String sExp) {
this.sExp = sExp;
}
public String getsPhNo() {
return sPhNo;
}
public void setsPhNo(String sPhNo) {
this.sPhNo = sPhNo;
}
public String getsEmail() {
return sEmail;
}
public void setsEmail(String sEmail) {
this.sEmail = sEmail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIsActiveS() {
return isActiveS;
}
public void setIsActiveS(String isActiveS) {
this.isActiveS = isActiveS;
}
public Date getCreatedDateS() {
return createdDateS;
}
public void setCreatedDateS(Date createdDateS) {
this.createdDateS = createdDateS;
}
}
| UTF-8 | Java | 2,571 | java | Login.java | Java | [
{
"context": ".sId = sId;\n\t\tthis.roleId = roleId;\n\t\tthis.sName = sName;\n\t\tthis.sDOB = sDOB;\n\t\tthis.sGender = sGender",
"end": 772,
"score": 0.6983197331428528,
"start": 771,
"tag": "NAME",
"value": "s"
},
{
"context": "= sPhNo;\n\t\tthis.sEmail = sEmail;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.isActiveS = i",
"end": 938,
"score": 0.9994186758995056,
"start": 930,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ail;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tthis.isActiveS = isActiveS;\n\t\tthis.createdDate",
"end": 966,
"score": 0.9923786520957947,
"start": 958,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "sEmail;\n\t}\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\tpublic void setUsername(String username) {\n\t",
"end": 2059,
"score": 0.9919415712356567,
"start": 2051,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\tpublic String getPassword() {\n\t\treturn passw",
"end": 2134,
"score": 0.9954198002815247,
"start": 2126,
"tag": "USERNAME",
"value": "username"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\tpublic String getIsActiveS() {\n\t\treturn isAc",
"end": 2262,
"score": 0.9930473566055298,
"start": 2254,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.ust.model;
import java.util.Date;
public class Login {
private int sId;
private int roleId;
private String sName;
private Date sDOB;
private String sGender;
private String sAddr;
private String sExp;
private String sPhNo;
private String sEmail;
private String username;
private String password;
private String isActiveS;
private Date createdDateS;
public Login() {
super();
// TODO Auto-generated constructor stub
}
public Login(int sId, int roleId, String sName, Date sDOB, String sGender,
String sAddr, String sExp, String sPhNo, String sEmail,
String username, String password, String isActiveS,
Date createdDateS) {
super();
this.sId = sId;
this.roleId = roleId;
this.sName = sName;
this.sDOB = sDOB;
this.sGender = sGender;
this.sAddr = sAddr;
this.sExp = sExp;
this.sPhNo = sPhNo;
this.sEmail = sEmail;
this.username = username;
this.password = <PASSWORD>;
this.isActiveS = isActiveS;
this.createdDateS = createdDateS;
}
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
public Date getsDOB() {
return sDOB;
}
public void setsDOB(Date sDOB) {
this.sDOB = sDOB;
}
public String getsGender() {
return sGender;
}
public void setsGender(String sGender) {
this.sGender = sGender;
}
public String getsAddr() {
return sAddr;
}
public void setsAddr(String sAddr) {
this.sAddr = sAddr;
}
public String getsExp() {
return sExp;
}
public void setsExp(String sExp) {
this.sExp = sExp;
}
public String getsPhNo() {
return sPhNo;
}
public void setsPhNo(String sPhNo) {
this.sPhNo = sPhNo;
}
public String getsEmail() {
return sEmail;
}
public void setsEmail(String sEmail) {
this.sEmail = sEmail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getIsActiveS() {
return isActiveS;
}
public void setIsActiveS(String isActiveS) {
this.isActiveS = isActiveS;
}
public Date getCreatedDateS() {
return createdDateS;
}
public void setCreatedDateS(Date createdDateS) {
this.createdDateS = createdDateS;
}
}
| 2,575 | 0.687281 | 0.687281 | 127 | 19.220472 | 14.277846 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.755906 | false | false | 2 |
897178f65c8dfc301893d992164ab540437896bd | 25,683,904,465,641 | 5790c846cdab9f20e476d793d0919c7efc57b351 | /app/src/main/java/com/example/muhammadfaizankhan/todo_list/Group.java | 7f339964cb87aab2fc58d36080f5f4c7c4ea2d68 | []
| no_license | faiz636/TodoList-Android | https://github.com/faiz636/TodoList-Android | c64a28d96332167c595601da3e14103405e05ff8 | 28e3edcb0e690b31ef9f6db22a8f863ff4241124 | refs/heads/master | 2021-01-25T05:15:47.872000 | 2015-05-01T18:45:16 | 2015-05-01T18:45:16 | 34,918,044 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.muhammadfaizankhan.todo_list;
/**
* Created by Muhammad Faizan Khan on 11/04/2015.
*/
public class Group {
}
| UTF-8 | Java | 132 | java | Group.java | Java | [
{
"context": "e.muhammadfaizankhan.todo_list;\n\n/**\n * Created by Muhammad Faizan Khan on 11/04/2015.\n */\npublic class Group {\n}\n",
"end": 89,
"score": 0.9998857975006104,
"start": 69,
"tag": "NAME",
"value": "Muhammad Faizan Khan"
}
]
| null | []
| package com.example.muhammadfaizankhan.todo_list;
/**
* Created by <NAME> on 11/04/2015.
*/
public class Group {
}
| 118 | 0.727273 | 0.666667 | 7 | 17.857143 | 20.663485 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 2 |
77e675a5074adad71dc35d7547aaef6147758057 | 652,835,089,738 | 6707de58adf6be486c213bd622cad7c5fcc4baa1 | /src/main/java/org/brijframework/college/service/MonthlyExamReportService.java | ca00055c2b2477860af1228b25270633050eefe7 | []
| no_license | ramkishor05/project-brijframework-college | https://github.com/ramkishor05/project-brijframework-college | 43c463d8d4697da7f0aaf4bfa5cfd48e3907ba80 | d5e3bb128e72c4cf72cd4dc553c16e6ca3b5177d | refs/heads/master | 2022-07-25T23:30:02.236000 | 2021-12-09T14:50:27 | 2021-12-09T14:50:27 | 189,605,485 | 0 | 0 | null | false | 2022-07-08T19:20:07 | 2019-05-31T14:15:20 | 2021-12-09T14:50:31 | 2022-07-08T19:20:07 | 9,589 | 0 | 0 | 4 | Java | false | false | package org.brijframework.college.service;
import java.util.List;
import java.util.Map;
import org.brijframework.college.model.MonthlyExamReport;
import org.brijframework.college.models.dto.MonthlyExamReportDTO;
public interface MonthlyExamReportService extends
CRUDService<Integer, MonthlyExamReport> {
public MonthlyExamReportDTO getMonthlyExamReport(int sessionId,
int classId, int sectionId, String studentId, int subjectId,
int monthId);
public void saveMonthlyExamReportData(
MonthlyExamReportDTO monthlyExamReportDTO);
public void updateMonthlyExamReportData(
MonthlyExamReportDTO monthlyExamReportDTO);
public Map<String, Object> getMonthlyExamReport(int sessionId, int classId,
int sectionId, String studentId);
List<MonthlyExamReportDTO> getMonthlyExamReport(int sessionId, int classId,
int sectionId, String studentId, int monthId);
public MonthlyExamReportDTO getMonthlyExamReport(int monthlyExamReportId);
}
| UTF-8 | Java | 957 | java | MonthlyExamReportService.java | Java | []
| null | []
| package org.brijframework.college.service;
import java.util.List;
import java.util.Map;
import org.brijframework.college.model.MonthlyExamReport;
import org.brijframework.college.models.dto.MonthlyExamReportDTO;
public interface MonthlyExamReportService extends
CRUDService<Integer, MonthlyExamReport> {
public MonthlyExamReportDTO getMonthlyExamReport(int sessionId,
int classId, int sectionId, String studentId, int subjectId,
int monthId);
public void saveMonthlyExamReportData(
MonthlyExamReportDTO monthlyExamReportDTO);
public void updateMonthlyExamReportData(
MonthlyExamReportDTO monthlyExamReportDTO);
public Map<String, Object> getMonthlyExamReport(int sessionId, int classId,
int sectionId, String studentId);
List<MonthlyExamReportDTO> getMonthlyExamReport(int sessionId, int classId,
int sectionId, String studentId, int monthId);
public MonthlyExamReportDTO getMonthlyExamReport(int monthlyExamReportId);
}
| 957 | 0.827586 | 0.827586 | 29 | 32 | 27.131863 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.793103 | false | false | 2 |
728b427a4fd886c583670fb42e597669f5e56d1b | 4,028,679,328,789 | c6450910a31d7258a16c75502a21019ab686fca1 | /src/org/frc1675/subsystems/climber/Climber.java | 3a2760244914dc27fb97d426885310f556430980 | []
| no_license | frc1675/frc1675-2013 | https://github.com/frc1675/frc1675-2013 | 38e9c466958df3b6d6d7e6403073527413eb3d3c | ce3f38c36e251c3bf930512389bbd7890bbe69f8 | refs/heads/master | 2016-09-05T16:23:04.692000 | 2014-01-10T22:56:33 | 2014-01-10T22:56:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.frc1675.subsystems.climber;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import org.frc1675.RobotMap;
/**
*
* @author TonyStano
*/
public class Climber extends Subsystem {
private Solenoid extend;
private Solenoid retract;
public Climber(){
extend = new Solenoid(RobotMap.CLIMBER_EXTEND);
retract = new Solenoid(RobotMap.CLIMBER_RETRACT);
}
public void initDefaultCommand() {
// no default command
}
public void extend(){
extend.set(true);
retract.set(false);
}
public void retract(){
extend.set(false);
retract.set(true);
}
public void doNothing(){
extend.set(false);
retract.set(false);
}
}
| UTF-8 | Java | 901 | java | Climber.java | Java | [
{
"context": "import org.frc1675.RobotMap;\n \n/**\n *\n * @author TonyStano\n */\npublic class Climber extends Subsystem {\n ",
"end": 287,
"score": 0.9997799396514893,
"start": 278,
"tag": "NAME",
"value": "TonyStano"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.frc1675.subsystems.climber;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import org.frc1675.RobotMap;
/**
*
* @author TonyStano
*/
public class Climber extends Subsystem {
private Solenoid extend;
private Solenoid retract;
public Climber(){
extend = new Solenoid(RobotMap.CLIMBER_EXTEND);
retract = new Solenoid(RobotMap.CLIMBER_RETRACT);
}
public void initDefaultCommand() {
// no default command
}
public void extend(){
extend.set(true);
retract.set(false);
}
public void retract(){
extend.set(false);
retract.set(true);
}
public void doNothing(){
extend.set(false);
retract.set(false);
}
}
| 901 | 0.624861 | 0.615982 | 43 | 19.953489 | 16.79833 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372093 | false | false | 2 |
17efe71ccdb6e2c6e32e0491cb1e131c62748cbf | 6,631,429,539,101 | 988c9b6eeb4589e3fd412f34a4bf92a16704b5d6 | /completed/USACO/Silver/2020-Feb-triangles.java | f0f33f943eff33851a83a3ea1a1065e2240f9d97 | []
| no_license | greenstripes4/USACO | https://github.com/greenstripes4/USACO | 3bf08c97767e457ace8f24c61117271028802693 | 24cd71c6d1cd168d76b27c2d6edd0c6abeeb7a83 | refs/heads/master | 2023-02-07T17:54:26.563000 | 2023-02-06T03:29:17 | 2023-02-06T03:29:17 | 192,225,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//Scanner f = new Scanner(new File("uva.in"));
//Scanner f = new Scanner(System.in);
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
//BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
BufferedReader f = new BufferedReader(new FileReader("triangles.in"));
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("triangles.out")));
int N = Integer.parseInt(f.readLine());
HashMap<Integer, HashSet<Integer>> x = new HashMap<>();
HashMap<Integer, HashSet<Integer>> y = new HashMap<>();
int[][] points = new int[N][2];
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
int X = Integer.parseInt(st.nextToken());
int Y = Integer.parseInt(st.nextToken());
if(!x.containsKey(X)) {
x.put(X, new HashSet<>());
}
if(!y.containsKey(Y)) {
y.put(Y, new HashSet<>());
}
x.get(X).add(Y);
y.get(Y).add(X);
points[i][0] = X;
points[i][1] = Y;
}
int totalArea = 0;
for(int[] i: points) {
int X1 = i[0];
int Y1 = i[1];
if(x.get(X1).size() == 1 || y.get(Y1).size() == 1) {
continue;
}
int totalXAbsDiff = 0;
int totalYAbsDiff = 0;
for(int Y2: x.get(X1)) {
totalXAbsDiff += Math.abs(Y1-Y2);
}
for(int X2: y.get(Y1)) {
totalYAbsDiff += Math.abs(X1-X2);
}
totalXAbsDiff %= 1000000007;
totalYAbsDiff %= 1000000007;
totalArea += (((long) totalXAbsDiff)*totalYAbsDiff)%1000000007;
totalArea %= 1000000007;
}
out.println(totalArea);
f.close();
out.close();
}
}
| UTF-8 | Java | 2,175 | java | 2020-Feb-triangles.java | Java | []
| null | []
| import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//Scanner f = new Scanner(new File("uva.in"));
//Scanner f = new Scanner(System.in);
//BufferedReader f = new BufferedReader(new FileReader("uva.in"));
//BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
BufferedReader f = new BufferedReader(new FileReader("triangles.in"));
//PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("triangles.out")));
int N = Integer.parseInt(f.readLine());
HashMap<Integer, HashSet<Integer>> x = new HashMap<>();
HashMap<Integer, HashSet<Integer>> y = new HashMap<>();
int[][] points = new int[N][2];
for(int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
int X = Integer.parseInt(st.nextToken());
int Y = Integer.parseInt(st.nextToken());
if(!x.containsKey(X)) {
x.put(X, new HashSet<>());
}
if(!y.containsKey(Y)) {
y.put(Y, new HashSet<>());
}
x.get(X).add(Y);
y.get(Y).add(X);
points[i][0] = X;
points[i][1] = Y;
}
int totalArea = 0;
for(int[] i: points) {
int X1 = i[0];
int Y1 = i[1];
if(x.get(X1).size() == 1 || y.get(Y1).size() == 1) {
continue;
}
int totalXAbsDiff = 0;
int totalYAbsDiff = 0;
for(int Y2: x.get(X1)) {
totalXAbsDiff += Math.abs(Y1-Y2);
}
for(int X2: y.get(Y1)) {
totalYAbsDiff += Math.abs(X1-X2);
}
totalXAbsDiff %= 1000000007;
totalYAbsDiff %= 1000000007;
totalArea += (((long) totalXAbsDiff)*totalYAbsDiff)%1000000007;
totalArea %= 1000000007;
}
out.println(totalArea);
f.close();
out.close();
}
}
| 2,175 | 0.514023 | 0.485057 | 56 | 37.839287 | 22.967972 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.803571 | false | false | 2 |
eee632ce623cac34cb613f4114d663b807b34993 | 6,459,630,832,862 | 12797ad5c7c015b63fc4dc1deda091ff1be98558 | /buukle-all/buukle-common/src/main/java/top/buukle/common/filter/reqestAndResponseParameterFilter/validatorAndHandler/DefaultResponseParamHandler.java | b777e9f9d8604f44c8b8ce6d1737e18dabaeabd4 | []
| no_license | bixiaoluo/buukle | https://github.com/bixiaoluo/buukle | af781bec00084c06c6dbf7190fe5c39c0d81c527 | 7306b1340450642e1afb46eaa0e5366a14313fa8 | refs/heads/master | 2020-03-31T07:02:43.524000 | 2018-10-07T19:17:48 | 2018-10-07T19:17:48 | 152,005,844 | 2 | 0 | null | true | 2018-10-08T02:12:36 | 2018-10-08T02:12:35 | 2018-10-07T19:18:00 | 2018-10-07T19:17:58 | 5,255 | 0 | 0 | 0 | null | false | null | package top.buukle.common.filter.reqestAndResponseParameterFilter.validatorAndHandler;
import top.buukle.common.filter.reqestAndResponseParameterFilter.validatorAndHandler.base.BaseResponseParamHandler;
import top.buukle.common.filter.reqestAndResponseParameterFilter.wrapper.BaseResponseWrapper;
/**
* @Author elvin
* @Date Created by elvin on 2018/10/7.
* @Description : 默认参数检验类
*/
public class DefaultResponseParamHandler extends BaseResponseParamHandler {
/**
* 重写默认处理方法
* @param baseResponseWrapper
*/
@Override
protected void doHandle(BaseResponseWrapper baseResponseWrapper) {
//默认不作处理
}
}
| UTF-8 | Java | 686 | java | DefaultResponseParamHandler.java | Java | [
{
"context": "ilter.wrapper.BaseResponseWrapper;\n\n/**\n * @Author elvin\n * @Date Created by elvin on 2018/10/7.\n * @Descr",
"end": 319,
"score": 0.9995183944702148,
"start": 314,
"tag": "USERNAME",
"value": "elvin"
}
]
| null | []
| package top.buukle.common.filter.reqestAndResponseParameterFilter.validatorAndHandler;
import top.buukle.common.filter.reqestAndResponseParameterFilter.validatorAndHandler.base.BaseResponseParamHandler;
import top.buukle.common.filter.reqestAndResponseParameterFilter.wrapper.BaseResponseWrapper;
/**
* @Author elvin
* @Date Created by elvin on 2018/10/7.
* @Description : 默认参数检验类
*/
public class DefaultResponseParamHandler extends BaseResponseParamHandler {
/**
* 重写默认处理方法
* @param baseResponseWrapper
*/
@Override
protected void doHandle(BaseResponseWrapper baseResponseWrapper) {
//默认不作处理
}
}
| 686 | 0.776398 | 0.765528 | 21 | 29.666666 | 35.014736 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 2 |
5058254fb89f8824b494bf70c1ac68bd1105bd9e | 6,459,630,829,808 | 08e0baacc3675942a62ef95599a6ccbc0cae24d6 | /Checkin/src/com/mavericks/checkin/parser/HCRequestStatus.java | f25212374ee5a588a3114d2e042eb36f9e3055f1 | []
| no_license | chipsyinfotech/hospital | https://github.com/chipsyinfotech/hospital | 067522cad56605d3436619928fcfd8bf33142269 | 6681949ec7de45d6f76d3c866bed5f47c98c9229 | refs/heads/master | 2016-09-06T12:13:22.583000 | 2014-11-01T07:05:53 | 2014-11-01T07:05:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @File:
* ABRequestStatus.java
* @Project:
* Abharan
* @Abstract:
*
* @Copyright:
* Copyright © 2014, 101 Mavericks.
* Written under contract by Chipsy Information Technology.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*! Revision history (Most recent first)
Created by vijayalaxmi on 22-Aug-2014
*/
package com.mavericks.checkin.parser;
/**
* @author vijayalaxmi
*
*/
public class HCRequestStatus {
String mStatusMsg;
int mError = -1;
public void setStatusMsg(String mStatusMsg) {
this.mStatusMsg = mStatusMsg;
}
public void setError(int mError) {
this.mError = mError;
}
public String getStatusMsg() {
return mStatusMsg;
}
public int getError() {
return mError;
}
}
| UTF-8 | Java | 880 | java | HCRequestStatus.java | Java | [
{
"context": " Revision history (Most recent first)\r\n Created by vijayalaxmi on 22-Aug-2014\r\n */\r\npackage com.mavericks.checki",
"end": 426,
"score": 0.9995074272155762,
"start": 415,
"tag": "USERNAME",
"value": "vijayalaxmi"
},
{
"context": "com.mavericks.checkin.parser;\r\n\r\n\r\n/**\r\n * @author vijayalaxmi\r\n *\r\n */\r\npublic class HCRequestStatus {\r\n\tString",
"end": 518,
"score": 0.9994207620620728,
"start": 507,
"tag": "USERNAME",
"value": "vijayalaxmi"
}
]
| null | []
| /*! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* @File:
* ABRequestStatus.java
* @Project:
* Abharan
* @Abstract:
*
* @Copyright:
* Copyright © 2014, 101 Mavericks.
* Written under contract by Chipsy Information Technology.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*! Revision history (Most recent first)
Created by vijayalaxmi on 22-Aug-2014
*/
package com.mavericks.checkin.parser;
/**
* @author vijayalaxmi
*
*/
public class HCRequestStatus {
String mStatusMsg;
int mError = -1;
public void setStatusMsg(String mStatusMsg) {
this.mStatusMsg = mStatusMsg;
}
public void setError(int mError) {
this.mError = mError;
}
public String getStatusMsg() {
return mStatusMsg;
}
public int getError() {
return mError;
}
}
| 880 | 0.527873 | 0.511945 | 44 | 17.977272 | 19.577919 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.931818 | false | false | 2 |
ee6573e01f2b9beed3b6b0b2d570cf8739b7cd56 | 5,179,730,621,293 | a747ddf3a38d8d0b9c142be19ab2003c52cdb59a | /com/greatlinkup/queue/QueueUtility.java | 8b9be7dda36e1a35d4b54315a547c6de2c7b59d6 | []
| no_license | lcahlander/uima | https://github.com/lcahlander/uima | ac30c53dee4848f21bd59b0f3c917ab8f3836480 | b9f60194a6685f24bdeb6a86def211806c0d7309 | refs/heads/master | 2020-12-30T14:56:08.440000 | 2013-07-02T14:09:34 | 2013-07-02T14:09:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.greatlinkup.queue;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.log4j.Logger;
import org.exist.xmldb.CollectionManagementServiceImpl;
import org.exist.xmldb.XPathQueryServiceImpl;
import org.exist.xmldb.XQueryService;
import org.exist.xupdate.XUpdateProcessor;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.Service;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XUpdateQueryService;
/**
* @author lcahlander
*
*/
public class QueueUtility {
/** The Constant logger. */
protected final static Logger logger = Logger.getLogger(QueueUtility.class);
/**
*
*/
public static final String UTC_FORMAT = "yyyy-MM-dd hh:mm:ss";
/**
*
*/
public static final String GMT = "GMT";
/**
*
* @return
*/
public static String getGMTStringForNow() {
Timestamp now = new Timestamp(System.currentTimeMillis());
return getGMTString(now);
}
/**
*
* @param date
* @return
*/
public static String getGMTString(Date date) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(UTC_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone(GMT));
String string = sdf.format(date);
string = string.replaceAll(" ", "T");
return string + "Z";
}
return "";
}
/**
*
* @param existURIString
* @param collectionPathString
* @param existUserName
* @param existUserPassword
* @return
*/
@SuppressWarnings("unchecked")
public static Collection getCollection(String existURIString, String collectionPathString, String existUserName,
String existUserPassword) {
String driver = "org.exist.xmldb.DatabaseImpl";
Collection coll = null;
try {
Class cl = Class.forName(driver);
Database database = (Database) cl.newInstance();
DatabaseManager.registerDatabase(database);
String existCollection = null;
coll = DatabaseManager.getCollection(existURIString + existCollection, existUserName, existUserPassword);
if (coll == null) {
int index = collectionPathString.lastIndexOf("/");
if (index > 0) {
String collectionPathSubString = collectionPathString.substring(0, index);
String newCollectionString = collectionPathString.substring(index + 1);
Collection root = getCollection(existURIString, collectionPathSubString, existUserName, existUserPassword);
if (root != null) {
CollectionManagementService mgtService = (CollectionManagementService) root.getService(
"CollectionManagementService", "1.0");
coll = mgtService.createCollection(newCollectionString);
} else {
return null;
}
} else {
return null;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (XMLDBException e) {
e.printStackTrace();
}
return coll;
}
/**
*
* @param existURIString
* @param resourcePathString
* @param existUserName
* @param existUserPassword
* @return
*/
public static Resource getResource(String existURIString, String resourcePathString, String resourceName, String existUserName,
String existUserPassword) {
Resource resource = null;
Collection collection = getCollection(existURIString, resourcePathString, existUserName, existUserPassword);
if (collection != null) {
try {
resource = collection.getResource(resourceName);
if (resource == null) {
resource = collection.getResource(resourcePathString.substring(4) + "/" + resourceName);
}
} catch (XMLDBException e) {
e.printStackTrace();
}
}
return resource;
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static String getTagTextFromResource(Resource resource, String tagPath) throws XMLDBException {
return getTagTextFromResource(resource, tagPath, null);
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static String getTagTextFromResource(Resource resource, String tagPath, String defaultValue) throws XMLDBException {
XPathQueryServiceImpl service = (XPathQueryServiceImpl) resource.getParentCollection().getService("XPathQueryService",
"1.0");
ResourceSet set = service.query((XMLResource) resource, tagPath + "/text()");
XMLResource res1 = (XMLResource) set.getResource(0);
if (res1 != null)
return (String) res1.getContent();
return defaultValue;
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static void updateDateTimeTagTextToNowFromResourceIfEmpty(Resource resource, String tagPath) throws XMLDBException {
XPathQueryServiceImpl service = (XPathQueryServiceImpl) resource.getParentCollection().getService("XPathQueryService",
"1.0");
ResourceSet set = service.query((XMLResource) resource, "//" + tagPath + "/text()");
XMLResource res1 = (XMLResource) set.getResource(0);
if (((res1 != null) && (((String) res1.getContent()).length() <= 0)) || (res1 == null)) {
String xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"" + XUpdateProcessor.XUPDATE_NS + "\">"
+ "<xu:variable name=\"now\" select=\"current-dateTime()\"/>" + "<xu:update select=\"//" + tagPath
+ "\"><xu:value-of select=\"$now\"/></xu:update>" + "</xu:modifications>";
doXUpdateResource(resource, xupdate);
}
}
public static void updateTagTextFromResource(Resource resource, String tagPath, String tagValue) throws XMLDBException {
String xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"" + XUpdateProcessor.XUPDATE_NS + "\">"
+ "<xu:update select=\"//" + tagPath + "\">" + tagValue + "</xu:update>" + "</xu:modifications>";
doXUpdateResource(resource, xupdate);
}
/**
*
* @param feed
* @param tagPath
* @param text
* @return
*/
public static boolean setTagTextFromResource(Resource feed, String tagPath, String text) {
// TODO Auto-generated method stub
return false;
}
/**
*
* @param sourceURLString
* xmldb:exist://localhost:8080/exist/xmlrpc
* @param userName
* admin
* @param password
* admin123
* @param sourceResourcePath
* /db/greatlinkup/apps/job-scheduler/data/queue
* @param sourceName
* 0000001feed0002.xml
* @param targetURLString
* xmldb:exist://localhost:8080/exist/xmlrpc
* @param targetResourcePath
* /db/syntacticq/apps/job-scheduler/data/cust/00000001/completed
* @return
* @throws XMLDBException
*/
public static boolean moveResource(String sourceURLString, String userName, String password, String sourceResourcePath,
String sourceName, String targetURLString, String targetResourcePath) throws XMLDBException {
System.out.println("sourceURLString = [" + sourceURLString + "]");
System.out.println("sourceResourcePath = [" + sourceResourcePath + "]");
System.out.println("sourceName = [" + sourceName + "]");
System.out.println("targetURLString = [" + targetURLString + "]");
System.out.println("targetResourcePath = [" + targetResourcePath + "]");
if (sourceURLString.equals(targetURLString)) {
Collection sourceCollection = getCollection(sourceURLString, sourceResourcePath, userName, password);
Resource resource = sourceCollection.getResource(sourceResourcePath.substring(4) + "/" + sourceName);
if (resource != null) {
CollectionManagementServiceImpl service = (CollectionManagementServiceImpl) sourceCollection.getService(
"CollectionManagementService", "1.0");
service.moveResource(sourceResourcePath.substring(4) + "/" + sourceName, targetResourcePath, null);
return true;
}
// CollectionManagementService
/*
* Move resource within same eXist database.
*/
} else {
/*
* Copy resource from source and create in target. Delete resource
* from source.
*/
}
return false;
}
public static Resource doQuery(Collection collection, String query) throws XMLDBException {
XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
ResourceSet result = service.query(query);
logger.info("Found " + result.getSize() + " results.");
for (ResourceIterator i = result.getIterator(); i.hasMoreResources();) {
return i.nextResource();
}
return null;
}
public static void doXUpdate(Collection collection, String xupdate) throws XMLDBException {
if ((xupdate == null) || (xupdate.length() <= 0)) {
logger.error("doXUpdate - no update string was passed in.");
return;
}
XUpdateQueryService service = (XUpdateQueryService) collection.getService("XUpdateQueryService", "1.0");
long mods = service.update(xupdate);
if (mods == 0) {
logger.info("no modifications processed for: \n\n" + xupdate);
} else {
logger.info(mods + " modifications processed");
}
}
public static void doXUpdateResource(Resource resource, String xupdate) {
if ((xupdate == null) || (xupdate.length() <= 0)) {
logger.error("doXUpdate - no update string was passed in.");
return;
}
long mods = 0;
try {
Collection collection = resource.getParentCollection();
// Service[] services = collection.getServices();
// for (int index = 0; index < services.length; index++) {
// System.out.println(services[index].getName() + ":" +
// services[index].getVersion());
// }
String collectionPath = collection.getName().substring(4);
String resourcePath = collectionPath + "/" + resource.getId();
XUpdateQueryService service = (XUpdateQueryService) collection.getService("XUpdateQueryService", "1.0");
System.out.println("doXUpdate[" + resourcePath + "][" + xupdate + "]");
mods = service.updateResource(resourcePath, xupdate);
} catch (XMLDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info(mods + " modifications processed.");
}
}
| UTF-8 | Java | 10,356 | java | QueueUtility.java | Java | [
{
"context": "b.api.modules.XUpdateQueryService;\n\n/**\n * @author lcahlander\n * \n */\npublic class QueueUtility {\n\n\t/** The Con",
"end": 856,
"score": 0.999585747718811,
"start": 846,
"tag": "USERNAME",
"value": "lcahlander"
},
{
"context": "80/exist/xmlrpc\n\t * @param userName\n\t * admin\n\t * @param password\n\t * admin123\n\t * @",
"end": 6568,
"score": 0.9979749321937561,
"start": 6563,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " admin\n\t * @param password\n\t * admin123\n\t * @param sourceResourcePath\n\t * /db/",
"end": 6612,
"score": 0.9985110759735107,
"start": 6604,
"tag": "PASSWORD",
"value": "admin123"
}
]
| null | []
| /**
*
*/
package com.greatlinkup.queue;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.log4j.Logger;
import org.exist.xmldb.CollectionManagementServiceImpl;
import org.exist.xmldb.XPathQueryServiceImpl;
import org.exist.xmldb.XQueryService;
import org.exist.xupdate.XUpdateProcessor;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.Service;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
import org.xmldb.api.modules.XUpdateQueryService;
/**
* @author lcahlander
*
*/
public class QueueUtility {
/** The Constant logger. */
protected final static Logger logger = Logger.getLogger(QueueUtility.class);
/**
*
*/
public static final String UTC_FORMAT = "yyyy-MM-dd hh:mm:ss";
/**
*
*/
public static final String GMT = "GMT";
/**
*
* @return
*/
public static String getGMTStringForNow() {
Timestamp now = new Timestamp(System.currentTimeMillis());
return getGMTString(now);
}
/**
*
* @param date
* @return
*/
public static String getGMTString(Date date) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(UTC_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone(GMT));
String string = sdf.format(date);
string = string.replaceAll(" ", "T");
return string + "Z";
}
return "";
}
/**
*
* @param existURIString
* @param collectionPathString
* @param existUserName
* @param existUserPassword
* @return
*/
@SuppressWarnings("unchecked")
public static Collection getCollection(String existURIString, String collectionPathString, String existUserName,
String existUserPassword) {
String driver = "org.exist.xmldb.DatabaseImpl";
Collection coll = null;
try {
Class cl = Class.forName(driver);
Database database = (Database) cl.newInstance();
DatabaseManager.registerDatabase(database);
String existCollection = null;
coll = DatabaseManager.getCollection(existURIString + existCollection, existUserName, existUserPassword);
if (coll == null) {
int index = collectionPathString.lastIndexOf("/");
if (index > 0) {
String collectionPathSubString = collectionPathString.substring(0, index);
String newCollectionString = collectionPathString.substring(index + 1);
Collection root = getCollection(existURIString, collectionPathSubString, existUserName, existUserPassword);
if (root != null) {
CollectionManagementService mgtService = (CollectionManagementService) root.getService(
"CollectionManagementService", "1.0");
coll = mgtService.createCollection(newCollectionString);
} else {
return null;
}
} else {
return null;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (XMLDBException e) {
e.printStackTrace();
}
return coll;
}
/**
*
* @param existURIString
* @param resourcePathString
* @param existUserName
* @param existUserPassword
* @return
*/
public static Resource getResource(String existURIString, String resourcePathString, String resourceName, String existUserName,
String existUserPassword) {
Resource resource = null;
Collection collection = getCollection(existURIString, resourcePathString, existUserName, existUserPassword);
if (collection != null) {
try {
resource = collection.getResource(resourceName);
if (resource == null) {
resource = collection.getResource(resourcePathString.substring(4) + "/" + resourceName);
}
} catch (XMLDBException e) {
e.printStackTrace();
}
}
return resource;
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static String getTagTextFromResource(Resource resource, String tagPath) throws XMLDBException {
return getTagTextFromResource(resource, tagPath, null);
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static String getTagTextFromResource(Resource resource, String tagPath, String defaultValue) throws XMLDBException {
XPathQueryServiceImpl service = (XPathQueryServiceImpl) resource.getParentCollection().getService("XPathQueryService",
"1.0");
ResourceSet set = service.query((XMLResource) resource, tagPath + "/text()");
XMLResource res1 = (XMLResource) set.getResource(0);
if (res1 != null)
return (String) res1.getContent();
return defaultValue;
}
/**
*
* @param resource
* @param tagPath
* @param service
* @return
* @throws XMLDBException
*/
public static void updateDateTimeTagTextToNowFromResourceIfEmpty(Resource resource, String tagPath) throws XMLDBException {
XPathQueryServiceImpl service = (XPathQueryServiceImpl) resource.getParentCollection().getService("XPathQueryService",
"1.0");
ResourceSet set = service.query((XMLResource) resource, "//" + tagPath + "/text()");
XMLResource res1 = (XMLResource) set.getResource(0);
if (((res1 != null) && (((String) res1.getContent()).length() <= 0)) || (res1 == null)) {
String xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"" + XUpdateProcessor.XUPDATE_NS + "\">"
+ "<xu:variable name=\"now\" select=\"current-dateTime()\"/>" + "<xu:update select=\"//" + tagPath
+ "\"><xu:value-of select=\"$now\"/></xu:update>" + "</xu:modifications>";
doXUpdateResource(resource, xupdate);
}
}
public static void updateTagTextFromResource(Resource resource, String tagPath, String tagValue) throws XMLDBException {
String xupdate = "<xu:modifications version=\"1.0\" xmlns:xu=\"" + XUpdateProcessor.XUPDATE_NS + "\">"
+ "<xu:update select=\"//" + tagPath + "\">" + tagValue + "</xu:update>" + "</xu:modifications>";
doXUpdateResource(resource, xupdate);
}
/**
*
* @param feed
* @param tagPath
* @param text
* @return
*/
public static boolean setTagTextFromResource(Resource feed, String tagPath, String text) {
// TODO Auto-generated method stub
return false;
}
/**
*
* @param sourceURLString
* xmldb:exist://localhost:8080/exist/xmlrpc
* @param userName
* admin
* @param password
* <PASSWORD>
* @param sourceResourcePath
* /db/greatlinkup/apps/job-scheduler/data/queue
* @param sourceName
* 0000001feed0002.xml
* @param targetURLString
* xmldb:exist://localhost:8080/exist/xmlrpc
* @param targetResourcePath
* /db/syntacticq/apps/job-scheduler/data/cust/00000001/completed
* @return
* @throws XMLDBException
*/
public static boolean moveResource(String sourceURLString, String userName, String password, String sourceResourcePath,
String sourceName, String targetURLString, String targetResourcePath) throws XMLDBException {
System.out.println("sourceURLString = [" + sourceURLString + "]");
System.out.println("sourceResourcePath = [" + sourceResourcePath + "]");
System.out.println("sourceName = [" + sourceName + "]");
System.out.println("targetURLString = [" + targetURLString + "]");
System.out.println("targetResourcePath = [" + targetResourcePath + "]");
if (sourceURLString.equals(targetURLString)) {
Collection sourceCollection = getCollection(sourceURLString, sourceResourcePath, userName, password);
Resource resource = sourceCollection.getResource(sourceResourcePath.substring(4) + "/" + sourceName);
if (resource != null) {
CollectionManagementServiceImpl service = (CollectionManagementServiceImpl) sourceCollection.getService(
"CollectionManagementService", "1.0");
service.moveResource(sourceResourcePath.substring(4) + "/" + sourceName, targetResourcePath, null);
return true;
}
// CollectionManagementService
/*
* Move resource within same eXist database.
*/
} else {
/*
* Copy resource from source and create in target. Delete resource
* from source.
*/
}
return false;
}
public static Resource doQuery(Collection collection, String query) throws XMLDBException {
XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
ResourceSet result = service.query(query);
logger.info("Found " + result.getSize() + " results.");
for (ResourceIterator i = result.getIterator(); i.hasMoreResources();) {
return i.nextResource();
}
return null;
}
public static void doXUpdate(Collection collection, String xupdate) throws XMLDBException {
if ((xupdate == null) || (xupdate.length() <= 0)) {
logger.error("doXUpdate - no update string was passed in.");
return;
}
XUpdateQueryService service = (XUpdateQueryService) collection.getService("XUpdateQueryService", "1.0");
long mods = service.update(xupdate);
if (mods == 0) {
logger.info("no modifications processed for: \n\n" + xupdate);
} else {
logger.info(mods + " modifications processed");
}
}
public static void doXUpdateResource(Resource resource, String xupdate) {
if ((xupdate == null) || (xupdate.length() <= 0)) {
logger.error("doXUpdate - no update string was passed in.");
return;
}
long mods = 0;
try {
Collection collection = resource.getParentCollection();
// Service[] services = collection.getServices();
// for (int index = 0; index < services.length; index++) {
// System.out.println(services[index].getName() + ":" +
// services[index].getVersion());
// }
String collectionPath = collection.getName().substring(4);
String resourcePath = collectionPath + "/" + resource.getId();
XUpdateQueryService service = (XUpdateQueryService) collection.getService("XUpdateQueryService", "1.0");
System.out.println("doXUpdate[" + resourcePath + "][" + xupdate + "]");
mods = service.updateResource(resourcePath, xupdate);
} catch (XMLDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.info(mods + " modifications processed.");
}
}
| 10,358 | 0.698822 | 0.691966 | 314 | 31.980892 | 32.115433 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.296178 | false | false | 2 |
99a32d32aee32a37fd1eabecc967bef9fd7838b2 | 17,360,257,844,545 | c44abf17d1778da002a002ef70c2907c188f80fd | /src/main/java/com/springtube/service/FileService.java | e07152b6c1c611a300e23c5ec1c6dc429e16ec91 | []
| no_license | MakarovEvgeny/SpringTube | https://github.com/MakarovEvgeny/SpringTube | 6c46ce0efe900cb2df55f3ce08604d60f4f7ba2e | a72b8c7acecbc24409245ecff532097f48d1a3c6 | refs/heads/master | 2017-11-02T14:01:06.306000 | 2014-09-22T11:27:51 | 2014-09-22T11:27:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.springtube.service;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Evgen
*/
public interface FileService {
public String upload(byte[] file, String absoluteDirectory, String originalFileName);
public void download(String url, HttpServletResponse response) throws IOException;
}
| UTF-8 | Java | 534 | java | FileService.java | Java | [
{
"context": "rvlet.http.HttpServletResponse;\n\n/**\n *\n * @author Evgen\n */\npublic interface FileService {\n public Str",
"end": 318,
"score": 0.9771930575370789,
"start": 313,
"tag": "NAME",
"value": "Evgen"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.springtube.service;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Evgen
*/
public interface FileService {
public String upload(byte[] file, String absoluteDirectory, String originalFileName);
public void download(String url, HttpServletResponse response) throws IOException;
}
| 534 | 0.762172 | 0.762172 | 19 | 27.105263 | 30.383331 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 2 |
d92fa155f496fd492a8b6f721837ea0b7b01701e | 10,900,627,050,045 | 6b615e53609657e238f4ed1a4596a6b3de8c886d | /CmasWeb/src/java/org/cmas/i18n/MsgKey.java | 08c9dbeaee59847e6279b6c63f4c20aefd93bbf3 | []
| no_license | sunsunich/cmas | https://github.com/sunsunich/cmas | 764cc6aba39b962c0828153bca62877974a63df7 | 36529df024961b51db88fb183fe97a9e6eb797f8 | refs/heads/master | 2022-09-30T04:48:11.453000 | 2022-09-24T11:29:50 | 2022-09-24T11:29:50 | 46,150,626 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.cmas.i18n;
/**
* ключи для system bundle
*
*/
public interface MsgKey {
// String MAIL_ENC = "cmas.system.mailEncoding";
// String HTTP_ENC = "cmas.system.httpEncoding";
// String SITE_MENU = "cmas.system.siteMenu";
// String TIMEZONE = "cmas.system.timeZones";
// String TIMEZONE_LOCALE = "cmas.system.tz.locale";
String MAIL_ENC = "utf-8";
String HTTP_ENC = "utf-8";
}
| UTF-8 | Java | 397 | java | MsgKey.java | Java | []
| null | []
| package org.cmas.i18n;
/**
* ключи для system bundle
*
*/
public interface MsgKey {
// String MAIL_ENC = "cmas.system.mailEncoding";
// String HTTP_ENC = "cmas.system.httpEncoding";
// String SITE_MENU = "cmas.system.siteMenu";
// String TIMEZONE = "cmas.system.timeZones";
// String TIMEZONE_LOCALE = "cmas.system.tz.locale";
String MAIL_ENC = "utf-8";
String HTTP_ENC = "utf-8";
}
| 397 | 0.683805 | 0.673522 | 15 | 24.933332 | 18.802364 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
36f2106dcfe181754581bf8f9c5fd143f873cd71 | 17,669,495,504,367 | 16b48645706faa31af030d4c36f13f920b440ccf | /src/main/java/com/jace/event/support/config/EnableMicroService.java | ef52ce23461871e6a663f0630fb56e7990cb7349 | []
| no_license | jiangqiang520/EventDriver | https://github.com/jiangqiang520/EventDriver | 40f5f0a654a01b0a9f241404545220014d3b3cf9 | f1ab80dc9f5c09a2a6cd164ea20b2f943b26d4c5 | refs/heads/master | 2020-07-26T21:17:25.676000 | 2019-09-16T10:09:07 | 2019-09-16T10:09:07 | 208,767,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jace.event.support.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.jace.event.core.common.configuration.CommonConfiguration;
import com.jace.event.core.event.configuration.EventConfiguration;
import com.jace.event.core.message.kafkaimpl.configuration.MessageConfiguration;
@SpringBootApplication
@EnableTransactionManagement
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({CommonConfiguration.class, EventConfiguration.class, MessageConfiguration.class})
public @interface EnableMicroService {
}
| UTF-8 | Java | 945 | java | EnableMicroService.java | Java | []
| null | []
| package com.jace.event.support.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.jace.event.core.common.configuration.CommonConfiguration;
import com.jace.event.core.event.configuration.EventConfiguration;
import com.jace.event.core.message.kafkaimpl.configuration.MessageConfiguration;
@SpringBootApplication
@EnableTransactionManagement
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({CommonConfiguration.class, EventConfiguration.class, MessageConfiguration.class})
public @interface EnableMicroService {
}
| 945 | 0.840212 | 0.840212 | 24 | 37.375 | 26.868216 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 2 |
bdc2a51604a0e66f868d2e3696c53c61d8accad5 | 26,405,458,995,682 | 06389f5f1dcfc282f34d173bcff12b0a8757a8da | /java-async/src/main/java/cn/soft1010/java/async/Member.java | b0e4712e6c994aadbdc206d8f56b987558995330 | []
| no_license | nine-free/java-base | https://github.com/nine-free/java-base | 07cfd6eba7941f028ef1061b2a120616ee4e6fa4 | a8a925710ae8be3817d1beb23dfc57d0d0f33390 | refs/heads/master | 2022-03-05T22:52:35.640000 | 2020-12-11T08:46:52 | 2020-12-11T08:46:52 | 174,985,064 | 0 | 1 | null | false | 2022-02-26T02:04:55 | 2019-03-11T11:21:33 | 2020-12-11T08:47:16 | 2022-02-26T02:04:54 | 53 | 0 | 0 | 2 | Java | false | false | package cn.soft1010.java.async;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Created by zhangjifu on 2020/12/6.
*/
public class Member implements Runnable {
private String name;
static int num = 0;
private CyclicBarrier cyclicBarrier;
public Member(String name, CyclicBarrier cyclicBarrier) {
this.name = name;
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
prepared();
try {
cyclicBarrier.await(50, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println(getName() + "------");
e.printStackTrace();
}
doEat();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void prepared() throws BrokenBarrierException, InterruptedException {
Thread.sleep(new Random().nextInt(10000));
System.out.println(getName() + " 准备好了 等待开饭... ");
}
private void doEat() throws InterruptedException {
Thread.sleep(new Random().nextInt(10000));
System.out.println(getName() + " 开始吃饭 ... ...");
num++;
System.out.println(num);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CyclicBarrier getCyclicBarrier() {
return cyclicBarrier;
}
public void setCyclicBarrier(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
}
| UTF-8 | Java | 1,826 | java | Member.java | Java | [
{
"context": "il.concurrent.TimeoutException;\n\n/**\n * Created by zhangjifu on 2020/12/6.\n */\npublic class Member implements ",
"end": 265,
"score": 0.999558687210083,
"start": 256,
"tag": "USERNAME",
"value": "zhangjifu"
}
]
| null | []
| package cn.soft1010.java.async;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Created by zhangjifu on 2020/12/6.
*/
public class Member implements Runnable {
private String name;
static int num = 0;
private CyclicBarrier cyclicBarrier;
public Member(String name, CyclicBarrier cyclicBarrier) {
this.name = name;
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
prepared();
try {
cyclicBarrier.await(50, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println(getName() + "------");
e.printStackTrace();
}
doEat();
} catch (BrokenBarrierException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void prepared() throws BrokenBarrierException, InterruptedException {
Thread.sleep(new Random().nextInt(10000));
System.out.println(getName() + " 准备好了 等待开饭... ");
}
private void doEat() throws InterruptedException {
Thread.sleep(new Random().nextInt(10000));
System.out.println(getName() + " 开始吃饭 ... ...");
num++;
System.out.println(num);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CyclicBarrier getCyclicBarrier() {
return cyclicBarrier;
}
public void setCyclicBarrier(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
}
| 1,826 | 0.607658 | 0.59434 | 71 | 24.380281 | 20.927349 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43662 | false | false | 2 |
b346650cd4b44ab318118a7c59be420b3edd5a29 | 18,562,848,708,703 | 84c22a57b1ce3e18bedc10f5861c0b67d5706f36 | /src/zadaci_15_01_2016/peti.java | e6a515452a13bc645e39564d3af285f47b9f9c49 | []
| no_license | NusretaNuxy/Bild-IT-Zadaci | https://github.com/NusretaNuxy/Bild-IT-Zadaci | 50fab2f0ad86319ce49c22112b99d4fd43a5123a | 21e396393a80d4fde8547ef53c020332ef5fae4f | refs/heads/master | 2021-01-10T15:01:52.845000 | 2016-02-13T00:00:15 | 2016-02-13T00:00:15 | 49,745,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package zadaci_15_01_2016;
import java.util.Scanner;
/*
*
* Napisati program koji učitava niz brojeva, pronalazi najveći broj te ispisruje koliko
* se puta taj broj ponavlja. Pretpostavimo da se unos brojeva završava sa nulom.
*/
public class peti {
public static void main(String[] args) {
// kreiraj skener
Scanner ulaz = new Scanner(System.in);
// deklarisi niz,varijablu max i brojac br
int max = 0;
int[] niz = new int[10];
int br = 0;
System.out.println("Unesite elelemnte niza");
// unesite clanove niza
for (int i = 0; i < niz.length; i++) {
niz[i] = ulaz.nextInt();
}
//Ispisi niz
System.out.print("Uneseni niz je\n");
for (int i = 0; i < niz.length; i++) {
System.out.print(niz[i] + " ");
}
// prodjimo kroz elemente niza i vidimo koji elemenat je maksimalan
for (int i = 0; i < niz.length; i++) {
if (max < niz[i]) {
max = niz[i];
}
}
// prodjimo kroz niz da vidimo koliko puta matrica sadrzi maksimalan
// broj
for (int i = 0; i < niz.length; i++) {
if (max == niz[i]) {
br++;
}
}
//ispisimo rezultat
System.out.println("\nnajveci elemnat matrice je: "+ max+ " a ponavlja se "+br + " puta");
}
}
| WINDOWS-1250 | Java | 1,266 | java | peti.java | Java | []
| null | []
| package zadaci_15_01_2016;
import java.util.Scanner;
/*
*
* Napisati program koji učitava niz brojeva, pronalazi najveći broj te ispisruje koliko
* se puta taj broj ponavlja. Pretpostavimo da se unos brojeva završava sa nulom.
*/
public class peti {
public static void main(String[] args) {
// kreiraj skener
Scanner ulaz = new Scanner(System.in);
// deklarisi niz,varijablu max i brojac br
int max = 0;
int[] niz = new int[10];
int br = 0;
System.out.println("Unesite elelemnte niza");
// unesite clanove niza
for (int i = 0; i < niz.length; i++) {
niz[i] = ulaz.nextInt();
}
//Ispisi niz
System.out.print("Uneseni niz je\n");
for (int i = 0; i < niz.length; i++) {
System.out.print(niz[i] + " ");
}
// prodjimo kroz elemente niza i vidimo koji elemenat je maksimalan
for (int i = 0; i < niz.length; i++) {
if (max < niz[i]) {
max = niz[i];
}
}
// prodjimo kroz niz da vidimo koliko puta matrica sadrzi maksimalan
// broj
for (int i = 0; i < niz.length; i++) {
if (max == niz[i]) {
br++;
}
}
//ispisimo rezultat
System.out.println("\nnajveci elemnat matrice je: "+ max+ " a ponavlja se "+br + " puta");
}
}
| 1,266 | 0.588282 | 0.575614 | 55 | 20.963636 | 23.932453 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.890909 | false | false | 2 |
e54bb5a1769bebd3e6251ae98ce15e588390499b | 33,492,155,035,212 | e678c5160e0b44e97cbe4e8a0c579313a4febeb4 | /src/test/java/utilities/TestBaseMethod.java | af22e2e9fca86d873d0e987ea250388aba915ba4 | []
| no_license | mucahit2664/TestNG13 | https://github.com/mucahit2664/TestNG13 | ea879fe78feb887be7fa21af90f2b85090e0bff4 | 2502ea28151d3bf0cd3e70a6b178dcd9bf63139d | refs/heads/master | 2023-05-15T05:34:51.388000 | 2021-06-11T14:28:47 | 2021-06-11T14:28:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utilities;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.util.concurrent.TimeUnit;
public abstract class TestBaseMethod {
// public : Herkes ulasabilir.
// protected : Ayni package veya child classlar
// default (bir sey yaz yazmazsak default kabul edilir) : package private'da denir. Sadece package'e ozel.
// private : sadece class icinde kullanabiliriz.
protected WebDriver driver;
@BeforeMethod
public void setup() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@AfterMethod
public void tearDown() {
driver.close();
}
}
| UTF-8 | Java | 940 | java | TestBaseMethod.java | Java | [
{
"context": "package utilities;\n\nimport io.github.bonigarcia.wdm.WebDriverManager;\nimport org.openqa.selenium.",
"end": 47,
"score": 0.9993453025817871,
"start": 37,
"tag": "USERNAME",
"value": "bonigarcia"
}
]
| null | []
| package utilities;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.util.concurrent.TimeUnit;
public abstract class TestBaseMethod {
// public : Herkes ulasabilir.
// protected : Ayni package veya child classlar
// default (bir sey yaz yazmazsak default kabul edilir) : package private'da denir. Sadece package'e ozel.
// private : sadece class icinde kullanabiliriz.
protected WebDriver driver;
@BeforeMethod
public void setup() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@AfterMethod
public void tearDown() {
driver.close();
}
}
| 940 | 0.715957 | 0.71383 | 31 | 29.32258 | 24.659472 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 2 |
71dd2fba09ec0d232152178e66df0ee9bc29ffa7 | 23,441,931,550,902 | 5793363bc9a75f027ad541d04e986a3a048114c5 | /TowerDefense/test/critter/WaveTest.java | cda00a53f372e51b0e2c4f7ab752ced0151c9876 | []
| no_license | mjhinton/TowerDefense | https://github.com/mjhinton/TowerDefense | 38636752512558f96a61be3ca25369fddd737386 | 9763adb1491f84dcabebd8596965a34f06f3664c | refs/heads/master | 2021-01-23T02:35:13.039000 | 2015-04-07T04:18:42 | 2015-04-07T04:18:42 | 32,041,262 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package critter;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import map.Map;
import model.Game;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import presentation.View;
import common.ReadWriteTxtFile;
public class WaveTest {
private String[] testArrayMap = ReadWriteTxtFile
.readTxtFileAsStringArray("lib/maps/15x15map.txt");
private Map testMap = new Map("testMap", 15, testArrayMap);
private Game testGame = new Game(testMap);
private ArrayList<Critter> testCritterBank, testReleaseBank;
private Wave testWave;
int amtNormCrit, amtSmartCrit, amtShieldedCrit, amtHeavyCrit, amtMonsterCrit, amtGhostCrit;
@Before
public void setUp() throws Exception {
testGame.generateWave();
testWave = testGame.getWave();
testCritterBank = testWave.getCritterBank();
testReleaseBank = testWave.getReleaseBank();
amtNormCrit = 0;
amtSmartCrit = 0;
amtShieldedCrit = 0;
amtMonsterCrit = 0;
amtHeavyCrit = 0;
amtGhostCrit = 0;
}
@After
public void tearDown() throws Exception {
testMap = null;
testGame = null;
testWave = null;
testCritterBank = null;
testReleaseBank = null;
}
@Test
public void testSetUpBank() {
//test that releaseBank is instantiated and filled with the same kinds of critters
for (int i = 0; i<8; i++){
assertTrue(testReleaseBank.get(i) instanceof NormalCritter);
}
//Change the difficulty multiplier (x>HARD)
//Now test that the right amount of each critter is instantiated at the hightest difficulty
testWave.setWaveNumber(22);
testWave.setUpBank();
for (int i = 0; i<testCritterBank.size(); i++){
if (testCritterBank.get(i) instanceof NormalCritter)
amtNormCrit++;
if (testCritterBank.get(i) instanceof SmartCritter)
amtSmartCrit++;
if (testCritterBank.get(i) instanceof ShieldedCritter)
amtShieldedCrit++;
if (testCritterBank.get(i) instanceof HeavyCritter)
amtHeavyCrit++;
if (testCritterBank.get(i) instanceof GhostCritter)
amtGhostCrit++;
if (testCritterBank.get(i) instanceof MonsterCritter)
amtMonsterCrit++;
}
assertEquals("Amount of normal critters should equal 3*x+5 added to the 8 existing ones", 8+(3*22+5), amtNormCrit);
assertEquals("Amount of heavy critters should equal x/2", 22/2, amtHeavyCrit);
assertEquals("Amount of smart critters should equal 2x/3", 2*22/3, amtSmartCrit);
assertEquals("Amount of shielded critters should equal x/3", 22/3, amtShieldedCrit);
assertEquals("Amount of monster critters should equal x/2", 22/2, amtMonsterCrit);
}
@Test
public void testGenerateCritters() {
//test that the correct type of critter is spawned
//with the correct quantity, and that they are added to the bank.
testWave.generateCritters("smart", 5, testGame);
//The first 8 critters in the bank should be Normal Critters
for (int i =0; i<8; i++){
Critter c = testWave.getCritterBank().get(i);
assertTrue(c instanceof NormalCritter);
}
//The next five critters should be Smart Critters
for (int i=8; i<13; i++){
Critter c = testWave.getCritterBank().get(i);
assertTrue(c instanceof SmartCritter);
}
}
@Test
public void testReleaseCritters() throws InterruptedException {
//releasing timing index is 0 at first, releasing is not finished.
testWave.releaseCritters();
assertFalse(testWave.finishedRelease());
//artificially increase releasing timing index to a high value
int index = (int)(testWave.DEFAULT_DELAY)/(int)(0.5*testWave.getDifficulty()*View.TIMEOUT)+1;
testWave.setReleasingTimingIndex(index);
//artificially increase the releasing index to the last value
int index2 = (int) testWave.getReleaseBank().size()-1;
testWave.setReleasingIndex(index2);
//Releasing should be finished now.
testWave.releaseCritters();
assertTrue(testWave.finishedRelease());
}
@Test
public void testWaveInProgress() throws InterruptedException {
//No critters killed, wave should be in progress
assertTrue(testWave.waveInProgress());
//Some critters killed, wave should be in progress
for (int i =0; i<2; i++){
testCritterBank.get(i).getsHit(5);
}
assertTrue(testWave.waveInProgress());
//All critters killed, wave should not be in progress.
testGame.generateWave();
for (int i=0; i<testCritterBank.size(); i++){
testCritterBank.get(i).getsHit(10);
}
for (int i=0; i<testReleaseBank.size(); i++){
testReleaseBank.get(i).getsHit(10);
}
assertFalse(testWave.waveInProgress());
}
}
| UTF-8 | Java | 4,487 | java | WaveTest.java | Java | []
| null | []
| package critter;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import map.Map;
import model.Game;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import presentation.View;
import common.ReadWriteTxtFile;
public class WaveTest {
private String[] testArrayMap = ReadWriteTxtFile
.readTxtFileAsStringArray("lib/maps/15x15map.txt");
private Map testMap = new Map("testMap", 15, testArrayMap);
private Game testGame = new Game(testMap);
private ArrayList<Critter> testCritterBank, testReleaseBank;
private Wave testWave;
int amtNormCrit, amtSmartCrit, amtShieldedCrit, amtHeavyCrit, amtMonsterCrit, amtGhostCrit;
@Before
public void setUp() throws Exception {
testGame.generateWave();
testWave = testGame.getWave();
testCritterBank = testWave.getCritterBank();
testReleaseBank = testWave.getReleaseBank();
amtNormCrit = 0;
amtSmartCrit = 0;
amtShieldedCrit = 0;
amtMonsterCrit = 0;
amtHeavyCrit = 0;
amtGhostCrit = 0;
}
@After
public void tearDown() throws Exception {
testMap = null;
testGame = null;
testWave = null;
testCritterBank = null;
testReleaseBank = null;
}
@Test
public void testSetUpBank() {
//test that releaseBank is instantiated and filled with the same kinds of critters
for (int i = 0; i<8; i++){
assertTrue(testReleaseBank.get(i) instanceof NormalCritter);
}
//Change the difficulty multiplier (x>HARD)
//Now test that the right amount of each critter is instantiated at the hightest difficulty
testWave.setWaveNumber(22);
testWave.setUpBank();
for (int i = 0; i<testCritterBank.size(); i++){
if (testCritterBank.get(i) instanceof NormalCritter)
amtNormCrit++;
if (testCritterBank.get(i) instanceof SmartCritter)
amtSmartCrit++;
if (testCritterBank.get(i) instanceof ShieldedCritter)
amtShieldedCrit++;
if (testCritterBank.get(i) instanceof HeavyCritter)
amtHeavyCrit++;
if (testCritterBank.get(i) instanceof GhostCritter)
amtGhostCrit++;
if (testCritterBank.get(i) instanceof MonsterCritter)
amtMonsterCrit++;
}
assertEquals("Amount of normal critters should equal 3*x+5 added to the 8 existing ones", 8+(3*22+5), amtNormCrit);
assertEquals("Amount of heavy critters should equal x/2", 22/2, amtHeavyCrit);
assertEquals("Amount of smart critters should equal 2x/3", 2*22/3, amtSmartCrit);
assertEquals("Amount of shielded critters should equal x/3", 22/3, amtShieldedCrit);
assertEquals("Amount of monster critters should equal x/2", 22/2, amtMonsterCrit);
}
@Test
public void testGenerateCritters() {
//test that the correct type of critter is spawned
//with the correct quantity, and that they are added to the bank.
testWave.generateCritters("smart", 5, testGame);
//The first 8 critters in the bank should be Normal Critters
for (int i =0; i<8; i++){
Critter c = testWave.getCritterBank().get(i);
assertTrue(c instanceof NormalCritter);
}
//The next five critters should be Smart Critters
for (int i=8; i<13; i++){
Critter c = testWave.getCritterBank().get(i);
assertTrue(c instanceof SmartCritter);
}
}
@Test
public void testReleaseCritters() throws InterruptedException {
//releasing timing index is 0 at first, releasing is not finished.
testWave.releaseCritters();
assertFalse(testWave.finishedRelease());
//artificially increase releasing timing index to a high value
int index = (int)(testWave.DEFAULT_DELAY)/(int)(0.5*testWave.getDifficulty()*View.TIMEOUT)+1;
testWave.setReleasingTimingIndex(index);
//artificially increase the releasing index to the last value
int index2 = (int) testWave.getReleaseBank().size()-1;
testWave.setReleasingIndex(index2);
//Releasing should be finished now.
testWave.releaseCritters();
assertTrue(testWave.finishedRelease());
}
@Test
public void testWaveInProgress() throws InterruptedException {
//No critters killed, wave should be in progress
assertTrue(testWave.waveInProgress());
//Some critters killed, wave should be in progress
for (int i =0; i<2; i++){
testCritterBank.get(i).getsHit(5);
}
assertTrue(testWave.waveInProgress());
//All critters killed, wave should not be in progress.
testGame.generateWave();
for (int i=0; i<testCritterBank.size(); i++){
testCritterBank.get(i).getsHit(10);
}
for (int i=0; i<testReleaseBank.size(); i++){
testReleaseBank.get(i).getsHit(10);
}
assertFalse(testWave.waveInProgress());
}
}
| 4,487 | 0.734344 | 0.719634 | 144 | 30.159721 | 25.514065 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.208333 | false | false | 2 |
38d886c82dde7b36034aae70edf87e76e160d5ab | 31,799,937,917,526 | a7bc28e86bf8eda63f5106335e58037991aa3822 | /src/main/java/com/xml/parsing/pojo/Organization.java | e7f8a7ff26b0c11f85edba210a79f774890fbedf | []
| no_license | VinodKandula/xml-parsing | https://github.com/VinodKandula/xml-parsing | f98adc5aa329250ada60ef14ed033ccbd5e28d4a | 8c64a756526b932dafce50693762b7ab69a18759 | refs/heads/master | 2021-01-18T22:12:48.304000 | 2016-09-26T07:02:38 | 2016-09-26T07:02:38 | 69,221,818 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.xml.parsing.pojo;
import com.xml.parsing.util.CommonXPathAnnotation;
/**
* @author vinod
*
*/
@CommonXPathAnnotation(xPath="/organisation")
public class Organization {
private References references;
private Defaults defaults;
private Address address;
private Contacts contacts;
private Version version;
@CommonXPathAnnotation(xPath="/organisation/directives/action")
private String action;
private UserCredentials usercredentials;
public References getReferences() {
return references;
}
public void setReferences(References references) {
this.references = references;
}
public Defaults getDefaults() {
return defaults;
}
public void setDefaults(Defaults defaults) {
this.defaults = defaults;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Contacts getContacts() {
return contacts;
}
public void setContacts(Contacts contacts) {
this.contacts = contacts;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public UserCredentials getUsercredentials() {
return usercredentials;
}
public void setUsercredentials(UserCredentials usercredentials) {
this.usercredentials = usercredentials;
}
@Override
public String toString() {
return "Organisation [references=" + references + ", defaults=" + defaults + ", address=" + address
+ ", contacts=" + contacts + ", version=" + version + ", action=" + action + ", usercredentials="
+ usercredentials + "]";
}
@CommonXPathAnnotation(xPath="/organisation/references")
public class References {
private String organisationtype;
private String name;
private String shortname;
private String suppliercode;
public String getOrganisationtype() {
return organisationtype;
}
public void setOrganisationtype(String organisationtype) {
this.organisationtype = organisationtype;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortname() {
return shortname;
}
public void setShortname(String shortname) {
this.shortname = shortname;
}
public String getSuppliercode() {
return suppliercode;
}
public void setSuppliercode(String suppliercode) {
this.suppliercode = suppliercode;
}
@Override
public String toString() {
return "References [organisationtype=" + organisationtype + ", name=" + name + ", shortname=" + shortname
+ ", suppliercode=" + suppliercode + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/defaults")
public class Defaults {
private String locode;
private String shippingterms;
private String currency;
private String toleranceperlot;
private String toleranceplusunits;
public String getLocode() {
return locode;
}
public void setLocode(String locode) {
this.locode = locode;
}
public String getShippingterms() {
return shippingterms;
}
public void setShippingterms(String shippingterms) {
this.shippingterms = shippingterms;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getToleranceperlot() {
return toleranceperlot;
}
public void setToleranceperlot(String toleranceperlot) {
this.toleranceperlot = toleranceperlot;
}
public String getToleranceplusunits() {
return toleranceplusunits;
}
public void setToleranceplusunits(String toleranceplusunits) {
this.toleranceplusunits = toleranceplusunits;
}
@Override
public String toString() {
return "Defaults [locode=" + locode + ", shippingterms=" + shippingterms + ", currency=" + currency
+ ", toleranceperlot=" + toleranceperlot + ", toleranceplusunits=" + toleranceplusunits + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/address")
public class Address {
private String address1;
private String address2;
private String address3;
private String address4;
private String city;
private String county;
private String iso3country;
private String postcode;
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getAddress3() {
return address3;
}
public void setAddress3(String address3) {
this.address3 = address3;
}
public String getAddress4() {
return address4;
}
public void setAddress4(String address4) {
this.address4 = address4;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getIso3country() {
return iso3country;
}
public void setIso3country(String iso3country) {
this.iso3country = iso3country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
@Override
public String toString() {
return "Address [address1=" + address1 + ", address2=" + address2 + ", address3=" + address3 + ", address4="
+ address4 + ", city=" + city + ", county=" + county + ", iso3country=" + iso3country + ", postcode="
+ postcode + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/contacts")
public class Contacts {
private String contactname;
private String telephone;
private String fax;
private String adminemailaddress;
private String opsemailaddress;
public String getContactname() {
return contactname;
}
public void setContactname(String contactname) {
this.contactname = contactname;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAdminemailaddress() {
return adminemailaddress;
}
public void setAdminemailaddress(String adminemailaddress) {
this.adminemailaddress = adminemailaddress;
}
public String getOpsemailaddress() {
return opsemailaddress;
}
public void setOpsemailaddress(String opsemailaddress) {
this.opsemailaddress = opsemailaddress;
}
@Override
public String toString() {
return "Contacts [contactname=" + contactname + ", telephone=" + telephone + ", fax=" + fax
+ ", adminemailaddress=" + adminemailaddress + ", opsemailaddress=" + opsemailaddress + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/version")
public class Version {
private String date;
private String statuscode;
private String statusname;
private String comments;
private String reference;
private String organisation;
private String user;
private String message_id;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStatuscode() {
return statuscode;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
public String getStatusname() {
return statusname;
}
public void setStatusname(String statusname) {
this.statusname = statusname;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getOrganisation() {
return organisation;
}
public void setOrganisation(String organisation) {
this.organisation = organisation;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage_id() {
return message_id;
}
public void setMessage_id(String message_id) {
this.message_id = message_id;
}
@Override
public String toString() {
return "Version [date=" + date + ", statuscode=" + statuscode + ", statusname=" + statusname + ", comments="
+ comments + ", reference=" + reference + ", organisation=" + organisation + ", user=" + user
+ ", message_id=" + message_id + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/usercredentials")
public class UserCredentials {
private String username;
private String emailaddress;
private String password;
private String firstname;
private String lastname;
private String departmentname;
private String accounttype;
@CommonXPathAnnotation(xPath="/organisation/usercredentials/rolemembership/role")
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDepartmentname() {
return departmentname;
}
public void setDepartmentname(String departmentname) {
this.departmentname = departmentname;
}
public String getAccounttype() {
return accounttype;
}
public void setAccounttype(String accounttype) {
this.accounttype = accounttype;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "UserCredentials [username=" + username + ", emailaddress=" + emailaddress + ", password=" + password
+ ", firstname=" + firstname + ", lastname=" + lastname + ", departmentname=" + departmentname
+ ", accounttype=" + accounttype + ", role=" + role + "]";
}
}
} | UTF-8 | Java | 10,462 | java | Organization.java | Java | [
{
"context": "arsing.util.CommonXPathAnnotation;\n\n/**\n * @author vinod\n *\n */\n@CommonXPathAnnotation(xPath=\"/organisatio",
"end": 115,
"score": 0.9990769028663635,
"start": 110,
"tag": "USERNAME",
"value": "vinod"
},
{
"context": "urn username;\n\t\t}\n\t\tpublic void setUsername(String username) {\n\t\t\tthis.username = username;\n\t\t}\n\t\tpublic Stri",
"end": 9094,
"score": 0.7230604887008667,
"start": 9086,
"tag": "USERNAME",
"value": "username"
},
{
"context": " setUsername(String username) {\n\t\t\tthis.username = username;\n\t\t}\n\t\tpublic String getEmailaddress() {\n\t\t\tretur",
"end": 9125,
"score": 0.9478943347930908,
"start": 9117,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tring() {\n\t\t\treturn \"UserCredentials [username=\" + username + \", emailaddress=\" + emailaddress + \", password=",
"end": 10222,
"score": 0.9497430920600891,
"start": 10214,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\", emailaddress=\" + emailaddress + \", password=\" + password\n\t\t\t\t\t+ \", firstname=\" + firstname + \", lastname=\"",
"end": 10284,
"score": 0.756053626537323,
"start": 10276,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| /**
*
*/
package com.xml.parsing.pojo;
import com.xml.parsing.util.CommonXPathAnnotation;
/**
* @author vinod
*
*/
@CommonXPathAnnotation(xPath="/organisation")
public class Organization {
private References references;
private Defaults defaults;
private Address address;
private Contacts contacts;
private Version version;
@CommonXPathAnnotation(xPath="/organisation/directives/action")
private String action;
private UserCredentials usercredentials;
public References getReferences() {
return references;
}
public void setReferences(References references) {
this.references = references;
}
public Defaults getDefaults() {
return defaults;
}
public void setDefaults(Defaults defaults) {
this.defaults = defaults;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Contacts getContacts() {
return contacts;
}
public void setContacts(Contacts contacts) {
this.contacts = contacts;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public UserCredentials getUsercredentials() {
return usercredentials;
}
public void setUsercredentials(UserCredentials usercredentials) {
this.usercredentials = usercredentials;
}
@Override
public String toString() {
return "Organisation [references=" + references + ", defaults=" + defaults + ", address=" + address
+ ", contacts=" + contacts + ", version=" + version + ", action=" + action + ", usercredentials="
+ usercredentials + "]";
}
@CommonXPathAnnotation(xPath="/organisation/references")
public class References {
private String organisationtype;
private String name;
private String shortname;
private String suppliercode;
public String getOrganisationtype() {
return organisationtype;
}
public void setOrganisationtype(String organisationtype) {
this.organisationtype = organisationtype;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortname() {
return shortname;
}
public void setShortname(String shortname) {
this.shortname = shortname;
}
public String getSuppliercode() {
return suppliercode;
}
public void setSuppliercode(String suppliercode) {
this.suppliercode = suppliercode;
}
@Override
public String toString() {
return "References [organisationtype=" + organisationtype + ", name=" + name + ", shortname=" + shortname
+ ", suppliercode=" + suppliercode + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/defaults")
public class Defaults {
private String locode;
private String shippingterms;
private String currency;
private String toleranceperlot;
private String toleranceplusunits;
public String getLocode() {
return locode;
}
public void setLocode(String locode) {
this.locode = locode;
}
public String getShippingterms() {
return shippingterms;
}
public void setShippingterms(String shippingterms) {
this.shippingterms = shippingterms;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getToleranceperlot() {
return toleranceperlot;
}
public void setToleranceperlot(String toleranceperlot) {
this.toleranceperlot = toleranceperlot;
}
public String getToleranceplusunits() {
return toleranceplusunits;
}
public void setToleranceplusunits(String toleranceplusunits) {
this.toleranceplusunits = toleranceplusunits;
}
@Override
public String toString() {
return "Defaults [locode=" + locode + ", shippingterms=" + shippingterms + ", currency=" + currency
+ ", toleranceperlot=" + toleranceperlot + ", toleranceplusunits=" + toleranceplusunits + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/address")
public class Address {
private String address1;
private String address2;
private String address3;
private String address4;
private String city;
private String county;
private String iso3country;
private String postcode;
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getAddress3() {
return address3;
}
public void setAddress3(String address3) {
this.address3 = address3;
}
public String getAddress4() {
return address4;
}
public void setAddress4(String address4) {
this.address4 = address4;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getIso3country() {
return iso3country;
}
public void setIso3country(String iso3country) {
this.iso3country = iso3country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
@Override
public String toString() {
return "Address [address1=" + address1 + ", address2=" + address2 + ", address3=" + address3 + ", address4="
+ address4 + ", city=" + city + ", county=" + county + ", iso3country=" + iso3country + ", postcode="
+ postcode + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/contacts")
public class Contacts {
private String contactname;
private String telephone;
private String fax;
private String adminemailaddress;
private String opsemailaddress;
public String getContactname() {
return contactname;
}
public void setContactname(String contactname) {
this.contactname = contactname;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAdminemailaddress() {
return adminemailaddress;
}
public void setAdminemailaddress(String adminemailaddress) {
this.adminemailaddress = adminemailaddress;
}
public String getOpsemailaddress() {
return opsemailaddress;
}
public void setOpsemailaddress(String opsemailaddress) {
this.opsemailaddress = opsemailaddress;
}
@Override
public String toString() {
return "Contacts [contactname=" + contactname + ", telephone=" + telephone + ", fax=" + fax
+ ", adminemailaddress=" + adminemailaddress + ", opsemailaddress=" + opsemailaddress + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/version")
public class Version {
private String date;
private String statuscode;
private String statusname;
private String comments;
private String reference;
private String organisation;
private String user;
private String message_id;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStatuscode() {
return statuscode;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
public String getStatusname() {
return statusname;
}
public void setStatusname(String statusname) {
this.statusname = statusname;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getOrganisation() {
return organisation;
}
public void setOrganisation(String organisation) {
this.organisation = organisation;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage_id() {
return message_id;
}
public void setMessage_id(String message_id) {
this.message_id = message_id;
}
@Override
public String toString() {
return "Version [date=" + date + ", statuscode=" + statuscode + ", statusname=" + statusname + ", comments="
+ comments + ", reference=" + reference + ", organisation=" + organisation + ", user=" + user
+ ", message_id=" + message_id + "]";
}
}
@CommonXPathAnnotation(xPath="/organisation/usercredentials")
public class UserCredentials {
private String username;
private String emailaddress;
private String password;
private String firstname;
private String lastname;
private String departmentname;
private String accounttype;
@CommonXPathAnnotation(xPath="/organisation/usercredentials/rolemembership/role")
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDepartmentname() {
return departmentname;
}
public void setDepartmentname(String departmentname) {
this.departmentname = departmentname;
}
public String getAccounttype() {
return accounttype;
}
public void setAccounttype(String accounttype) {
this.accounttype = accounttype;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "UserCredentials [username=" + username + ", emailaddress=" + emailaddress + ", password=" + <PASSWORD>
+ ", firstname=" + firstname + ", lastname=" + lastname + ", departmentname=" + departmentname
+ ", accounttype=" + accounttype + ", role=" + role + "]";
}
}
} | 10,464 | 0.703307 | 0.699006 | 414 | 24.272947 | 21.911667 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.468599 | false | false | 2 |
7887410e09755799327bf440c1944bac3d8dd51d | 21,827,023,848,180 | 471ff43c581977b2c579d34bae4e82ac46eb6490 | /topology-webapp/src/main/java/cz/ladicek/swarm/tiny/topologyWebapp/HelloServlet.java | 0336b9827e165f62795828ebafa9497eef7afeca | []
| no_license | Ladicek/swarm-tinies | https://github.com/Ladicek/swarm-tinies | 2e947ea29b4af9527f8f8fed24d4005761c4d196 | f6eec369c6b984d98a3ca838ef397bce1f49feda | refs/heads/master | 2021-01-12T10:55:06.977000 | 2019-11-15T12:17:02 | 2019-11-15T12:17:02 | 72,753,368 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cz.ladicek.swarm.tiny.topologyWebapp;
import org.wildfly.swarm.topology.Advertise;
import org.wildfly.swarm.topology.Topology;
import javax.naming.NamingException;
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 java.io.IOException;
@Advertise("hello")
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
resp.getWriter().print("Hello, topology is " + Topology.lookup().asMap().keySet());
} catch (NamingException e) {
throw new ServletException(e);
}
}
}
| UTF-8 | Java | 845 | java | HelloServlet.java | Java | []
| null | []
| package cz.ladicek.swarm.tiny.topologyWebapp;
import org.wildfly.swarm.topology.Advertise;
import org.wildfly.swarm.topology.Topology;
import javax.naming.NamingException;
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 java.io.IOException;
@Advertise("hello")
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
resp.getWriter().print("Hello, topology is " + Topology.lookup().asMap().keySet());
} catch (NamingException e) {
throw new ServletException(e);
}
}
}
| 845 | 0.751479 | 0.751479 | 25 | 32.799999 | 26.981476 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 2 |
b2b49f06462b77e62497642a75915be429b418b6 | 21,852,793,671,214 | c3e7a15718884a552be4ce119dc5af300a992408 | /src/main/java/com/training/service/impl/CareerPathServiceImpl.java | dca3d9058c57d8d10da9e3182f6b7c051efed573 | []
| no_license | PENGWAYNE/training-server | https://github.com/PENGWAYNE/training-server | c20acf28a95cbe59a7c253ae5083e4cf4679cf90 | cd26eac6e6f7c40638280ff264d70cc6aea4610e | refs/heads/master | 2020-03-20T13:08:26.490000 | 2019-04-06T06:13:16 | 2019-04-06T06:13:16 | 137,448,589 | 0 | 1 | null | false | 2020-09-18T16:44:52 | 2018-06-15T06:18:41 | 2019-04-06T06:13:37 | 2019-04-06T06:13:35 | 4,830 | 0 | 1 | 1 | Java | false | false | package com.training.service.impl;
import com.training.service.CareerPathService;
import com.training.domain.CareerPath;
import com.training.repository.CareerPathRepository;
import com.training.service.dto.CareerPathDTO;
import com.training.service.mapper.CareerPathMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing CareerPath.
*/
@Service
@Transactional
public class CareerPathServiceImpl implements CareerPathService {
private final Logger log = LoggerFactory.getLogger(CareerPathServiceImpl.class);
private final CareerPathRepository careerPathRepository;
private final CareerPathMapper careerPathMapper;
public CareerPathServiceImpl(CareerPathRepository careerPathRepository, CareerPathMapper careerPathMapper) {
this.careerPathRepository = careerPathRepository;
this.careerPathMapper = careerPathMapper;
}
/**
* Save a careerPath.
*
* @param careerPathDTO the entity to save
* @return the persisted entity
*/
@Override
public CareerPathDTO save(CareerPathDTO careerPathDTO) {
log.debug("Request to save CareerPath : {}", careerPathDTO);
CareerPath careerPath = careerPathMapper.toEntity(careerPathDTO);
careerPath = careerPathRepository.save(careerPath);
return careerPathMapper.toDto(careerPath);
}
/**
* Get all the careerPaths.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public Page<CareerPathDTO> findAll(Pageable pageable) {
log.debug("Request to get all CareerPaths");
return careerPathRepository.findAll(pageable)
.map(careerPathMapper::toDto);
}
/**
* Get one careerPath by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public CareerPathDTO findOne(Long id) {
log.debug("Request to get CareerPath : {}", id);
CareerPath careerPath = careerPathRepository.findOne(id);
return careerPathMapper.toDto(careerPath);
}
/**
* Delete the careerPath by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete CareerPath : {}", id);
careerPathRepository.delete(id);
}
}
| UTF-8 | Java | 2,645 | java | CareerPathServiceImpl.java | Java | []
| null | []
| package com.training.service.impl;
import com.training.service.CareerPathService;
import com.training.domain.CareerPath;
import com.training.repository.CareerPathRepository;
import com.training.service.dto.CareerPathDTO;
import com.training.service.mapper.CareerPathMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing CareerPath.
*/
@Service
@Transactional
public class CareerPathServiceImpl implements CareerPathService {
private final Logger log = LoggerFactory.getLogger(CareerPathServiceImpl.class);
private final CareerPathRepository careerPathRepository;
private final CareerPathMapper careerPathMapper;
public CareerPathServiceImpl(CareerPathRepository careerPathRepository, CareerPathMapper careerPathMapper) {
this.careerPathRepository = careerPathRepository;
this.careerPathMapper = careerPathMapper;
}
/**
* Save a careerPath.
*
* @param careerPathDTO the entity to save
* @return the persisted entity
*/
@Override
public CareerPathDTO save(CareerPathDTO careerPathDTO) {
log.debug("Request to save CareerPath : {}", careerPathDTO);
CareerPath careerPath = careerPathMapper.toEntity(careerPathDTO);
careerPath = careerPathRepository.save(careerPath);
return careerPathMapper.toDto(careerPath);
}
/**
* Get all the careerPaths.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public Page<CareerPathDTO> findAll(Pageable pageable) {
log.debug("Request to get all CareerPaths");
return careerPathRepository.findAll(pageable)
.map(careerPathMapper::toDto);
}
/**
* Get one careerPath by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public CareerPathDTO findOne(Long id) {
log.debug("Request to get CareerPath : {}", id);
CareerPath careerPath = careerPathRepository.findOne(id);
return careerPathMapper.toDto(careerPath);
}
/**
* Delete the careerPath by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete CareerPath : {}", id);
careerPathRepository.delete(id);
}
}
| 2,645 | 0.709263 | 0.708507 | 86 | 29.755814 | 24.770075 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372093 | false | false | 2 |
0f4f202d60257110c790d98c715b2f2d5e1f7d40 | 39,668,317,953,326 | f77d04f1e0f64a6a5e720ce24b65b1ccb3c546d2 | /zyj-hec-master/zyj-hec/src/main/java/com/hand/hec/exp/dto/ExpMoRepTypeRefEmpGp.java | 1623b7819ce1b016ae27105665f91b13616ae66e | []
| no_license | floodboad/zyj-hssp | https://github.com/floodboad/zyj-hssp | 3139a4e73ec599730a67360cd04aa34bc9eaf611 | dc0ef445935fa48b7a6e86522ec64da0042dc0f3 | refs/heads/master | 2023-05-27T21:28:01.290000 | 2020-01-03T06:21:59 | 2020-01-03T06:29:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hand.hec.exp.dto;
import com.hand.hap.mybatis.annotation.ExtensionAttribute;
import com.hand.hap.mybatis.common.query.JoinColumn;
import com.hand.hap.mybatis.common.query.JoinOn;
import com.hand.hap.mybatis.common.query.JoinTable;
import com.hand.hap.mybatis.common.query.Where;
import com.hand.hap.system.dto.BaseDTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.criteria.JoinType;
import javax.validation.constraints.NotNull;
/**
* <p>
* ExpMoRepTypeRefEmpGp
* </p>
*
* @author yang.duan 2019/01/10 14:45
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@ExtensionAttribute(disable = true)
@Table(name = "exp_mo_rep_type_ref_emp_gp")
public class ExpMoRepTypeRefEmpGp extends BaseDTO {
public static final String FIELD_REF_ID = "refId";
public static final String FIELD_MO_EXP_REPORT_TYPE_ID = "moExpReportTypeId";
public static final String FIELD_MO_EMP_GROUP_ID = "moEmpGroupId";
public static final String FIELD_ENABLED_FLAG = "enabledFlag";
public static final String FIELD_MO_EMP_GROUP_CODE = "moEmpGroupCode";
public static final String FIELD_MO_EMP_GROUP_NAME = "moEmpGroupName";
@Id
@GeneratedValue
private Long refId;
/**
* 管理组织级报销单类型ID
*/
@NotNull
@Where
private Long moExpReportTypeId;
/**
* 管理组织级员工组ID
*
*/
@NotNull
@JoinTable(name = "empGroupJoin", target = ExpMoEmpGroup.class, joinMultiLanguageTable = true, type = JoinType.LEFT,
on = {@JoinOn(joinField = ExpMoEmpGroup.FIELD_MO_EMP_GROUP_ID)})
private Long moEmpGroupId;
@Transient
@JoinColumn(joinName = "empGroupJoin",field = ExpMoEmpGroup.FIELD_MO_EMP_GROUP_CODE)
@Where
private String moEmpGroupCode;
@Transient
@JoinColumn(joinName = "empGroupJoin",field = ExpMoEmpGroup.FIELD_DESCRIPTION)
@Where
private String moEmpGroupName;
/**
* 启用标志
*/
@NotEmpty
@Length(max = 1)
private String enabledFlag;
}
| UTF-8 | Java | 2,340 | java | ExpMoRepTypeRefEmpGp.java | Java | [
{
"context": " <p>\n * ExpMoRepTypeRefEmpGp\n * </p>\n *\n * @author yang.duan 2019/01/10 14:45\n */\n@Getter\n@Setter\n@ToString\n@N",
"end": 832,
"score": 0.9769588112831116,
"start": 823,
"tag": "USERNAME",
"value": "yang.duan"
}
]
| null | []
| package com.hand.hec.exp.dto;
import com.hand.hap.mybatis.annotation.ExtensionAttribute;
import com.hand.hap.mybatis.common.query.JoinColumn;
import com.hand.hap.mybatis.common.query.JoinOn;
import com.hand.hap.mybatis.common.query.JoinTable;
import com.hand.hap.mybatis.common.query.Where;
import com.hand.hap.system.dto.BaseDTO;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.criteria.JoinType;
import javax.validation.constraints.NotNull;
/**
* <p>
* ExpMoRepTypeRefEmpGp
* </p>
*
* @author yang.duan 2019/01/10 14:45
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
@ExtensionAttribute(disable = true)
@Table(name = "exp_mo_rep_type_ref_emp_gp")
public class ExpMoRepTypeRefEmpGp extends BaseDTO {
public static final String FIELD_REF_ID = "refId";
public static final String FIELD_MO_EXP_REPORT_TYPE_ID = "moExpReportTypeId";
public static final String FIELD_MO_EMP_GROUP_ID = "moEmpGroupId";
public static final String FIELD_ENABLED_FLAG = "enabledFlag";
public static final String FIELD_MO_EMP_GROUP_CODE = "moEmpGroupCode";
public static final String FIELD_MO_EMP_GROUP_NAME = "moEmpGroupName";
@Id
@GeneratedValue
private Long refId;
/**
* 管理组织级报销单类型ID
*/
@NotNull
@Where
private Long moExpReportTypeId;
/**
* 管理组织级员工组ID
*
*/
@NotNull
@JoinTable(name = "empGroupJoin", target = ExpMoEmpGroup.class, joinMultiLanguageTable = true, type = JoinType.LEFT,
on = {@JoinOn(joinField = ExpMoEmpGroup.FIELD_MO_EMP_GROUP_ID)})
private Long moEmpGroupId;
@Transient
@JoinColumn(joinName = "empGroupJoin",field = ExpMoEmpGroup.FIELD_MO_EMP_GROUP_CODE)
@Where
private String moEmpGroupCode;
@Transient
@JoinColumn(joinName = "empGroupJoin",field = ExpMoEmpGroup.FIELD_DESCRIPTION)
@Where
private String moEmpGroupName;
/**
* 启用标志
*/
@NotEmpty
@Length(max = 1)
private String enabledFlag;
}
| 2,340 | 0.725174 | 0.719512 | 84 | 26.333334 | 25.835714 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440476 | false | false | 2 |
2b7122ae6aad008e226a61cb51323b0446b6105d | 39,556,648,829,376 | 72e39f1a0fc41a80575b206e3cc03f76e6bf69e2 | /tesla/tesla-gateway/src/main/java/com/xiaomi/youpin/gateway/netty/filter/request/MockFilter.java | 9851552bf30c3c269814c4443af0d56df6a246f4 | [
"Apache-2.0"
]
| permissive | JDmajia/mone | https://github.com/JDmajia/mone | d4a4cf235c2f567d78e1ef0bb44f707bd850314a | 42c39e00c0a348bc6fc8de9e63f0e81966f21f73 | refs/heads/master | 2023-03-27T04:36:47.919000 | 2021-03-29T03:14:37 | 2021-03-29T03:14:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2020 Xiaomi
*
* 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.xiaomi.youpin.gateway.netty.filter.request;
import com.xiaomi.data.push.redis.Redis;
import com.xiaomi.youpin.gateway.common.FilterOrder;
import com.xiaomi.youpin.gateway.common.HttpResponseUtils;
import com.xiaomi.youpin.gateway.common.Keys;
import com.xiaomi.youpin.gateway.filter.FilterContext;
import com.xiaomi.youpin.gateway.filter.Invoker;
import com.xiaomi.youpin.gateway.filter.RequestFilter;
import com.youpin.xiaomi.tesla.bo.ApiInfo;
import com.youpin.xiaomi.tesla.bo.Flag;
import com.youpin.xiaomi.tesla.bo.ResponseConfig;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author goodjava@qq.com
* 进行mock处理
*/
@Component
@FilterOrder(1000)
public class MockFilter extends RequestFilter {
private static final Logger logger = LoggerFactory.getLogger(MockFilter.class);
@Autowired
private Redis redis;
@Override
public FullHttpResponse doFilter(FilterContext context, Invoker invoker, ApiInfo apiInfo, FullHttpRequest request) {
if (apiInfo.isAllow(Flag.ALLOW_MOCK)) {
logger.debug("mock filter invoker id:{}", apiInfo.getId());
ResponseConfig rc = new ResponseConfig();
rc.setContentType(HttpResponseUtils.ContentTypeJson);
context.setResponseConfig(rc);
String mockDataId = String.valueOf(apiInfo.getId());
String data = redis.get(Keys.mockKey(mockDataId));
return HttpResponseUtils.create(data, context.getResponseConfig().getContentType());
}
return invoker.doInvoker(context, apiInfo, request);
}
}
| UTF-8 | Java | 2,425 | java | MockFilter.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author goodjava@qq.com\n * 进行mock处理\n */\n@Component\n@FilterOrder(1000)\npub",
"end": 1472,
"score": 0.999903678894043,
"start": 1457,
"tag": "EMAIL",
"value": "goodjava@qq.com"
}
]
| null | []
| /*
* Copyright 2020 Xiaomi
*
* 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.xiaomi.youpin.gateway.netty.filter.request;
import com.xiaomi.data.push.redis.Redis;
import com.xiaomi.youpin.gateway.common.FilterOrder;
import com.xiaomi.youpin.gateway.common.HttpResponseUtils;
import com.xiaomi.youpin.gateway.common.Keys;
import com.xiaomi.youpin.gateway.filter.FilterContext;
import com.xiaomi.youpin.gateway.filter.Invoker;
import com.xiaomi.youpin.gateway.filter.RequestFilter;
import com.youpin.xiaomi.tesla.bo.ApiInfo;
import com.youpin.xiaomi.tesla.bo.Flag;
import com.youpin.xiaomi.tesla.bo.ResponseConfig;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author <EMAIL>
* 进行mock处理
*/
@Component
@FilterOrder(1000)
public class MockFilter extends RequestFilter {
private static final Logger logger = LoggerFactory.getLogger(MockFilter.class);
@Autowired
private Redis redis;
@Override
public FullHttpResponse doFilter(FilterContext context, Invoker invoker, ApiInfo apiInfo, FullHttpRequest request) {
if (apiInfo.isAllow(Flag.ALLOW_MOCK)) {
logger.debug("mock filter invoker id:{}", apiInfo.getId());
ResponseConfig rc = new ResponseConfig();
rc.setContentType(HttpResponseUtils.ContentTypeJson);
context.setResponseConfig(rc);
String mockDataId = String.valueOf(apiInfo.getId());
String data = redis.get(Keys.mockKey(mockDataId));
return HttpResponseUtils.create(data, context.getResponseConfig().getContentType());
}
return invoker.doInvoker(context, apiInfo, request);
}
}
| 2,417 | 0.741415 | 0.735623 | 63 | 37.365078 | 28.807133 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.619048 | false | false | 2 |
962b1a1eafa54f736f181d035c2b577327ea51be | 39,135,742,018,591 | e622e847020b8de3be73c2e2e78e00829f619e17 | /app/src/main/java/nso/rest_client/MainActivity.java | 2665d5d829d877e001cd720a24f642ce48ecd74f | []
| no_license | NaokiKoreeda/android-java-rest-client-light | https://github.com/NaokiKoreeda/android-java-rest-client-light | 9e45055f04f1cd2023e8987f42ef4df3916bb778 | 752a5a8a187389da0a0bf584d1dd5b4e28013513 | refs/heads/master | 2017-11-30T20:08:44.418000 | 2016-06-14T10:41:26 | 2016-06-14T10:41:26 | 61,113,221 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nso.rest_client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txtRequestUri = (TextView)findViewById(R.id.txtRequestUri);
Button btnExecute = (Button)findViewById(R.id.btnExecute);
final TextView txtViewRespose = (TextView)findViewById(R.id.txtViewResponse);
btnExecute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence strUri = txtRequestUri.getText();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(strUri.toString());
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
String str = InputStreamToString(con.getInputStream());
txtViewRespose.setText(str);
} catch (Exception e) {
//
}
}
}).start();
}
});
}
static String InputStreamToString(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
| UTF-8 | Java | 2,125 | java | MainActivity.java | Java | []
| null | []
| package nso.rest_client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txtRequestUri = (TextView)findViewById(R.id.txtRequestUri);
Button btnExecute = (Button)findViewById(R.id.btnExecute);
final TextView txtViewRespose = (TextView)findViewById(R.id.txtViewResponse);
btnExecute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence strUri = txtRequestUri.getText();
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(strUri.toString());
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
String str = InputStreamToString(con.getInputStream());
txtViewRespose.setText(str);
} catch (Exception e) {
//
}
}
}).start();
}
});
}
static String InputStreamToString(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
| 2,125 | 0.576 | 0.575529 | 64 | 32.203125 | 24.995737 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
03b9533a29223dc368f25035dbee54e1efa434a8 | 30,760,555,835,010 | ca7e5e550903c01af8e6f596e652694fcca9070d | /Android/app/src/main/java/com/shouduo/plant/view/dialog/BaseDialogFragment.java | 156f348cfc15451c12278eec12c6abb22294a817 | [
"Apache-2.0"
]
| permissive | Shouduo/PlanT | https://github.com/Shouduo/PlanT | be523ae46598f4d870110c7a2da370b5ceebd6b6 | dd7e017fc54ba584f895c2ab458954301b27c54e | refs/heads/master | 2021-01-23T13:16:22.367000 | 2019-12-02T08:13:02 | 2019-12-02T08:13:02 | 93,236,521 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shouduo.plant.view.dialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import com.shouduo.plant.PlanT;
/**
* Created by 刘亨俊 on 17.2.13.
*/
public abstract class BaseDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
PlanT.getInstance().getTopActivity().getDialogList().add(this);
return super.onCreateDialog(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
PlanT.getInstance().getTopActivity().getDialogList().remove(this);
}
public abstract View getSnackbarContainer();
}
| UTF-8 | Java | 716 | java | BaseDialogFragment.java | Java | [
{
"context": "mport com.shouduo.plant.PlanT;\n\n/**\n * Created by 刘亨俊 on 17.2.13.\n */\n\npublic abstract class BaseDialog",
"end": 209,
"score": 0.9998554587364197,
"start": 206,
"tag": "NAME",
"value": "刘亨俊"
}
]
| null | []
| package com.shouduo.plant.view.dialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import com.shouduo.plant.PlanT;
/**
* Created by 刘亨俊 on 17.2.13.
*/
public abstract class BaseDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
PlanT.getInstance().getTopActivity().getDialogList().add(this);
return super.onCreateDialog(savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
PlanT.getInstance().getTopActivity().getDialogList().remove(this);
}
public abstract View getSnackbarContainer();
}
| 716 | 0.721127 | 0.714085 | 29 | 23.482759 | 23.608328 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37931 | false | false | 2 |
a41e9db16bd92d6f29c60506d60389c5494dfe09 | 22,411,139,410,921 | d45d8fb27ba8c0c1c0d7a2a3225e6b99337c8b12 | /model/src/main/java/ru/aparfenov/model/ChildBLocal.java | d2c4e6a17cf0c5f8d8c965175a0d18b6378cd148 | []
| no_license | getman/test-ejb-injection | https://github.com/getman/test-ejb-injection | e07f4dd82b55a1b285e1e1309dbc76580d38163b | f0053427f2bc164c8bdde95087692cb7ef2ee1f1 | refs/heads/master | 2021-01-21T21:00:20.772000 | 2018-03-12T21:38:44 | 2018-03-12T21:38:44 | 94,769,980 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.aparfenov.model;
import ru.aparfenov.model.ParentLocal;
import javax.ejb.Local;
/**
* Created by ArtemParfenov on 16.06.2017.
*/
@Local
public interface ChildBLocal extends ParentLocal {
}
| UTF-8 | Java | 205 | java | ChildBLocal.java | Java | [
{
"context": "Local;\n\nimport javax.ejb.Local;\n\n/**\n * Created by ArtemParfenov on 16.06.2017.\n */\n@Local\npublic interface ChildB",
"end": 125,
"score": 0.9971420168876648,
"start": 112,
"tag": "NAME",
"value": "ArtemParfenov"
}
]
| null | []
| package ru.aparfenov.model;
import ru.aparfenov.model.ParentLocal;
import javax.ejb.Local;
/**
* Created by ArtemParfenov on 16.06.2017.
*/
@Local
public interface ChildBLocal extends ParentLocal {
}
| 205 | 0.760976 | 0.721951 | 12 | 16.083334 | 18.066813 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 2 |
e1f0ded013d91461bbafcebff83eeca22c7e8c06 | 39,410,619,925,236 | 5b55f38a753d251c1696f87d52f9554f2c04334a | /src/com/more/buss/eis/bd/basedos/service/pg/AjaxFindItemBySnAndCondition.java | 77102f86cbac714401ac5c264fe96d2826bd4785 | []
| no_license | 1wangxueyan2/SKS-MC | https://github.com/1wangxueyan2/SKS-MC | 2b64d4a51547214690a60dd8bde5cdbdfd67e6ca | 898e38e5be2dc78d268774d76cf3054f09c747fe | refs/heads/master | 2022-03-06T06:40:51.405000 | 2019-10-25T06:59:18 | 2019-10-25T06:59:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.more.buss.eis.bd.basedos.service.pg;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.more.fw.core.base.core.action.BaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.more.fw.core.common.method.StringUtils;
import com.more.fw.core.base.core.action.ModelAction;
import com.more.fw.core.dbo.model.service.ModelService;
import com.more.fw.core.common.method.CommMethod;
import com.more.fw.core.dbo.model.service.impl.base.FuncService;
/**
* @Description 根据物料组物料获取信息
* @ClassName AjaxFindItemBySnAndCondition
* @author
*/
public class AjaxFindItemBySnAndCondition implements FuncService {
private final Log log = LogFactory.getLog(this.getClass());
@Override
public String exeFunc(ModelAction modelAction, ModelService modelService) {
String cigName = modelAction.getParaMap().get("cigName");
String cigType = modelAction.getParaMap().get("cigType");
String itemCode = modelAction.getParaMap().get("itemCode");
String itemName = modelAction.getParaMap().get("itemName");
String itemSpec = modelAction.getParaMap().get("itemSpec");
String itemType = modelAction.getParaMap().get("itemType");
String dataAuth = modelAction.getRequest().getParameter("data_auth");//组织机构
String userId = modelAction.getSessionUser().getId();//用户id
//根据物料、物料组查询条件得到所对应的物料组
String querySql = "SELECT row_number() over() as ROWNUM,T1.ID,T1.CIG_SN,T1.CIG_NAME,T1.CIG_TYPE,T1.DATA_AUTH,SD.NAME AS DATA_AUTH2 " +
"FROM T_CO_ITEM_GROUP T1 " +
"LEFT JOIN SY_DEPT SD ON SD.ID = T1.DATA_AUTH " +
"WHERE T1.CIG_SN IN "+
"(SELECT CIG_SN FROM T_CO_ITEM_CONNECT T2 "+
"WHERE T1.CIG_SN = T2.CIG_SN "+
"AND T2.CIC_ITEM_CODE IN "+
"(SELECT CI_ITEM_CODE "+
"FROM T_CO_ITEM T3 "+
"WHERE T2.CIC_ITEM_CODE = T3.CI_ITEM_CODE ";
Map<String, String> map = new HashMap<String, String>();
if(StringUtils.isNotBlank(dataAuth)){
querySql += " AND T1.DATA_AUTH = :DATA_AUTH1 AND T2.DATA_AUTH = :DATA_AUTH2 AND T3.DATA_AUTH = :DATA_AUTH3 ";
map.put("DATA_AUTH1", dataAuth);
map.put("DATA_AUTH2", dataAuth);
map.put("DATA_AUTH3", dataAuth);
}else {
querySql+=" and T3.DATA_AUTH in (select DEPT_ID from sy_data_auth where user_id = :user_id) AA ";
map.put("user_id",userId);
}
if(StringUtils.isNotBlank(itemCode)){
querySql += " AND T3.CI_ITEM_CODE LIKE '%' || :itemCode || '%'";
map.put("itemCode", itemCode);
}
if(StringUtils.isNotBlank(itemName)){
querySql += " AND T3.CI_ITEM_NAME LIKE '%' || :itemName || '%'";
map.put("itemName", itemName);
}
if(StringUtils.isNotBlank(itemSpec)){
querySql += " AND T3.CI_ITEM_SPEC LIKE '%' || :itemSpec || '%'";
map.put("itemSpec", itemSpec);
}
if(StringUtils.isNotBlank(itemType)){
querySql += " AND T3.CI_ITEM_TYPE = :itemType ";
map.put("itemType", itemType);
}
querySql += "))";
if(StringUtils.isNotBlank(cigName)){
querySql += " AND T1.CIG_NAME LIKE '%' || :cigName || '%'";
map.put("cigName", cigName);
}
if(StringUtils.isNotBlank(cigType)){
querySql += " AND T1.CIG_TYPE = :cigType ";
map.put("cigType", cigType);
}
if(StringUtils.isBlank(dataAuth)){
querySql+=" AND T1.DATA_AUTH in (select DEPT_ID from sy_data_auth where user_id = :user_id1) ";
map.put("user_id1",userId);
}
List itemList = modelService.listSql(querySql, modelAction.getPage(), map,null,null);
modelAction.setAjaxPage(modelAction.getPage());
modelAction.getAjaxPage().setDataList(itemList);
CommMethod.listMapToEscapeJs(itemList);
return BaseActionSupport.AJAX;
}
}
| UTF-8 | Java | 3,837 | java | AjaxFindItemBySnAndCondition.java | Java | []
| null | []
| package com.more.buss.eis.bd.basedos.service.pg;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.more.fw.core.base.core.action.BaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.more.fw.core.common.method.StringUtils;
import com.more.fw.core.base.core.action.ModelAction;
import com.more.fw.core.dbo.model.service.ModelService;
import com.more.fw.core.common.method.CommMethod;
import com.more.fw.core.dbo.model.service.impl.base.FuncService;
/**
* @Description 根据物料组物料获取信息
* @ClassName AjaxFindItemBySnAndCondition
* @author
*/
public class AjaxFindItemBySnAndCondition implements FuncService {
private final Log log = LogFactory.getLog(this.getClass());
@Override
public String exeFunc(ModelAction modelAction, ModelService modelService) {
String cigName = modelAction.getParaMap().get("cigName");
String cigType = modelAction.getParaMap().get("cigType");
String itemCode = modelAction.getParaMap().get("itemCode");
String itemName = modelAction.getParaMap().get("itemName");
String itemSpec = modelAction.getParaMap().get("itemSpec");
String itemType = modelAction.getParaMap().get("itemType");
String dataAuth = modelAction.getRequest().getParameter("data_auth");//组织机构
String userId = modelAction.getSessionUser().getId();//用户id
//根据物料、物料组查询条件得到所对应的物料组
String querySql = "SELECT row_number() over() as ROWNUM,T1.ID,T1.CIG_SN,T1.CIG_NAME,T1.CIG_TYPE,T1.DATA_AUTH,SD.NAME AS DATA_AUTH2 " +
"FROM T_CO_ITEM_GROUP T1 " +
"LEFT JOIN SY_DEPT SD ON SD.ID = T1.DATA_AUTH " +
"WHERE T1.CIG_SN IN "+
"(SELECT CIG_SN FROM T_CO_ITEM_CONNECT T2 "+
"WHERE T1.CIG_SN = T2.CIG_SN "+
"AND T2.CIC_ITEM_CODE IN "+
"(SELECT CI_ITEM_CODE "+
"FROM T_CO_ITEM T3 "+
"WHERE T2.CIC_ITEM_CODE = T3.CI_ITEM_CODE ";
Map<String, String> map = new HashMap<String, String>();
if(StringUtils.isNotBlank(dataAuth)){
querySql += " AND T1.DATA_AUTH = :DATA_AUTH1 AND T2.DATA_AUTH = :DATA_AUTH2 AND T3.DATA_AUTH = :DATA_AUTH3 ";
map.put("DATA_AUTH1", dataAuth);
map.put("DATA_AUTH2", dataAuth);
map.put("DATA_AUTH3", dataAuth);
}else {
querySql+=" and T3.DATA_AUTH in (select DEPT_ID from sy_data_auth where user_id = :user_id) AA ";
map.put("user_id",userId);
}
if(StringUtils.isNotBlank(itemCode)){
querySql += " AND T3.CI_ITEM_CODE LIKE '%' || :itemCode || '%'";
map.put("itemCode", itemCode);
}
if(StringUtils.isNotBlank(itemName)){
querySql += " AND T3.CI_ITEM_NAME LIKE '%' || :itemName || '%'";
map.put("itemName", itemName);
}
if(StringUtils.isNotBlank(itemSpec)){
querySql += " AND T3.CI_ITEM_SPEC LIKE '%' || :itemSpec || '%'";
map.put("itemSpec", itemSpec);
}
if(StringUtils.isNotBlank(itemType)){
querySql += " AND T3.CI_ITEM_TYPE = :itemType ";
map.put("itemType", itemType);
}
querySql += "))";
if(StringUtils.isNotBlank(cigName)){
querySql += " AND T1.CIG_NAME LIKE '%' || :cigName || '%'";
map.put("cigName", cigName);
}
if(StringUtils.isNotBlank(cigType)){
querySql += " AND T1.CIG_TYPE = :cigType ";
map.put("cigType", cigType);
}
if(StringUtils.isBlank(dataAuth)){
querySql+=" AND T1.DATA_AUTH in (select DEPT_ID from sy_data_auth where user_id = :user_id1) ";
map.put("user_id1",userId);
}
List itemList = modelService.listSql(querySql, modelAction.getPage(), map,null,null);
modelAction.setAjaxPage(modelAction.getPage());
modelAction.getAjaxPage().setDataList(itemList);
CommMethod.listMapToEscapeJs(itemList);
return BaseActionSupport.AJAX;
}
}
| 3,837 | 0.668439 | 0.659133 | 98 | 37.377552 | 28.21402 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.326531 | false | false | 2 |
6bd94e3c7166aa32e34d82e229a426d4e5614db1 | 35,923,106,496,389 | 57a2850b31921598d4fcad52ddd271bca4717383 | /src/main/java/com/qa/ims/persistence/dao/OrderDAO.java | dc3b052dbd176f5972a164cb0929426659ec16fc | [
"MIT"
]
| permissive | NDuggan-dev/IMS-JuneSDET-Niall | https://github.com/NDuggan-dev/IMS-JuneSDET-Niall | a953c28053c97c3da45b8dfe8dd29e4a331ba0b9 | 11b5ea598610d432117fb3665576d7b5b5d60849 | refs/heads/main | 2023-06-17T00:44:37.211000 | 2021-07-16T14:04:28 | 2021-07-16T14:04:28 | 384,134,961 | 0 | 0 | MIT | false | 2021-07-16T14:04:29 | 2021-07-08T13:32:50 | 2021-07-16T11:01:59 | 2021-07-16T14:04:28 | 6,585 | 0 | 0 | 0 | Java | false | false | package com.qa.ims.persistence.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.qa.ims.persistence.OrderBuilder;
import com.qa.ims.persistence.domain.Customer;
import com.qa.ims.persistence.domain.Item;
import com.qa.ims.persistence.domain.Order;
import com.qa.ims.utils.DBUtilsPool;
public class OrderDAO implements Dao<Order> {
private static final Logger LOGGER = LogManager.getLogger();
private static final ItemDAO itemDAO = new ItemDAO();
//private static final DataSource dataSource = DBUtilsPool.getDataSource();
@Override
public Order modelFromResultSet(ResultSet resultSet) throws SQLException {
Long id = resultSet.getLong("order_id");
Long customerId = resultSet.getLong("customer_id");
Date orderDate = resultSet.getDate("order_date");
List<Item> itemList = itemMapToList(readItemMap(id));
return new OrderBuilder().id(id).customerId(customerId).orderDate(orderDate).itemList(itemList).build();
}
/**
* Reads all customers from the database
*
* @return A list of customers
*/
@Override
public HashMap<Long, Order> readAll(){
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM orders");) {
HashMap<Long, Order> orders = new HashMap<>();
while (resultSet.next()) {
orders.put(modelFromResultSet(resultSet).getId(), modelFromResultSet(resultSet));
}
return orders;
} catch (SQLException e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public Order readLatest() {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM orders ORDER BY order_id DESC LIMIT 1");) {
resultSet.next();
return modelFromResultSet(resultSet);
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Creates a customer in the database
*
* @param customer - takes in a customer object. id will be ignored
*/
@Override
public Order create(Order order){
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("INSERT INTO orders(customer_id) VALUES (?)");) {
statement.setLong(1, order.getCustomerId());
statement.executeUpdate();
readLatest();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
List<Item> items = order.getItemList();
Order thisOrder = readLatest();
if(items != null) {
for(Item item : items) {
addItemToOrder(thisOrder, item);
}
}
return readLatest();
}
@Override
public Order read(Long id) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM orders WHERE order_id = ?");) {
statement.setLong(1, id);
try (ResultSet resultSet = statement.executeQuery();) {
resultSet.next();
return modelFromResultSet(resultSet);
}
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Updates a customer in the database
*
* @param customer - takes in a customer object, the id field will be used to
* update that customer in the database
* @return
*/
@Override
public Order update(Order order) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("UPDATE orders SET order_date = now() WHERE order_id = ?");) {
statement.setLong(1, order.getId());
statement.executeUpdate();
return read(order.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Deletes a customer in the database
*
* @param id - id of the customer
*/
@Override
public int delete(long id) {
deleteFromOrderItems(id);
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("DELETE FROM orders WHERE order_id = ?");) {
statement.setLong(1, id);
return statement.executeUpdate();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return 0;
}
public int deleteFromOrderItems(long id) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("DELETE FROM orders_items WHERE order_id = ?");) {
statement.setLong(1, id);
return statement.executeUpdate();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return 0;
}
public Order addItemToOrder(Order thisOrder, Item item) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("INSERT INTO orders_items(order_id, item_id) VALUES (?, ?)");) {
statement.setLong(1, thisOrder.getId());
statement.setLong(2, item.getItemId());
statement.executeUpdate();
update(thisOrder);
return read(thisOrder.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public HashMap<Long, Item> readItemMap(Long orderId){
HashMap<Long, Item> itemMap = new HashMap<>();
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement =
connection.prepareStatement("SELECT * FROM orders_items WHERE order_id = ?");) {
statement.setLong(1, orderId);
try (ResultSet resultSet = statement.executeQuery();) {
return listItemFromResultSet(resultSet);
}
}catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return itemMap;
}
public HashMap<Long, Item> listItemFromResultSet(ResultSet resultSet){
HashMap<Long, Item> itemList = new HashMap<>();
try {
while(resultSet.next()) {
Item item = itemDAO.read(resultSet.getLong("item_id"));
itemList.put(resultSet.getLong("orders_items_id"), item);
}
} catch (SQLException e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return itemList;
}
public Order deleteItemFromOrder(Long id, Order thisOrder) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("DELETE FROM orders_items WHERE orders_items_id = ?");) {
statement.setLong(1, id);
statement.executeUpdate();
update(thisOrder);
return read(thisOrder.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public List<Item> itemMapToList(HashMap<Long, Item> itemMap){
List<Item> itemList = new ArrayList<Item>();
for(Entry<Long, Item> item : itemMap.entrySet()) {
itemList.add(item.getValue());
}
return itemList;
}
}
| UTF-8 | Java | 7,541 | java | OrderDAO.java | Java | []
| null | []
| package com.qa.ims.persistence.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.qa.ims.persistence.OrderBuilder;
import com.qa.ims.persistence.domain.Customer;
import com.qa.ims.persistence.domain.Item;
import com.qa.ims.persistence.domain.Order;
import com.qa.ims.utils.DBUtilsPool;
public class OrderDAO implements Dao<Order> {
private static final Logger LOGGER = LogManager.getLogger();
private static final ItemDAO itemDAO = new ItemDAO();
//private static final DataSource dataSource = DBUtilsPool.getDataSource();
@Override
public Order modelFromResultSet(ResultSet resultSet) throws SQLException {
Long id = resultSet.getLong("order_id");
Long customerId = resultSet.getLong("customer_id");
Date orderDate = resultSet.getDate("order_date");
List<Item> itemList = itemMapToList(readItemMap(id));
return new OrderBuilder().id(id).customerId(customerId).orderDate(orderDate).itemList(itemList).build();
}
/**
* Reads all customers from the database
*
* @return A list of customers
*/
@Override
public HashMap<Long, Order> readAll(){
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM orders");) {
HashMap<Long, Order> orders = new HashMap<>();
while (resultSet.next()) {
orders.put(modelFromResultSet(resultSet).getId(), modelFromResultSet(resultSet));
}
return orders;
} catch (SQLException e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public Order readLatest() {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM orders ORDER BY order_id DESC LIMIT 1");) {
resultSet.next();
return modelFromResultSet(resultSet);
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Creates a customer in the database
*
* @param customer - takes in a customer object. id will be ignored
*/
@Override
public Order create(Order order){
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("INSERT INTO orders(customer_id) VALUES (?)");) {
statement.setLong(1, order.getCustomerId());
statement.executeUpdate();
readLatest();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
List<Item> items = order.getItemList();
Order thisOrder = readLatest();
if(items != null) {
for(Item item : items) {
addItemToOrder(thisOrder, item);
}
}
return readLatest();
}
@Override
public Order read(Long id) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM orders WHERE order_id = ?");) {
statement.setLong(1, id);
try (ResultSet resultSet = statement.executeQuery();) {
resultSet.next();
return modelFromResultSet(resultSet);
}
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Updates a customer in the database
*
* @param customer - takes in a customer object, the id field will be used to
* update that customer in the database
* @return
*/
@Override
public Order update(Order order) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("UPDATE orders SET order_date = now() WHERE order_id = ?");) {
statement.setLong(1, order.getId());
statement.executeUpdate();
return read(order.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
/**
* Deletes a customer in the database
*
* @param id - id of the customer
*/
@Override
public int delete(long id) {
deleteFromOrderItems(id);
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("DELETE FROM orders WHERE order_id = ?");) {
statement.setLong(1, id);
return statement.executeUpdate();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return 0;
}
public int deleteFromOrderItems(long id) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("DELETE FROM orders_items WHERE order_id = ?");) {
statement.setLong(1, id);
return statement.executeUpdate();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return 0;
}
public Order addItemToOrder(Order thisOrder, Item item) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("INSERT INTO orders_items(order_id, item_id) VALUES (?, ?)");) {
statement.setLong(1, thisOrder.getId());
statement.setLong(2, item.getItemId());
statement.executeUpdate();
update(thisOrder);
return read(thisOrder.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public HashMap<Long, Item> readItemMap(Long orderId){
HashMap<Long, Item> itemMap = new HashMap<>();
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement =
connection.prepareStatement("SELECT * FROM orders_items WHERE order_id = ?");) {
statement.setLong(1, orderId);
try (ResultSet resultSet = statement.executeQuery();) {
return listItemFromResultSet(resultSet);
}
}catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return itemMap;
}
public HashMap<Long, Item> listItemFromResultSet(ResultSet resultSet){
HashMap<Long, Item> itemList = new HashMap<>();
try {
while(resultSet.next()) {
Item item = itemDAO.read(resultSet.getLong("item_id"));
itemList.put(resultSet.getLong("orders_items_id"), item);
}
} catch (SQLException e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return itemList;
}
public Order deleteItemFromOrder(Long id, Order thisOrder) {
try (Connection connection = DBUtilsPool.getDataSource().getConnection();
PreparedStatement statement = connection
.prepareStatement("DELETE FROM orders_items WHERE orders_items_id = ?");) {
statement.setLong(1, id);
statement.executeUpdate();
update(thisOrder);
return read(thisOrder.getId());
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
public List<Item> itemMapToList(HashMap<Long, Item> itemMap){
List<Item> itemList = new ArrayList<Item>();
for(Entry<Long, Item> item : itemMap.entrySet()) {
itemList.add(item.getValue());
}
return itemList;
}
}
| 7,541 | 0.68784 | 0.685983 | 242 | 30.161158 | 25.783485 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.334711 | false | false | 2 |
1dfd0146d113a84fc6e1dfde0f5580577cdaa915 | 36,910,948,970,764 | 937beabc1431d0c7a421284539a9cc688b37ca05 | /src/main/java/com/proxibanque/model/Gerant.java | 689ebd96723afa38b00986f1da9af616de811a4d | []
| no_license | Badr-tech/ProxiBanqueV1 | https://github.com/Badr-tech/ProxiBanqueV1 | e0435a6096ec439d13a039b4d7125f9b9bee490e | b616d31bede97cf9c01fa1d77a2f17d169e6db9c | refs/heads/master | 2022-01-16T11:41:54.482000 | 2019-07-20T18:18:18 | 2019-07-20T18:18:18 | 197,813,847 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.proxibanque.model;
public class Gerant extends Personne {
private String login;
private String password;
// Constructeurs
public Gerant(int id, String nom, String prenom, int codePostal, int telephone, String ville, String login,
String password) {
super(id, nom, prenom, codePostal, telephone, ville);
this.login = login;
this.password = password;
}
// Gettesr & Setters
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Gerant [login=" + login + ", password=" + password + "]";
}
}
| UTF-8 | Java | 760 | java | Gerant.java | Java | [
{
"context": "e, ville);\n\t\tthis.login = login;\n\t\tthis.password = password;\n\t}\n\n\t// Gettesr & Setters\n\tpublic String getLogi",
"end": 375,
"score": 0.9480803608894348,
"start": 367,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tret",
"end": 639,
"score": 0.9694356322288513,
"start": 631,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.proxibanque.model;
public class Gerant extends Personne {
private String login;
private String password;
// Constructeurs
public Gerant(int id, String nom, String prenom, int codePostal, int telephone, String ville, String login,
String password) {
super(id, nom, prenom, codePostal, telephone, ville);
this.login = login;
this.password = <PASSWORD>;
}
// Gettesr & Setters
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@Override
public String toString() {
return "Gerant [login=" + login + ", password=" + password + "]";
}
}
| 764 | 0.696053 | 0.696053 | 39 | 18.487179 | 22.109137 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.564103 | false | false | 2 |
18687c90749492cf63add14e3f6ab202ed97826f | 35,304,631,221,683 | d82a56d3bbb4bca1dd7b2d97af76b9d409775b8d | /app/src/main/java/com/example/administrator/myapplication/activity/ExchangePush.java | 07814662da3198422d2ed7c920e99dc659912f37 | []
| no_license | zh-shasha/nongjiyun | https://github.com/zh-shasha/nongjiyun | 58473e5ca09fba2ba2268bce98fa0aab9531dd79 | 3507a7ebf34847ecd0e706888957868d2b3edaf5 | refs/heads/master | 2020-05-05T02:03:04.997000 | 2018-06-24T14:59:20 | 2018-06-24T14:59:20 | 179,622,930 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.myapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.utils.GlideLoader;
import com.example.administrator.myapplication.utils.Utils;
import com.jaiky.imagespickers.ImageConfig;
import com.jaiky.imagespickers.ImageSelector;
import com.jaiky.imagespickers.ImageSelectorActivity;
import java.util.ArrayList;
import java.util.List;
public class ExchangePush extends AppCompatActivity implements AMapLocationListener {
private AMapLocationClient locationClient = null;
private AMapLocationClientOption locationOption = null;
private TextView textView;
private String[] strMsg;
private ArrayList<String> path = new ArrayList<>();
public static final int REQUEST_CODE = 123;
private ImageConfig imageConfig;
private RadioButton quick_question_photo_rb;
private RadioButton quick_question_video_rb;
private LinearLayout llContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_push);
quick_question_photo_rb = findViewById(R.id.quick_question_photo_rb);
quick_question_video_rb = findViewById(R.id.quick_question_video_rb);
llContainer = (LinearLayout) findViewById(R.id.llContainer);
textView=findViewById(R.id.tv_adress);
ImageView exchange_push_back_iv = (ImageView) findViewById(R.id.exchange_push_back_iv);
exchange_push_back_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
quick_question_photo_rb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageConfig = new ImageConfig.Builder(
new GlideLoader())
.steepToolBarColor(getResources().getColor(R.color.green))
.titleBgColor(getResources().getColor(R.color.green))
.titleSubmitTextColor(getResources().getColor(R.color.white))
.titleTextColor(getResources().getColor(R.color.white))
// 开启多选 (默认为多选)
.mutiSelect()
// 多选时的最大数量 (默认 9 张)
.mutiSelectMaxSize(9)
//设置图片显示容器,参数:、(容器,每行显示数量,是否可删除)
.setContainer(llContainer, 3, true)
// 已选择的图片路径
.pathList(path)
// 拍照后存放的图片路径(默认 /temp/picture)
.filePath("/temp")
// 开启拍照功能 (默认关闭)
.showCamera()
.requestCode(REQUEST_CODE)
.build();
ImageSelector.open(ExchangePush.this, imageConfig);
}
});
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Location();
}
});
}
@Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
// tv1.setText("");
// for (String path : pathList) {
// tv1.append(path);
// tv1.append("\n");
// }
path.clear();
path.addAll(pathList);
}
}
private void Location() {
try {
locationClient = new AMapLocationClient(this);
locationOption = new AMapLocationClientOption();
// 设置定位模式为低功耗模式
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
// 设置定位监听
locationClient.setLocationListener(this);
locationOption.setOnceLocation(true);//设置为单次定位
locationClient.setLocationOption(locationOption);// 设置定位参数
// 启动定位
locationClient.startLocation();
mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
} catch (Exception e) {
Toast.makeText(ExchangePush.this, "定位失败", Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationChanged(AMapLocation loc) {
if (null != loc) {
Message msg = mHandler.obtainMessage();
msg.obj = loc;
msg.what = Utils.MSG_LOCATION_FINISH;
mHandler.sendMessage(msg);
}
}
Handler mHandler = new Handler() {
public void dispatchMessage(android.os.Message msg) {
switch (msg.what) {
//定位完成
case Utils.MSG_LOCATION_FINISH:
String result = "";
try {
AMapLocation loc = (AMapLocation) msg.obj;
result = Utils.getLocationStr(loc, 1);
strMsg = result.split(",");
Toast.makeText(ExchangePush.this, "定位成功", Toast.LENGTH_LONG).show();
// textView.setText("地址:" + strMsg[0] + "\n" + "经 度:" + strMsg[1] + "\n" + "纬 度:" + strMsg[1]);
textView.setText(strMsg[0]);
} catch (Exception e) {
Toast.makeText(ExchangePush.this, "定位失败", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
};
}
| UTF-8 | Java | 6,703 | java | ExchangePush.java | Java | []
| null | []
| package com.example.administrator.myapplication.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.utils.GlideLoader;
import com.example.administrator.myapplication.utils.Utils;
import com.jaiky.imagespickers.ImageConfig;
import com.jaiky.imagespickers.ImageSelector;
import com.jaiky.imagespickers.ImageSelectorActivity;
import java.util.ArrayList;
import java.util.List;
public class ExchangePush extends AppCompatActivity implements AMapLocationListener {
private AMapLocationClient locationClient = null;
private AMapLocationClientOption locationOption = null;
private TextView textView;
private String[] strMsg;
private ArrayList<String> path = new ArrayList<>();
public static final int REQUEST_CODE = 123;
private ImageConfig imageConfig;
private RadioButton quick_question_photo_rb;
private RadioButton quick_question_video_rb;
private LinearLayout llContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exchange_push);
quick_question_photo_rb = findViewById(R.id.quick_question_photo_rb);
quick_question_video_rb = findViewById(R.id.quick_question_video_rb);
llContainer = (LinearLayout) findViewById(R.id.llContainer);
textView=findViewById(R.id.tv_adress);
ImageView exchange_push_back_iv = (ImageView) findViewById(R.id.exchange_push_back_iv);
exchange_push_back_iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
quick_question_photo_rb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imageConfig = new ImageConfig.Builder(
new GlideLoader())
.steepToolBarColor(getResources().getColor(R.color.green))
.titleBgColor(getResources().getColor(R.color.green))
.titleSubmitTextColor(getResources().getColor(R.color.white))
.titleTextColor(getResources().getColor(R.color.white))
// 开启多选 (默认为多选)
.mutiSelect()
// 多选时的最大数量 (默认 9 张)
.mutiSelectMaxSize(9)
//设置图片显示容器,参数:、(容器,每行显示数量,是否可删除)
.setContainer(llContainer, 3, true)
// 已选择的图片路径
.pathList(path)
// 拍照后存放的图片路径(默认 /temp/picture)
.filePath("/temp")
// 开启拍照功能 (默认关闭)
.showCamera()
.requestCode(REQUEST_CODE)
.build();
ImageSelector.open(ExchangePush.this, imageConfig);
}
});
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Location();
}
});
}
@Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
// tv1.setText("");
// for (String path : pathList) {
// tv1.append(path);
// tv1.append("\n");
// }
path.clear();
path.addAll(pathList);
}
}
private void Location() {
try {
locationClient = new AMapLocationClient(this);
locationOption = new AMapLocationClientOption();
// 设置定位模式为低功耗模式
locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
// 设置定位监听
locationClient.setLocationListener(this);
locationOption.setOnceLocation(true);//设置为单次定位
locationClient.setLocationOption(locationOption);// 设置定位参数
// 启动定位
locationClient.startLocation();
mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
} catch (Exception e) {
Toast.makeText(ExchangePush.this, "定位失败", Toast.LENGTH_LONG).show();
}
}
@Override
public void onLocationChanged(AMapLocation loc) {
if (null != loc) {
Message msg = mHandler.obtainMessage();
msg.obj = loc;
msg.what = Utils.MSG_LOCATION_FINISH;
mHandler.sendMessage(msg);
}
}
Handler mHandler = new Handler() {
public void dispatchMessage(android.os.Message msg) {
switch (msg.what) {
//定位完成
case Utils.MSG_LOCATION_FINISH:
String result = "";
try {
AMapLocation loc = (AMapLocation) msg.obj;
result = Utils.getLocationStr(loc, 1);
strMsg = result.split(",");
Toast.makeText(ExchangePush.this, "定位成功", Toast.LENGTH_LONG).show();
// textView.setText("地址:" + strMsg[0] + "\n" + "经 度:" + strMsg[1] + "\n" + "纬 度:" + strMsg[1]);
textView.setText(strMsg[0]);
} catch (Exception e) {
Toast.makeText(ExchangePush.this, "定位失败", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
};
}
| 6,703 | 0.584517 | 0.582176 | 161 | 38.795033 | 25.876947 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583851 | false | false | 2 |
24f8b802fbea67a7084bf7a2c7f432499d41410f | 34,626,026,394,850 | 6a4717fd3bfd68435fb054f93cf61d16daef41db | /qh_inspect/src/main/java/com/miu360/taxi_check/ui/ChckItemLeiBieJYActivity.java | 9b77ea0c3df54872d2ddba45dbec8ef9b2a6d2d8 | [
"Apache-2.0"
]
| permissive | mc190diancom/taxi_inspect | https://github.com/mc190diancom/taxi_inspect | 79a9d4ed1ac5666ca33090c6c81e2763c9bac79c | 8e07e03006f520c1f33a6c5cad59e14e5eae34dd | refs/heads/master | 2020-05-17T23:58:05.046000 | 2019-07-04T09:24:55 | 2019-07-04T09:24:55 | 184,045,911 | 0 | 0 | Apache-2.0 | true | 2019-06-25T07:18:43 | 2019-04-29T09:58:41 | 2019-06-20T11:51:40 | 2019-06-25T07:18:42 | 44,865 | 0 | 0 | 0 | Java | false | false | package com.miu360.taxi_check.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lubao.lubao.async.AsyncUtil;
import com.lubao.lubao.async.Callback;
import com.lubao.lubao.async.Result;
import com.miu360.inspect.R;
import com.miu360.taxi_check.BaseActivity;
import com.miu360.taxi_check.common.CommonDialog.OnDialogItemClickListener;
import com.miu30.common.util.MyProgressDialog;
import com.miu360.taxi_check.common.Windows;
import com.miu360.taxi_check.data.WeiFaCheckPreference;
import com.miu360.taxi_check.data.WeiZhanData;
import com.miu360.taxi_check.model.FaGuiDetailAllInfo;
import com.miu360.taxi_check.model.FaGuiQueryInfo;
import com.miu360.taxi_check.model.JCLBQ;
import com.miu360.taxi_check.model.JclbModel;
import com.miu360.taxi_check.util.UIUtils;
import com.miu360.taxi_check.view.HeaderHolder;
import com.miu360.taxi_check.view.ListViewHolder;
public class ChckItemLeiBieJYActivity extends BaseActivity implements OnClickListener {
@ViewInject(R.id.leibie_show)
private LinearLayout leibie_show;
@ViewInject(R.id.check_leibie)
private TextView check_leibie;
@ViewInject(R.id.leibie_daima)
private TextView leibie_daima;// 代码
@ViewInject(R.id.leibie_neirong)
private TextView leibie_neirong;// 检查内容
@ViewInject(R.id.leibie_query)
private TextView leibie_query;
@ViewInject(R.id.leibie_hide)
private TextView leibie_hide;
ListViewHolder holder;
CheckItemLeiBieAdapter adapter;
ArrayList<FaGuiDetailAllInfo> testList = new ArrayList<>();
ArrayList<String> list = new ArrayList<>();
View root;
boolean isOver = true;
String resultString = "";
String bjczt = "";
HeaderHolder header;
String[] itemOne;
ArrayList<JclbModel> arrayListJclb;
FaGuiQueryInfo info = new FaGuiQueryInfo();
//对获取的数据进行排序
Comparator<FaGuiDetailAllInfo> comparator = new Comparator<FaGuiDetailAllInfo>() {
public int compare(FaGuiDetailAllInfo f1, FaGuiDetailAllInfo f2) {
// 先排JCLB
if (!f1.getJCLB().equals(f2.getJCLB())) {
return f1.getJCLB().compareTo(f2.getJCLB());
} else if (!f1.getBM().equals(f2.getBM())) {
return f1.getBM().compareTo(f2.getBM());
} else{
}
return 0;
}
};
//对获取的数据进行排序
Comparator<JclbModel> comparator2 = new Comparator<JclbModel>() {
public int compare(JclbModel f1, JclbModel f2) {
// 先排JCLB
if (!f1.getJCLB().equals(f2.getJCLB())) {
return f1.getJCLB().compareTo(f2.getJCLB());
} else{
}
return 0;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chck_item_lei_bie);
initView();
arrayListJclb = new ArrayList<>();
bjczt = getIntent().getStringExtra("bjczt");
info.setHYLB(getIntent().getStringExtra("HYLB"));
info.setStartIndex(0);
info.setEndIndex(120);
final JCLBQ jclbq = new JCLBQ();
if(bjczt!=null && bjczt!=""){
jclbq.setBjczt(bjczt);
}else{
jclbq.setBjczt("出租汽车驾驶员");
}
AsyncUtil.goAsync(new Callable<Result<List<JclbModel>>>() {
@Override
public Result<List<JclbModel>> call() throws Exception {
return WeiZhanData.getJclb_old(jclbq);
}
}, new Callback<Result<List<JclbModel>>>() {
@Override
public void onHandle(Result<List<JclbModel>> result) {
if (result.ok()) {
if(info.getHYLB()!=null){
if(info.getHYLB().contains("非营运车")){
JclbModel c = new JclbModel();
c.setJCLB("00全部");
arrayListJclb.add(c);
arrayListJclb.add(result.getData().get(0));
Collections.sort(arrayListJclb, comparator2);
}else{
arrayListJclb.addAll(result.getData());
//arrayListJclb.remove(0);
JclbModel c = new JclbModel();
c.setJCLB("00全部");
arrayListJclb.add(c);
Collections.sort(arrayListJclb, comparator2);
}
itemOne = new String[arrayListJclb.size()];
for (int i = 0; i < arrayListJclb.size(); i++) {
itemOne[i] = arrayListJclb.get(i).getJCLB();
}
}
} else {
//UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
holder = ListViewHolder.initList(self);
adapter = new CheckItemLeiBieAdapter();
//root = LayoutInflater.from(self).inflate(R.layout.checkitemleibieadapterheader, null);
holder.list.setMode(Mode.DISABLED);
holder.list.setVisibility(View.GONE);
holder.list.setAdapter(adapter);
//holder.list.getRefreshableView().addHeaderView(root);
holder.list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
FaGuiDetailAllInfo info = (FaGuiDetailAllInfo) arg0.getItemAtPosition(arg2);
// Intent intent = new Intent(self,
// CheckDetailWeiFaActivity.class);
// intent.putExtra("FaGuiDetailAllInfo", info);
// startActivity(intent);
}
});
queryAll();
}
private void initView() {
ViewUtils.inject(self);
WeiFaCheckPreference pref = new WeiFaCheckPreference(self);
int count = pref.getInt("resultPeopleSize", -1);
for (int i = 0; i < count; i++) {
String s = pref.getString("checkPositionContext_" + i, "");
if (!TextUtils.isEmpty(s)) {
checkPositionContext.add(s);
}
}
header = new HeaderHolder();
header.init(self, "检查项");
header.leftBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isOver) {
Intent intent = new Intent();
intent.putExtra("result", resultString);
//intent.putExtra(name, value);
setResult(RESULT_OK, intent);
}
finish();
}
});
header.rightTextBtn.setVisibility(View.VISIBLE);
header.rightTextBtn.setText("确认");
header.rightTextBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isOver = false;
Intent intent = new Intent();
WeiFaCheckPreference prefer = new WeiFaCheckPreference(self);
prefer.clearPreference();
prefer.setInt("resultPeopleSize", checkPositionContext.size());
intent.putExtra("resultPeopleSize", checkPositionContext.size());
Iterator<String> iter = checkPositionContext.iterator();
int count = 0;
while(iter.hasNext()){
String s = iter.next();
prefer.setString("checkPositionContext_"+count, s);
intent.putExtra("resultPeople_"+count, s);
count++;
}
intent.putStringArrayListExtra("jclb", jclbList);
intent.putStringArrayListExtra("wfxwId", wfxwIdList);
intent.putStringArrayListExtra("wfqxId", wfqxIdList);
intent.putExtra("checkBJCZT", bjczt);
setResult(RESULT_OK, intent);
finish();
}
});
leibie_hide.setOnClickListener(this);
check_leibie.setOnClickListener(this);
leibie_query.setOnClickListener(this);
}
String jcnr;
String code;
String jclb;
private void initQuery() {
holder.list.setVisibility(View.GONE);
jcnr = leibie_neirong.getText().toString();
code = leibie_daima.getText().toString().toUpperCase();
jclb = check_leibie.getText().toString();
FaGuiQueryInfo info = new FaGuiQueryInfo();
info.setCODE(code);
info.setJCLB(jclb);
info.setJCNR(jcnr);
info.setBjczt(bjczt);
info.setHYLB(getIntent().getStringExtra("HYLB"));
/*info.setStartIndex(0 + testList.size());
info.setEndIndex(10 + testList.size());*/
if(info.getJCLB()!=null){
if(info.getJCLB().contains("00全部")){
info.setJCLB("");
queryFenLei(info);
}else{
queryFenLei(info);
}
}else{
queryFenLei(info);
}
}
private void queryAll(){
final FaGuiQueryInfo infoall = new FaGuiQueryInfo();
infoall.setHYLB(getIntent().getStringExtra("HYLB"));
infoall.setBjczt(bjczt);
final MyProgressDialog pd = Windows.waiting(self);
AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryCheckItemInfo(infoall);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
pd.dismiss();
if (result.ok()) {
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "查不到数据", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
/*AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryFaGuiAllInfo(info);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
holder.list.onRefreshComplete();
if (result.ok()) {
if (result.getData() == null) {
UIUtils.toast(self, "无信息", Toast.LENGTH_LONG);
return;
}
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "无信息", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
//testList.addAll(result.getData());
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
//UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});*/
}
private void queryFenLei(final FaGuiQueryInfo info){
final MyProgressDialog pd = Windows.waiting(self);
AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryCheckItemInfo(info);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
pd.dismiss();
if (result.ok()) {
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "查不到数据", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
}
@Override
public void onClick(View v) {
if (v == leibie_hide) {
if (leibie_show.getVisibility() == View.GONE) {
leibie_show.setVisibility(View.VISIBLE);
} else {
leibie_show.setVisibility(View.GONE);
}
} else if (v == check_leibie) {
Windows.singleChoice(self, "选择检查类别", itemOne, new OnDialogItemClickListener() {
@Override
public void dialogItemClickListener(int position) {
check_leibie.setText(itemOne[position]);
testList.clear();
initQuery();
}
});
} else if (v == leibie_query) {
if (TextUtils.isEmpty(check_leibie.getText().toString()) &&
TextUtils.isEmpty(leibie_neirong.getText().toString())&&
TextUtils.isEmpty(leibie_daima.getText().toString().toUpperCase())) {
UIUtils.toast(self, "请输入请求参数", Toast.LENGTH_SHORT);
return;
}
testList.clear();
initQuery();
}
}
HashMap<Integer, String> result = new HashMap<>();
// HashSet<Integer> checkPosition = new HashSet<Integer>();
ArrayList<Integer> position = new ArrayList<>();
HashSet<String> resultStr = new HashSet<>();
ArrayList<String> resultArr = new ArrayList<>();
ArrayList<String> jclbList = new ArrayList<>();//存储勾选内容的检查类别
ArrayList<String> wfxwIdList = new ArrayList<>();//违法行为id
ArrayList<String> wfqxIdList = new ArrayList<>();//违法情形id
HashSet<String> checkPositionContext = new HashSet<String>();
private class CheckItemLeiBieAdapter extends BaseAdapter {
ViewHolderCheckItemLeiBie holder;
@Override
public int getCount() {
return testList.size();
}
@Override
public Object getItem(int arg0) {
return testList.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(final int arg0, View arg1, ViewGroup arg2) {
holder = null;
if (arg1 == null) {
arg1 = LayoutInflater.from(self).inflate(R.layout.checkitemleibieadapter, arg2, false);
holder = new ViewHolderCheckItemLeiBie();
arg1.setTag(holder);
holder.jiancha_daima = (TextView) arg1.findViewById(R.id.jiancha_daima);
holder.jiancha_leibie = (TextView) arg1.findViewById(R.id.jiancha_leibie);
holder.jiancha_neirong = (TextView) arg1.findViewById(R.id.jiancha_neirong);
holder.jiancha_weifa = (CheckBox) arg1.findViewById(R.id.jiancha_weifa);
} else {
holder = (ViewHolderCheckItemLeiBie) arg1.getTag();
}
holder.jiancha_daima.setText(testList.get(arg0).getBM());
holder.jiancha_leibie.setText(testList.get(arg0).getJCLB());
holder.jiancha_neirong.setText(testList.get(arg0).getJCJG());
holder.jiancha_weifa.setTag(arg0);
//Log.e("长度", checkPositionContext.size()+"");
boolean b = checkPositionContext.contains(testList.get(arg0).getJCJG());
// boolean c = checkPosition.contains(arg0);
// if (!checkPosition.isEmpty()) {
// if (checkPosition.iterator().next().equals("1") && arg0 == 1) {
// System.out.println();
// }
// }
holder.jiancha_weifa.setChecked(b);
holder.jiancha_weifa.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Integer tag = (Integer) buttonView.getTag();
if (isChecked) {
// checkPosition.add(tag);
checkPositionContext.add(testList.get(tag).getJCJG());
//wfxwIdList
String jclbNR = testList.get(tag).getJCLB().substring(2);
if(!jclbList.contains(jclbNR)){
jclbList.add(jclbNR);
}
String wfxwId = testList.get(tag).getWFXW_ID();
if(!wfxwIdList.contains(wfxwId)){
wfxwIdList.add(wfxwId);
}
String wfqxId = testList.get(tag).getWFQX_ID();
if(!wfqxIdList.contains(wfqxId)){
wfqxIdList.add(wfqxId);
}
// result.put(tag, testList.get(tag).getJCJG());
} else {
// result.remove(tag);
// checkPosition.remove(tag);
jclbList.remove(testList.get(tag).getJCLB());
wfxwIdList.remove(testList.get(tag).getWFXW_ID());
wfqxIdList.remove(testList.get(tag).getWFQX_ID());
checkPositionContext.remove(testList.get(tag).getJCJG());
}
}
});
return arg1;
}
private class ViewHolderCheckItemLeiBie {
TextView jiancha_leibie;
TextView jiancha_daima;
TextView jiancha_neirong;
CheckBox jiancha_weifa;
}
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("resultPeopleSize", resultArr.size());
for (int i = 0; i < resultArr.size(); i++) {
intent.putExtra("resultPeople_" + i, resultArr.get(i));
}
intent.putExtra("checkBJCZT", bjczt);
setResult(RESULT_OK, intent);
super.onBackPressed();
}
}
| UTF-8 | Java | 16,451 | java | ChckItemLeiBieJYActivity.java | Java | []
| null | []
| package com.miu360.taxi_check.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lubao.lubao.async.AsyncUtil;
import com.lubao.lubao.async.Callback;
import com.lubao.lubao.async.Result;
import com.miu360.inspect.R;
import com.miu360.taxi_check.BaseActivity;
import com.miu360.taxi_check.common.CommonDialog.OnDialogItemClickListener;
import com.miu30.common.util.MyProgressDialog;
import com.miu360.taxi_check.common.Windows;
import com.miu360.taxi_check.data.WeiFaCheckPreference;
import com.miu360.taxi_check.data.WeiZhanData;
import com.miu360.taxi_check.model.FaGuiDetailAllInfo;
import com.miu360.taxi_check.model.FaGuiQueryInfo;
import com.miu360.taxi_check.model.JCLBQ;
import com.miu360.taxi_check.model.JclbModel;
import com.miu360.taxi_check.util.UIUtils;
import com.miu360.taxi_check.view.HeaderHolder;
import com.miu360.taxi_check.view.ListViewHolder;
public class ChckItemLeiBieJYActivity extends BaseActivity implements OnClickListener {
@ViewInject(R.id.leibie_show)
private LinearLayout leibie_show;
@ViewInject(R.id.check_leibie)
private TextView check_leibie;
@ViewInject(R.id.leibie_daima)
private TextView leibie_daima;// 代码
@ViewInject(R.id.leibie_neirong)
private TextView leibie_neirong;// 检查内容
@ViewInject(R.id.leibie_query)
private TextView leibie_query;
@ViewInject(R.id.leibie_hide)
private TextView leibie_hide;
ListViewHolder holder;
CheckItemLeiBieAdapter adapter;
ArrayList<FaGuiDetailAllInfo> testList = new ArrayList<>();
ArrayList<String> list = new ArrayList<>();
View root;
boolean isOver = true;
String resultString = "";
String bjczt = "";
HeaderHolder header;
String[] itemOne;
ArrayList<JclbModel> arrayListJclb;
FaGuiQueryInfo info = new FaGuiQueryInfo();
//对获取的数据进行排序
Comparator<FaGuiDetailAllInfo> comparator = new Comparator<FaGuiDetailAllInfo>() {
public int compare(FaGuiDetailAllInfo f1, FaGuiDetailAllInfo f2) {
// 先排JCLB
if (!f1.getJCLB().equals(f2.getJCLB())) {
return f1.getJCLB().compareTo(f2.getJCLB());
} else if (!f1.getBM().equals(f2.getBM())) {
return f1.getBM().compareTo(f2.getBM());
} else{
}
return 0;
}
};
//对获取的数据进行排序
Comparator<JclbModel> comparator2 = new Comparator<JclbModel>() {
public int compare(JclbModel f1, JclbModel f2) {
// 先排JCLB
if (!f1.getJCLB().equals(f2.getJCLB())) {
return f1.getJCLB().compareTo(f2.getJCLB());
} else{
}
return 0;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chck_item_lei_bie);
initView();
arrayListJclb = new ArrayList<>();
bjczt = getIntent().getStringExtra("bjczt");
info.setHYLB(getIntent().getStringExtra("HYLB"));
info.setStartIndex(0);
info.setEndIndex(120);
final JCLBQ jclbq = new JCLBQ();
if(bjczt!=null && bjczt!=""){
jclbq.setBjczt(bjczt);
}else{
jclbq.setBjczt("出租汽车驾驶员");
}
AsyncUtil.goAsync(new Callable<Result<List<JclbModel>>>() {
@Override
public Result<List<JclbModel>> call() throws Exception {
return WeiZhanData.getJclb_old(jclbq);
}
}, new Callback<Result<List<JclbModel>>>() {
@Override
public void onHandle(Result<List<JclbModel>> result) {
if (result.ok()) {
if(info.getHYLB()!=null){
if(info.getHYLB().contains("非营运车")){
JclbModel c = new JclbModel();
c.setJCLB("00全部");
arrayListJclb.add(c);
arrayListJclb.add(result.getData().get(0));
Collections.sort(arrayListJclb, comparator2);
}else{
arrayListJclb.addAll(result.getData());
//arrayListJclb.remove(0);
JclbModel c = new JclbModel();
c.setJCLB("00全部");
arrayListJclb.add(c);
Collections.sort(arrayListJclb, comparator2);
}
itemOne = new String[arrayListJclb.size()];
for (int i = 0; i < arrayListJclb.size(); i++) {
itemOne[i] = arrayListJclb.get(i).getJCLB();
}
}
} else {
//UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
holder = ListViewHolder.initList(self);
adapter = new CheckItemLeiBieAdapter();
//root = LayoutInflater.from(self).inflate(R.layout.checkitemleibieadapterheader, null);
holder.list.setMode(Mode.DISABLED);
holder.list.setVisibility(View.GONE);
holder.list.setAdapter(adapter);
//holder.list.getRefreshableView().addHeaderView(root);
holder.list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
FaGuiDetailAllInfo info = (FaGuiDetailAllInfo) arg0.getItemAtPosition(arg2);
// Intent intent = new Intent(self,
// CheckDetailWeiFaActivity.class);
// intent.putExtra("FaGuiDetailAllInfo", info);
// startActivity(intent);
}
});
queryAll();
}
private void initView() {
ViewUtils.inject(self);
WeiFaCheckPreference pref = new WeiFaCheckPreference(self);
int count = pref.getInt("resultPeopleSize", -1);
for (int i = 0; i < count; i++) {
String s = pref.getString("checkPositionContext_" + i, "");
if (!TextUtils.isEmpty(s)) {
checkPositionContext.add(s);
}
}
header = new HeaderHolder();
header.init(self, "检查项");
header.leftBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isOver) {
Intent intent = new Intent();
intent.putExtra("result", resultString);
//intent.putExtra(name, value);
setResult(RESULT_OK, intent);
}
finish();
}
});
header.rightTextBtn.setVisibility(View.VISIBLE);
header.rightTextBtn.setText("确认");
header.rightTextBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isOver = false;
Intent intent = new Intent();
WeiFaCheckPreference prefer = new WeiFaCheckPreference(self);
prefer.clearPreference();
prefer.setInt("resultPeopleSize", checkPositionContext.size());
intent.putExtra("resultPeopleSize", checkPositionContext.size());
Iterator<String> iter = checkPositionContext.iterator();
int count = 0;
while(iter.hasNext()){
String s = iter.next();
prefer.setString("checkPositionContext_"+count, s);
intent.putExtra("resultPeople_"+count, s);
count++;
}
intent.putStringArrayListExtra("jclb", jclbList);
intent.putStringArrayListExtra("wfxwId", wfxwIdList);
intent.putStringArrayListExtra("wfqxId", wfqxIdList);
intent.putExtra("checkBJCZT", bjczt);
setResult(RESULT_OK, intent);
finish();
}
});
leibie_hide.setOnClickListener(this);
check_leibie.setOnClickListener(this);
leibie_query.setOnClickListener(this);
}
String jcnr;
String code;
String jclb;
private void initQuery() {
holder.list.setVisibility(View.GONE);
jcnr = leibie_neirong.getText().toString();
code = leibie_daima.getText().toString().toUpperCase();
jclb = check_leibie.getText().toString();
FaGuiQueryInfo info = new FaGuiQueryInfo();
info.setCODE(code);
info.setJCLB(jclb);
info.setJCNR(jcnr);
info.setBjczt(bjczt);
info.setHYLB(getIntent().getStringExtra("HYLB"));
/*info.setStartIndex(0 + testList.size());
info.setEndIndex(10 + testList.size());*/
if(info.getJCLB()!=null){
if(info.getJCLB().contains("00全部")){
info.setJCLB("");
queryFenLei(info);
}else{
queryFenLei(info);
}
}else{
queryFenLei(info);
}
}
private void queryAll(){
final FaGuiQueryInfo infoall = new FaGuiQueryInfo();
infoall.setHYLB(getIntent().getStringExtra("HYLB"));
infoall.setBjczt(bjczt);
final MyProgressDialog pd = Windows.waiting(self);
AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryCheckItemInfo(infoall);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
pd.dismiss();
if (result.ok()) {
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "查不到数据", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
/*AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryFaGuiAllInfo(info);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
holder.list.onRefreshComplete();
if (result.ok()) {
if (result.getData() == null) {
UIUtils.toast(self, "无信息", Toast.LENGTH_LONG);
return;
}
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "无信息", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
//testList.addAll(result.getData());
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
//UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});*/
}
private void queryFenLei(final FaGuiQueryInfo info){
final MyProgressDialog pd = Windows.waiting(self);
AsyncUtil.goAsync(new Callable<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public Result<List<FaGuiDetailAllInfo>> call() throws Exception {
return WeiZhanData.queryCheckItemInfo(info);
}
}, new Callback<Result<List<FaGuiDetailAllInfo>>>() {
@Override
public void onHandle(Result<List<FaGuiDetailAllInfo>> result) {
pd.dismiss();
if (result.ok()) {
if (result.getData().toString().equals("[]")) {
UIUtils.toast(self, "查不到数据", Toast.LENGTH_LONG);
return;
}
holder.list.setVisibility(View.VISIBLE);
for(int i=0,len = result.getData().size();i<len;i++){
if(!result.getData().get(i).getBH().contains("00")){
testList.add(result.getData().get(i));
}
}
Collections.sort(testList, comparator);
adapter.notifyDataSetChanged();
} else {
UIUtils.toast(self, result.getErrorMsg(), Toast.LENGTH_LONG);
}
}
});
}
@Override
public void onClick(View v) {
if (v == leibie_hide) {
if (leibie_show.getVisibility() == View.GONE) {
leibie_show.setVisibility(View.VISIBLE);
} else {
leibie_show.setVisibility(View.GONE);
}
} else if (v == check_leibie) {
Windows.singleChoice(self, "选择检查类别", itemOne, new OnDialogItemClickListener() {
@Override
public void dialogItemClickListener(int position) {
check_leibie.setText(itemOne[position]);
testList.clear();
initQuery();
}
});
} else if (v == leibie_query) {
if (TextUtils.isEmpty(check_leibie.getText().toString()) &&
TextUtils.isEmpty(leibie_neirong.getText().toString())&&
TextUtils.isEmpty(leibie_daima.getText().toString().toUpperCase())) {
UIUtils.toast(self, "请输入请求参数", Toast.LENGTH_SHORT);
return;
}
testList.clear();
initQuery();
}
}
HashMap<Integer, String> result = new HashMap<>();
// HashSet<Integer> checkPosition = new HashSet<Integer>();
ArrayList<Integer> position = new ArrayList<>();
HashSet<String> resultStr = new HashSet<>();
ArrayList<String> resultArr = new ArrayList<>();
ArrayList<String> jclbList = new ArrayList<>();//存储勾选内容的检查类别
ArrayList<String> wfxwIdList = new ArrayList<>();//违法行为id
ArrayList<String> wfqxIdList = new ArrayList<>();//违法情形id
HashSet<String> checkPositionContext = new HashSet<String>();
private class CheckItemLeiBieAdapter extends BaseAdapter {
ViewHolderCheckItemLeiBie holder;
@Override
public int getCount() {
return testList.size();
}
@Override
public Object getItem(int arg0) {
return testList.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(final int arg0, View arg1, ViewGroup arg2) {
holder = null;
if (arg1 == null) {
arg1 = LayoutInflater.from(self).inflate(R.layout.checkitemleibieadapter, arg2, false);
holder = new ViewHolderCheckItemLeiBie();
arg1.setTag(holder);
holder.jiancha_daima = (TextView) arg1.findViewById(R.id.jiancha_daima);
holder.jiancha_leibie = (TextView) arg1.findViewById(R.id.jiancha_leibie);
holder.jiancha_neirong = (TextView) arg1.findViewById(R.id.jiancha_neirong);
holder.jiancha_weifa = (CheckBox) arg1.findViewById(R.id.jiancha_weifa);
} else {
holder = (ViewHolderCheckItemLeiBie) arg1.getTag();
}
holder.jiancha_daima.setText(testList.get(arg0).getBM());
holder.jiancha_leibie.setText(testList.get(arg0).getJCLB());
holder.jiancha_neirong.setText(testList.get(arg0).getJCJG());
holder.jiancha_weifa.setTag(arg0);
//Log.e("长度", checkPositionContext.size()+"");
boolean b = checkPositionContext.contains(testList.get(arg0).getJCJG());
// boolean c = checkPosition.contains(arg0);
// if (!checkPosition.isEmpty()) {
// if (checkPosition.iterator().next().equals("1") && arg0 == 1) {
// System.out.println();
// }
// }
holder.jiancha_weifa.setChecked(b);
holder.jiancha_weifa.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Integer tag = (Integer) buttonView.getTag();
if (isChecked) {
// checkPosition.add(tag);
checkPositionContext.add(testList.get(tag).getJCJG());
//wfxwIdList
String jclbNR = testList.get(tag).getJCLB().substring(2);
if(!jclbList.contains(jclbNR)){
jclbList.add(jclbNR);
}
String wfxwId = testList.get(tag).getWFXW_ID();
if(!wfxwIdList.contains(wfxwId)){
wfxwIdList.add(wfxwId);
}
String wfqxId = testList.get(tag).getWFQX_ID();
if(!wfqxIdList.contains(wfqxId)){
wfqxIdList.add(wfqxId);
}
// result.put(tag, testList.get(tag).getJCJG());
} else {
// result.remove(tag);
// checkPosition.remove(tag);
jclbList.remove(testList.get(tag).getJCLB());
wfxwIdList.remove(testList.get(tag).getWFXW_ID());
wfqxIdList.remove(testList.get(tag).getWFQX_ID());
checkPositionContext.remove(testList.get(tag).getJCJG());
}
}
});
return arg1;
}
private class ViewHolderCheckItemLeiBie {
TextView jiancha_leibie;
TextView jiancha_daima;
TextView jiancha_neirong;
CheckBox jiancha_weifa;
}
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("resultPeopleSize", resultArr.size());
for (int i = 0; i < resultArr.size(); i++) {
intent.putExtra("resultPeople_" + i, resultArr.get(i));
}
intent.putExtra("checkBJCZT", bjczt);
setResult(RESULT_OK, intent);
super.onBackPressed();
}
}
| 16,451 | 0.690097 | 0.68228 | 541 | 29.031424 | 22.819733 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.245841 | false | false | 2 |
ff663aa1946ccb42ae6da11ad630c55616093986 | 21,577,915,714,137 | 7151f07bfa10cac81baa0209b6528991c07d8de1 | /src/main/java/com/air/pojo/form/CellRelation.java | bd6d767548ca5a703611d1dcd1bcaf70dee6a640 | []
| no_license | ourbest/qfdsuit | https://github.com/ourbest/qfdsuit | bf38a141fab6479d84a3c5ce24124e74f65bd964 | b07c946fe1b04ac3afbcba4acc4bd2979a95dd7c | refs/heads/master | 2021-01-21T23:16:48.490000 | 2011-10-30T09:35:13 | 2011-10-30T09:35:14 | 2,629,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.air.pojo.form;
import javax.persistence.Id;
/**
* create at: 11-9-14
*
* @author Yonghui Chen
*/
public class CellRelation {
@Id
private String reId;
private long formId;
private long rowId;
private long colId;
private long rFormId;
private long rRowId;
private long rColId;
private long formulaId;
public String getReId() {
return reId;
}
public void setReId(String reId) {
this.reId = reId;
}
public long getFormId() {
return formId;
}
public void setFormId(long formId) {
this.formId = formId;
}
public long getRowId() {
return rowId;
}
public void setRowId(long rowId) {
this.rowId = rowId;
}
public long getColId() {
return colId;
}
public void setColId(long colId) {
this.colId = colId;
}
public long getRFormId() {
return rFormId;
}
public void setRFormId(long rFormId) {
this.rFormId = rFormId;
}
public long getRRowId() {
return rRowId;
}
public void setRRowId(long rRowId) {
this.rRowId = rRowId;
}
public long getRColId() {
return rColId;
}
public void setRColId(long rColId) {
this.rColId = rColId;
}
public long getFormulaId() {
return formulaId;
}
public void setFormulaId(long formulaId) {
this.formulaId = formulaId;
}
}
| UTF-8 | Java | 1,464 | java | CellRelation.java | Java | [
{
"context": "tence.Id;\n\n/**\n * create at: 11-9-14\n *\n * @author Yonghui Chen\n */\npublic class CellRelation {\n @Id\n priva",
"end": 110,
"score": 0.9998027682304382,
"start": 98,
"tag": "NAME",
"value": "Yonghui Chen"
}
]
| null | []
| package com.air.pojo.form;
import javax.persistence.Id;
/**
* create at: 11-9-14
*
* @author <NAME>
*/
public class CellRelation {
@Id
private String reId;
private long formId;
private long rowId;
private long colId;
private long rFormId;
private long rRowId;
private long rColId;
private long formulaId;
public String getReId() {
return reId;
}
public void setReId(String reId) {
this.reId = reId;
}
public long getFormId() {
return formId;
}
public void setFormId(long formId) {
this.formId = formId;
}
public long getRowId() {
return rowId;
}
public void setRowId(long rowId) {
this.rowId = rowId;
}
public long getColId() {
return colId;
}
public void setColId(long colId) {
this.colId = colId;
}
public long getRFormId() {
return rFormId;
}
public void setRFormId(long rFormId) {
this.rFormId = rFormId;
}
public long getRRowId() {
return rRowId;
}
public void setRRowId(long rRowId) {
this.rRowId = rRowId;
}
public long getRColId() {
return rColId;
}
public void setRColId(long rColId) {
this.rColId = rColId;
}
public long getFormulaId() {
return formulaId;
}
public void setFormulaId(long formulaId) {
this.formulaId = formulaId;
}
}
| 1,458 | 0.580601 | 0.577186 | 85 | 16.22353 | 13.942214 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305882 | false | false | 2 |
2d55842a5d2bcf00d99f66d80df611aa256b5e11 | 10,316,511,469,510 | 5a71d42e09b6fad191f5846c10178022c20193d9 | /distribution-parent/distribution-data/src/main/java/com/chauncy/data/haiguan/vo/CustomsDataWithMyId.java | 95f76225b898de13ca89ad372e382303c30bf055 | []
| no_license | moutainhigh/congya | https://github.com/moutainhigh/congya | a562812eb4b0262a937b4999ebd5695cb40ecf28 | 987022868eee1d4e93585276c13aac65334747a3 | refs/heads/master | 2022-04-19T03:23:23.916000 | 2020-04-16T14:43:31 | 2020-04-16T14:43:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chauncy.data.haiguan.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @Author zhangrt
* @Date 2019/9/23 13:47
**/
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class CustomsDataWithMyId {
private String customsDataId;
private HgCheckVO hgCheckVO;
}
| UTF-8 | Java | 393 | java | CustomsDataWithMyId.java | Java | [
{
"context": "ort lombok.experimental.Accessors;\n\n/**\n * @Author zhangrt\n * @Date 2019/9/23 13:47\n **/\n@Data\n@Accessors(ch",
"end": 186,
"score": 0.9996448159217834,
"start": 179,
"tag": "USERNAME",
"value": "zhangrt"
}
]
| null | []
| package com.chauncy.data.haiguan.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @Author zhangrt
* @Date 2019/9/23 13:47
**/
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class CustomsDataWithMyId {
private String customsDataId;
private HgCheckVO hgCheckVO;
}
| 393 | 0.773537 | 0.745547 | 21 | 17.714285 | 13.85346 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
2a32a2ee1026cd6e481b58dc61afd40b8262ccb6 | 21,680,994,925,193 | 9099d8901dbfd8bbc8f2f06c86ead72ae51e584e | /src/main/java/net/wesjd/towny/ngin/town/TownManager.java | 40ea1d63e3c022da729d2c2f2582a21e386b4eee | []
| no_license | CyberFlameGO/towny-ngin | https://github.com/CyberFlameGO/towny-ngin | 07da5d3deeb75951454d5c464417a202991b8745 | 12922f12c0814440e8a10b62cd63c3d9f5176d63 | refs/heads/master | 2023-08-17T05:25:58.773000 | 2017-10-28T02:22:15 | 2017-10-28T02:22:15 | 487,011,295 | 0 | 0 | null | true | 2023-08-11T21:14:43 | 2022-04-29T14:55:24 | 2019-02-10T17:33:22 | 2023-08-11T21:14:43 | 177 | 0 | 0 | 1 | null | false | false | package net.wesjd.towny.ngin.town;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import net.wesjd.towny.ngin.storage.StorageFolder;
import java.io.File;
import java.util.*;
/**
* Manages all towns
*/
public class TownManager {
/**
* The injected storage folder
*/
@Inject @Named("towns")
private StorageFolder storage;
/**
* A hashmap of all the current {@link Town}s, used to save on lookup times
*/
private final Map<String, Town> towns = new HashMap<>();
/**
* Saves all the currently stored towns
*/
public void saveTowns() {
towns.values().forEach(Town::save);
}
/**
* Loads all the stored towns from the towns folder
*/
public void loadTowns() {
towns.clear();
Arrays.stream(storage.getAllFiles())
.map(File::getName)
.map(this::createTown)
.forEach(this::addTown);
towns.values().forEach(Town::load);
}
/**
* Creates a town with the specified name
*
* @param name The name of the town
* @return A newly created town
*/
public Town createTown(String name) {
return new Town(name.toLowerCase(), storage);
}
/**
* Adds a {@link Town} to the internal set of towns
*
* @param town The {@link Town} to add
*/
public void addTown(Town town) {
towns.put(town.getName(), town);
}
/**
* Gets a {@link Town} and wraps it with an Optional
*
* @param name The {@link Town} name
* @return An {@link Optional<Town>} empty if no town found
*/
public Optional<Town> getTownSafely(String name) {
return Optional.ofNullable(getTown(name));
}
/**
* Get a town by its name
*
* @param name The name of the town
* @return A {@link Town} or null if there is no town by that name
*/
public Town getTown(String name) {
return towns.get(name);
}
public Collection<Town> getTowns() {
return towns.values();
}
}
| UTF-8 | Java | 2,083 | java | TownManager.java | Java | []
| null | []
| package net.wesjd.towny.ngin.town;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import net.wesjd.towny.ngin.storage.StorageFolder;
import java.io.File;
import java.util.*;
/**
* Manages all towns
*/
public class TownManager {
/**
* The injected storage folder
*/
@Inject @Named("towns")
private StorageFolder storage;
/**
* A hashmap of all the current {@link Town}s, used to save on lookup times
*/
private final Map<String, Town> towns = new HashMap<>();
/**
* Saves all the currently stored towns
*/
public void saveTowns() {
towns.values().forEach(Town::save);
}
/**
* Loads all the stored towns from the towns folder
*/
public void loadTowns() {
towns.clear();
Arrays.stream(storage.getAllFiles())
.map(File::getName)
.map(this::createTown)
.forEach(this::addTown);
towns.values().forEach(Town::load);
}
/**
* Creates a town with the specified name
*
* @param name The name of the town
* @return A newly created town
*/
public Town createTown(String name) {
return new Town(name.toLowerCase(), storage);
}
/**
* Adds a {@link Town} to the internal set of towns
*
* @param town The {@link Town} to add
*/
public void addTown(Town town) {
towns.put(town.getName(), town);
}
/**
* Gets a {@link Town} and wraps it with an Optional
*
* @param name The {@link Town} name
* @return An {@link Optional<Town>} empty if no town found
*/
public Optional<Town> getTownSafely(String name) {
return Optional.ofNullable(getTown(name));
}
/**
* Get a town by its name
*
* @param name The name of the town
* @return A {@link Town} or null if there is no town by that name
*/
public Town getTown(String name) {
return towns.get(name);
}
public Collection<Town> getTowns() {
return towns.values();
}
}
| 2,083 | 0.584734 | 0.584734 | 87 | 22.94253 | 20.398533 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 2 |
0a2c5cfbace432669ab35e4d3577d9d6525a8e79 | 18,459,769,457,325 | a0cda57eb8bf95a1fe5bc7b53b31676849b87ef2 | /sdk/src/main/java/sdk/af/com/sdk/core/biztask/SendSession.java | c92edd3e668c91fa98f72f943bfb6ceb56171d4a | []
| no_license | wzqhbkjdx/SDKDemo | https://github.com/wzqhbkjdx/SDKDemo | 476cb7a93c5e6519f9258dcfe48fa4031b4fbeec | 56b1d5236d79c0877e288dd1f56bea492c2b1fa9 | refs/heads/master | 2020-04-11T08:04:57.089000 | 2018-12-18T09:45:56 | 2018-12-18T09:45:56 | 161,631,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sdk.af.com.sdk.core.biztask;
import sdk.af.com.sdk.service.task.BaseTask;
import sdk.af.com.sdk.util.Logger;
public class SendSession extends BaseTask {
private String sessionName;
public String getSessionName() {
return sessionName;
}
public void setSessionName(String sessionName) {
this.sessionName = sessionName;
}
@Override
protected void task() {
Logger.instance().d("SendSession",
sessionName + " : " +Thread.currentThread().getName());
}
}
| UTF-8 | Java | 535 | java | SendSession.java | Java | []
| null | []
| package sdk.af.com.sdk.core.biztask;
import sdk.af.com.sdk.service.task.BaseTask;
import sdk.af.com.sdk.util.Logger;
public class SendSession extends BaseTask {
private String sessionName;
public String getSessionName() {
return sessionName;
}
public void setSessionName(String sessionName) {
this.sessionName = sessionName;
}
@Override
protected void task() {
Logger.instance().d("SendSession",
sessionName + " : " +Thread.currentThread().getName());
}
}
| 535 | 0.656075 | 0.656075 | 24 | 21.291666 | 20.763508 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
b494e343bd71a0ad5dc703b1e1b51dcf7c4e98da | 4,483,945,879,371 | b2ff9d714bfc8a5db1dc6c93bd17e1b4f4ff3521 | /src/access/usuarioDAO.java | ad8c359366c1cee2f53b16e16481fd70f6997934 | []
| no_license | Juan961/reto5 | https://github.com/Juan961/reto5 | 23d158ab538a32ee7f14f3b18e1aad83054ebe07 | bbdcafedb62a600de76fefceb5fd6fdedf8efadd | refs/heads/main | 2023-07-18T12:02:23.621000 | 2021-09-06T02:24:45 | 2021-09-06T02:24:45 | 403,345,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package access;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.usuarioModel;
import utils.conexion;
public class usuarioDAO {
private Connection conn = null;
// Consultar la informacion del usuario para tenerla a la mano despues del login
public ArrayList<String> getUser(usuarioModel user){
ArrayList<String> data = new ArrayList<>();
try {
if(conn == null)
conn = conexion.getConection();
String sql = "SELECT * FROM USUARIO where emailUsuario=? AND contraseñaUsuario=? ;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getEmailUsuario());
statement.setString(2, user.getContraseñaUsuario());
ResultSet result = statement.executeQuery();
while(result.next()){
for(int i=1;i<7;i++){
data.add(result.getString(i));
}
}
}
catch (SQLException ex) {
System.out.println("Algo salio mal por aca" + ex);
}
return data;
}
// Validar el login
public boolean consultUser(usuarioModel user){
try {
if(conn == null)
conn = conexion.getConection();
String sql = "SELECT * FROM USUARIO where emailUsuario=? AND contraseñaUsuario=? ;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getEmailUsuario());
statement.setString(2, user.getContraseñaUsuario());
ResultSet result = statement.executeQuery();
return result.next();
} catch(SQLException ex){
System.out.println("Algo salio mal en la consulta" + ex);
}
return false;
}
// Crear un usuario en el register
public void insertUser(usuarioModel user){
try {
if(conn == null)
conn = conexion.getConection();
// Sentencia de insercion de SQL
String sql = "INSERT INTO USUARIO(nombreUsuario, emailUsuario, contraseñaUsuario, directorUsuario) VALUES (?, ?, ?, ?);";
// Formateamos la sentencia de SQL
PreparedStatement statement = conn.prepareStatement(sql);
// Asignamos valores que queremos formatear segun los tipos de datos
statement.setString(1, user.getNombreUsuario());
statement.setString(2, user.getEmailUsuario());
statement.setString(3, user.getContraseñaUsuario());
System.out.println(user.isDirectorUsuario());
statement.setBoolean(4, user.isDirectorUsuario());
int rowsInserted = statement.executeUpdate();
} catch (SQLException ex) {
System.out.println("Algo salio mal en la insercion" + ex);
}
}
// Solicitar el id del usuario creador de un contenido para renderizar el contenido del feedback
public int getIdUser(String titulo, String descripcion, String categoria, String produccion){
int id = 0;
try{
if(conn == null)
conn = conexion.getConection();
String sql = "Select idUsuario from usuario, contenido where contenido.usuario_idUsuario = usuario.idUsuario AND contenido.tituloContenido= ? AND contenido.descripcionContenido= ? AND contenido.categoriaContenido = ? AND contenido.produccionContenido = ? ; ";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, titulo);
statement.setString(2, descripcion);
statement.setString(3, categoria);
statement.setString(4, produccion);
ResultSet result = statement.executeQuery();
while(result.next()){
id = result.getInt(1);
}
} catch(SQLException ex){
System.out.println("Algo salio mal " + ex);
}
return id;
}
public boolean deleteUser(int idUsuario){
boolean pass = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "DELETE FROM usuario where idUsuario=?;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, idUsuario);
int rowsUpdate = statement.executeUpdate();
System.out.println("Actualizaciones " + rowsUpdate);
pass = rowsUpdate != 0;
} catch (SQLException ex) {
System.out.println("Algo salio mal en la eliminacion del usuario: " + ex);
}
return pass;
}
public boolean updateUser(int idUsuario, String newName, String newPassword, boolean newIsDirector, boolean newShareEmail){
boolean pass = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "UPDATE usuario SET nombreUsuario=?, contraseñaUsuario=?, directorUsuario=?, shareEmailUsuario=? where idUsuario=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, newName);
statement.setString(2, newPassword);
statement.setBoolean(3, newIsDirector);
statement.setBoolean(4, newShareEmail);
statement.setInt(5, idUsuario);
int rowsUpdate = statement.executeUpdate();
pass = rowsUpdate != 0;
} catch (SQLException ex) {
System.out.println("Algo salio mal en la actualizacion del usuario: " + ex);
}
return pass;
}
public boolean shareEmail(int id){
boolean value = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "select shareEmailUsuario from usuario where idUsuario=?;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet result = statement.executeQuery();
while(result.next()){
System.out.println(result.getBoolean(1));
value = result.getBoolean(1);
}
return value;
} catch(SQLException ex){
System.out.println("Algo salio mal en la verificacion de compartir el email " + ex);
}
return value;
}
}
| UTF-8 | Java | 7,071 | java | usuarioDAO.java | Java | [
{
"context": "SQL\n String sql = \"INSERT INTO USUARIO(nombreUsuario, emailUsuario, contraseñaUsuario, directorUsuario",
"end": 2549,
"score": 0.5337101817131042,
"start": 2536,
"tag": "USERNAME",
"value": "nombreUsuario"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package access;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import model.usuarioModel;
import utils.conexion;
public class usuarioDAO {
private Connection conn = null;
// Consultar la informacion del usuario para tenerla a la mano despues del login
public ArrayList<String> getUser(usuarioModel user){
ArrayList<String> data = new ArrayList<>();
try {
if(conn == null)
conn = conexion.getConection();
String sql = "SELECT * FROM USUARIO where emailUsuario=? AND contraseñaUsuario=? ;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getEmailUsuario());
statement.setString(2, user.getContraseñaUsuario());
ResultSet result = statement.executeQuery();
while(result.next()){
for(int i=1;i<7;i++){
data.add(result.getString(i));
}
}
}
catch (SQLException ex) {
System.out.println("Algo salio mal por aca" + ex);
}
return data;
}
// Validar el login
public boolean consultUser(usuarioModel user){
try {
if(conn == null)
conn = conexion.getConection();
String sql = "SELECT * FROM USUARIO where emailUsuario=? AND contraseñaUsuario=? ;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getEmailUsuario());
statement.setString(2, user.getContraseñaUsuario());
ResultSet result = statement.executeQuery();
return result.next();
} catch(SQLException ex){
System.out.println("Algo salio mal en la consulta" + ex);
}
return false;
}
// Crear un usuario en el register
public void insertUser(usuarioModel user){
try {
if(conn == null)
conn = conexion.getConection();
// Sentencia de insercion de SQL
String sql = "INSERT INTO USUARIO(nombreUsuario, emailUsuario, contraseñaUsuario, directorUsuario) VALUES (?, ?, ?, ?);";
// Formateamos la sentencia de SQL
PreparedStatement statement = conn.prepareStatement(sql);
// Asignamos valores que queremos formatear segun los tipos de datos
statement.setString(1, user.getNombreUsuario());
statement.setString(2, user.getEmailUsuario());
statement.setString(3, user.getContraseñaUsuario());
System.out.println(user.isDirectorUsuario());
statement.setBoolean(4, user.isDirectorUsuario());
int rowsInserted = statement.executeUpdate();
} catch (SQLException ex) {
System.out.println("Algo salio mal en la insercion" + ex);
}
}
// Solicitar el id del usuario creador de un contenido para renderizar el contenido del feedback
public int getIdUser(String titulo, String descripcion, String categoria, String produccion){
int id = 0;
try{
if(conn == null)
conn = conexion.getConection();
String sql = "Select idUsuario from usuario, contenido where contenido.usuario_idUsuario = usuario.idUsuario AND contenido.tituloContenido= ? AND contenido.descripcionContenido= ? AND contenido.categoriaContenido = ? AND contenido.produccionContenido = ? ; ";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, titulo);
statement.setString(2, descripcion);
statement.setString(3, categoria);
statement.setString(4, produccion);
ResultSet result = statement.executeQuery();
while(result.next()){
id = result.getInt(1);
}
} catch(SQLException ex){
System.out.println("Algo salio mal " + ex);
}
return id;
}
public boolean deleteUser(int idUsuario){
boolean pass = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "DELETE FROM usuario where idUsuario=?;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, idUsuario);
int rowsUpdate = statement.executeUpdate();
System.out.println("Actualizaciones " + rowsUpdate);
pass = rowsUpdate != 0;
} catch (SQLException ex) {
System.out.println("Algo salio mal en la eliminacion del usuario: " + ex);
}
return pass;
}
public boolean updateUser(int idUsuario, String newName, String newPassword, boolean newIsDirector, boolean newShareEmail){
boolean pass = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "UPDATE usuario SET nombreUsuario=?, contraseñaUsuario=?, directorUsuario=?, shareEmailUsuario=? where idUsuario=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, newName);
statement.setString(2, newPassword);
statement.setBoolean(3, newIsDirector);
statement.setBoolean(4, newShareEmail);
statement.setInt(5, idUsuario);
int rowsUpdate = statement.executeUpdate();
pass = rowsUpdate != 0;
} catch (SQLException ex) {
System.out.println("Algo salio mal en la actualizacion del usuario: " + ex);
}
return pass;
}
public boolean shareEmail(int id){
boolean value = false;
try {
if(conn == null)
conn = conexion.getConection();
String sql = "select shareEmailUsuario from usuario where idUsuario=?;";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet result = statement.executeQuery();
while(result.next()){
System.out.println(result.getBoolean(1));
value = result.getBoolean(1);
}
return value;
} catch(SQLException ex){
System.out.println("Algo salio mal en la verificacion de compartir el email " + ex);
}
return value;
}
}
| 7,071 | 0.570781 | 0.566959 | 194 | 35.412373 | 32.396782 | 272 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.680412 | false | false | 2 |
0ee6e4d6a166ef34fb2f2ca2da7a822b9354a558 | 28,037,546,532,445 | 12f0acc8bad6bf2b2e47f23d0f2fa7fcf123e517 | /core/src/main/java/pl/alpheratzteam/obfuscator/transformer/InlineRemoverTransformer.java | 2068148b0565efa08da02438c744955da2f65bee | [
"MIT"
]
| permissive | Trixtaro/obfuscator | https://github.com/Trixtaro/obfuscator | 900dfa0c078712142763b6f4395358da86864534 | 616708db85694901717d0f07e231f73cbc4d86a9 | refs/heads/master | 2022-11-11T16:02:13.131000 | 2020-07-11T23:00:55 | 2020-07-11T23:00:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.alpheratzteam.obfuscator.transformer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.*;
import pl.alpheratzteam.obfuscator.Obfuscator;
import pl.alpheratzteam.obfuscator.util.AccessUtil;
import pl.alpheratzteam.obfuscator.util.StringUtil;
import java.util.*;
/**
* @author Unix
* @since 14.04.20
*/
public class InlineRemoverTransformer extends Transformer
{
private final Map<String, Set<MethodNode>> methodSet = new HashMap<>();
public InlineRemoverTransformer(Obfuscator obfuscator) {
super(obfuscator);
}
@Override
public void visit(Map<String, ClassNode> classMap) {
classMap.values().forEach(classNode -> {
final Set<MethodNode> methods = new HashSet<>();
classNode.methods.forEach(methodNode -> Arrays.stream(methodNode.instructions.toArray()).forEach(ain -> {
final MethodNode x = createMethod(ain);
if (Objects.isNull(x))
return;
methods.add(x);
methodNode.instructions.insertBefore(ain.getNext(), new MethodInsnNode((AccessUtil.isStatic(x.access) ? INVOKESTATIC : INVOKEVIRTUAL), classNode.name, x.name, x.desc, false));
methodNode.instructions.remove(ain);
}));
methodSet.put(classNode.name, methods);
});
classMap.values().forEach(classNode -> {
if (!methodSet.containsKey(classNode.name))
return;
classNode.methods.addAll(methodSet.get(classNode.name));
});
}
@Nullable
private MethodNode createMethod(@NotNull AbstractInsnNode ain) {
final String methodName = StringUtil.generateString(16);
MethodNode methodNode = null;
switch (ain.getOpcode()) {
case SIPUSH:
methodNode = new MethodNode(ACC_PUBLIC | ACC_STATIC, methodName, "()I", null, null);
methodNode.visitCode();
final Label label0 = new Label();
methodNode.visitLabel(label0);
methodNode.visitLineNumber(9, label0);
methodNode.visitIntInsn(SIPUSH, ((IntInsnNode) ain).operand);
methodNode.visitInsn(IRETURN);
methodNode.visitMaxs(1, 0);
methodNode.visitEnd();
break;
case LDC:
methodNode = new MethodNode(ACC_PUBLIC | ACC_STATIC, methodName, "()Ljava/lang/String;", null, null);
methodNode.visitCode();
final Label label1 = new Label();
methodNode.visitLabel(label1);
methodNode.visitLineNumber(16, label1);
methodNode.visitLdcInsn(((LdcInsnNode) ain).cst.toString());
methodNode.visitInsn(ARETURN);
methodNode.visitMaxs(1, 0);
methodNode.visitEnd();
break;
}
return methodNode;
}
} | UTF-8 | Java | 3,032 | java | InlineRemoverTransformer.java | Java | [
{
"context": "il.StringUtil;\nimport java.util.*;\n\n/**\n * @author Unix\n * @since 14.04.20\n */\n\npublic class InlineRemove",
"end": 391,
"score": 0.9645319581031799,
"start": 387,
"tag": "USERNAME",
"value": "Unix"
}
]
| null | []
| package pl.alpheratzteam.obfuscator.transformer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.*;
import pl.alpheratzteam.obfuscator.Obfuscator;
import pl.alpheratzteam.obfuscator.util.AccessUtil;
import pl.alpheratzteam.obfuscator.util.StringUtil;
import java.util.*;
/**
* @author Unix
* @since 14.04.20
*/
public class InlineRemoverTransformer extends Transformer
{
private final Map<String, Set<MethodNode>> methodSet = new HashMap<>();
public InlineRemoverTransformer(Obfuscator obfuscator) {
super(obfuscator);
}
@Override
public void visit(Map<String, ClassNode> classMap) {
classMap.values().forEach(classNode -> {
final Set<MethodNode> methods = new HashSet<>();
classNode.methods.forEach(methodNode -> Arrays.stream(methodNode.instructions.toArray()).forEach(ain -> {
final MethodNode x = createMethod(ain);
if (Objects.isNull(x))
return;
methods.add(x);
methodNode.instructions.insertBefore(ain.getNext(), new MethodInsnNode((AccessUtil.isStatic(x.access) ? INVOKESTATIC : INVOKEVIRTUAL), classNode.name, x.name, x.desc, false));
methodNode.instructions.remove(ain);
}));
methodSet.put(classNode.name, methods);
});
classMap.values().forEach(classNode -> {
if (!methodSet.containsKey(classNode.name))
return;
classNode.methods.addAll(methodSet.get(classNode.name));
});
}
@Nullable
private MethodNode createMethod(@NotNull AbstractInsnNode ain) {
final String methodName = StringUtil.generateString(16);
MethodNode methodNode = null;
switch (ain.getOpcode()) {
case SIPUSH:
methodNode = new MethodNode(ACC_PUBLIC | ACC_STATIC, methodName, "()I", null, null);
methodNode.visitCode();
final Label label0 = new Label();
methodNode.visitLabel(label0);
methodNode.visitLineNumber(9, label0);
methodNode.visitIntInsn(SIPUSH, ((IntInsnNode) ain).operand);
methodNode.visitInsn(IRETURN);
methodNode.visitMaxs(1, 0);
methodNode.visitEnd();
break;
case LDC:
methodNode = new MethodNode(ACC_PUBLIC | ACC_STATIC, methodName, "()Ljava/lang/String;", null, null);
methodNode.visitCode();
final Label label1 = new Label();
methodNode.visitLabel(label1);
methodNode.visitLineNumber(16, label1);
methodNode.visitLdcInsn(((LdcInsnNode) ain).cst.toString());
methodNode.visitInsn(ARETURN);
methodNode.visitMaxs(1, 0);
methodNode.visitEnd();
break;
}
return methodNode;
}
} | 3,032 | 0.608179 | 0.601253 | 86 | 34.267441 | 32.066219 | 191 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.813953 | false | false | 2 |
a2249e45ac2dfaf148383912b9116271c846842b | 12,446,815,250,312 | b26138767229d53a64bf8bfc26fd392fbfe370b2 | /bookrent/src/main/java/com/devrauxx/bookrent/util/GlobalResponseUtil.java | 7acc19293187658a2cfeeed74cba6354f0e030cb | []
| no_license | ishailendra/recordMS | https://github.com/ishailendra/recordMS | e503f2c0ceec9285a07e29a9dee5d1b902f02788 | 37326be49f2043609e9141c6819c975a353f0b21 | refs/heads/master | 2020-07-06T01:49:10.747000 | 2019-10-13T03:52:51 | 2019-10-13T03:52:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.devrauxx.bookrent.util;
import java.time.LocalDateTime;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class GlobalResponseUtil {
public static <T> ResponseEntity<?> generateResponse(LocalDateTime time,HttpStatus status,String message,T data){
CustomResponse<T> response = new CustomResponse<>();
response.setTime(time);
response.setHttpStatus(status);
response.setMessage(message);
response.setData(data);
return new ResponseEntity<CustomResponse<T>>(response,status);
}
}
| UTF-8 | Java | 563 | java | GlobalResponseUtil.java | Java | []
| null | []
| package com.devrauxx.bookrent.util;
import java.time.LocalDateTime;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class GlobalResponseUtil {
public static <T> ResponseEntity<?> generateResponse(LocalDateTime time,HttpStatus status,String message,T data){
CustomResponse<T> response = new CustomResponse<>();
response.setTime(time);
response.setHttpStatus(status);
response.setMessage(message);
response.setData(data);
return new ResponseEntity<CustomResponse<T>>(response,status);
}
}
| 563 | 0.78508 | 0.78508 | 20 | 27.15 | 28.318325 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.65 | false | false | 2 |
d6d2f4623dd173dcf02e9b598b103bf454d075c5 | 12,446,815,251,260 | a9fe53413e2bde106f212e6d72c1a27230547e9a | /src/app/linkedbox/Node.java | 34e4c1bcc7637af36fb9430891121e1357e2ac72 | []
| no_license | KevinFSW/myJavaCode | https://github.com/KevinFSW/myJavaCode | bd6401661d74b128cded0c6874d1111cefcbeda8 | da51bf7ae0074f6f1ecae77b4dc47a31441922ea | refs/heads/master | 2021-01-04T18:24:34.475000 | 2020-04-05T16:11:44 | 2020-04-05T16:11:44 | 240,707,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.linkedbox;
/*
public class Node<E>{
private Node<E> prev;
private Node<E> next;
private E item;
public Node(){
this.prev = null;
this.next = null;
this.item = null;
}
public Node(Node<E> prev, Node<E> next, E item){
this.prev = prev;
this.next = next;
this.item = item;
}
public Node<E> getPrev(){
return this.prev;
}
public Node<E> getNext(){
return this.next;
}
public E getItem(){
return this.item;
}
public void setPrev(Node<E> prev){
this.prev = prev;
}
public void setNext(Node<E> next){
this.next = next;
}
public void setItem(E item){
this.item = item;
}
}
*/ | UTF-8 | Java | 760 | java | Node.java | Java | []
| null | []
| package app.linkedbox;
/*
public class Node<E>{
private Node<E> prev;
private Node<E> next;
private E item;
public Node(){
this.prev = null;
this.next = null;
this.item = null;
}
public Node(Node<E> prev, Node<E> next, E item){
this.prev = prev;
this.next = next;
this.item = item;
}
public Node<E> getPrev(){
return this.prev;
}
public Node<E> getNext(){
return this.next;
}
public E getItem(){
return this.item;
}
public void setPrev(Node<E> prev){
this.prev = prev;
}
public void setNext(Node<E> next){
this.next = next;
}
public void setItem(E item){
this.item = item;
}
}
*/ | 760 | 0.521053 | 0.521053 | 45 | 15.911111 | 13.33637 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 2 |
d5c6cf9cbc08f733ce16b32da47d903bca140e63 | 1,511,828,489,058 | 80747e8899682f7fb6df213e358f1caa2d205c0e | /archive/spring-in28min&rest&mvc/SpringBasics/DIExample/src/main/java/Mockito_example/Data.java | 539e5e44ef4052ee06e3208c8be121ec43ecdbe0 | []
| no_license | ArjitS1/MiniProjects | https://github.com/ArjitS1/MiniProjects | 471a21e2c95364530faa9205f542540987b5f094 | 6f734b8d3b1ae9353f1124a2b8096277e14c0a27 | refs/heads/main | 2023-05-13T21:43:55.514000 | 2023-01-05T11:01:07 | 2023-01-05T11:01:07 | 328,728,537 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Mockito_example;
public class Data {
public DataService dataService;
public Data(DataService dataService){
this.dataService=dataService;
}
public int findGreatest() {
int[] data = dataService.retrieveAllData();
int greatest = Integer.MIN_VALUE;
for(int i: data)
greatest = Math.max(greatest, i);
return greatest;
}
}
| UTF-8 | Java | 355 | java | Data.java | Java | []
| null | []
| package Mockito_example;
public class Data {
public DataService dataService;
public Data(DataService dataService){
this.dataService=dataService;
}
public int findGreatest() {
int[] data = dataService.retrieveAllData();
int greatest = Integer.MIN_VALUE;
for(int i: data)
greatest = Math.max(greatest, i);
return greatest;
}
}
| 355 | 0.707042 | 0.707042 | 19 | 17.68421 | 15.317869 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.684211 | false | false | 2 |
9a93f75e48c34260710133f6927f6d6b4b860072 | 1,503,238,622,999 | 96a22956380a8b388d98dbacb6f2e4d313018f1a | /src/main/java/wwlib/xlssmartreader/ValueItem.java | 2e185820d57e8d4651f11258ff835e8511a657c2 | []
| no_license | wwalery/xlssmartreader | https://github.com/wwalery/xlssmartreader | cdca569ed6dece80c9c4b35546a1ecb82403f008 | 5da9d884b5b681fd7c92c79eb0b4ae27e7a2cebe | refs/heads/master | 2020-03-26T19:44:59.987000 | 2018-10-15T21:08:20 | 2018-10-15T21:08:20 | 145,284,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wwlib.xlssmartreader;
import java.util.Objects;
import org.apache.poi.ss.usermodel.Cell;
/**
*
* @author Walery Wysotsky <dev@wysotsky.info>
*/
public class ValueItem {
private String stringValue;
private Cell cell;
public ValueItem(String stringValue, Cell cell) {
this.stringValue = stringValue;
this.cell = cell;
}
public String getStringValue() {
return stringValue;
}
public Cell getCell() {
return cell;
}
@Override
public String toString() {
return "ValueItem{" + "stringValue=" + stringValue + ", cell=" + cell + '}';
}
}
| UTF-8 | Java | 592 | java | ValueItem.java | Java | [
{
"context": "g.apache.poi.ss.usermodel.Cell;\n\n/**\n *\n * @author Walery Wysotsky <dev@wysotsky.info>\n */\npublic class ValueItem {\n",
"end": 132,
"score": 0.9998986124992371,
"start": 117,
"tag": "NAME",
"value": "Walery Wysotsky"
},
{
"context": "ermodel.Cell;\n\n/**\n *\n * @author Walery Wysotsky <dev@wysotsky.info>\n */\npublic class ValueItem {\n\n private String s",
"end": 151,
"score": 0.9999312162399292,
"start": 134,
"tag": "EMAIL",
"value": "dev@wysotsky.info"
}
]
| null | []
| package wwlib.xlssmartreader;
import java.util.Objects;
import org.apache.poi.ss.usermodel.Cell;
/**
*
* @author <NAME> <<EMAIL>>
*/
public class ValueItem {
private String stringValue;
private Cell cell;
public ValueItem(String stringValue, Cell cell) {
this.stringValue = stringValue;
this.cell = cell;
}
public String getStringValue() {
return stringValue;
}
public Cell getCell() {
return cell;
}
@Override
public String toString() {
return "ValueItem{" + "stringValue=" + stringValue + ", cell=" + cell + '}';
}
}
| 573 | 0.66723 | 0.66723 | 34 | 16.411764 | 18.816635 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 2 |
54e3b1ee559b4354d82cd920e82986d82a7e0867 | 28,913,719,890,628 | 93a9c92248919a58616c60738ede6fd66277f77b | /webshop/service/src/main/java/miki/uni/sarajevo/webshop/dao/CustomerDAO.java | 475fb300358e88798ecb79ffa7318aaa1b7a31c6 | []
| no_license | miki995/WebShop_SwengErasmus17 | https://github.com/miki995/WebShop_SwengErasmus17 | 6ba68f8737725be67951ff832a41c76497e3fd41 | 72ba43a1ae82418d83711ced6c613b8635a98bfd | refs/heads/master | 2022-12-09T20:24:22.081000 | 2017-10-10T16:29:14 | 2017-10-10T16:29:14 | 106,168,557 | 0 | 0 | null | false | 2020-09-02T15:24:04 | 2017-10-08T10:43:31 | 2017-10-10T16:18:22 | 2020-09-02T15:24:03 | 243 | 0 | 0 | 1 | Java | false | false | package miki.uni.sarajevo.webshop.dao;
import miki.uni.sarajevo.webshop.dao.exceptions.customerExceptions.*;
import miki.uni.sarajevo.webshop.model.Customer;
import miki.uni.sarajevo.webshop.model.helpClasses.City;
import miki.uni.sarajevo.webshop.model.helpClasses.Country;
import miki.uni.sarajevo.webshop.model.helpClasses.Gender;
import java.util.Collection;
import java.util.Date;
/**
* Created by miki995 on 2017.10.08..
*/
public interface CustomerDAO {
void createCustomer(Customer customer) throws CustomerAlreadyExistsException;
void updateCustomer(Customer customer) throws CustomerNotFoundException;
void deleteCustomer(Customer customer) throws CustomerNotFoundException;
Collection<Customer> readCustomers();
Collection<Customer> readCustomersByCity(City city);
Collection<Customer> readCustomersByCountry(Country country);
Collection<Customer> readCustomersByGender(Gender gender);
Customer readCustomerByBirthDate(Date date) throws BirthDateNotFoundException;
Customer readCustomerByEmail(String email) throws EmailNotFoundException;
Customer readCustomerByPhone(String phone) throws PhoneNotFoundException;
}
| UTF-8 | Java | 1,181 | java | CustomerDAO.java | Java | [
{
"context": "lection;\nimport java.util.Date;\n\n/**\n * Created by miki995 on 2017.10.08..\n */\npublic interface CustomerDAO ",
"end": 414,
"score": 0.9995743036270142,
"start": 407,
"tag": "USERNAME",
"value": "miki995"
}
]
| null | []
| package miki.uni.sarajevo.webshop.dao;
import miki.uni.sarajevo.webshop.dao.exceptions.customerExceptions.*;
import miki.uni.sarajevo.webshop.model.Customer;
import miki.uni.sarajevo.webshop.model.helpClasses.City;
import miki.uni.sarajevo.webshop.model.helpClasses.Country;
import miki.uni.sarajevo.webshop.model.helpClasses.Gender;
import java.util.Collection;
import java.util.Date;
/**
* Created by miki995 on 2017.10.08..
*/
public interface CustomerDAO {
void createCustomer(Customer customer) throws CustomerAlreadyExistsException;
void updateCustomer(Customer customer) throws CustomerNotFoundException;
void deleteCustomer(Customer customer) throws CustomerNotFoundException;
Collection<Customer> readCustomers();
Collection<Customer> readCustomersByCity(City city);
Collection<Customer> readCustomersByCountry(Country country);
Collection<Customer> readCustomersByGender(Gender gender);
Customer readCustomerByBirthDate(Date date) throws BirthDateNotFoundException;
Customer readCustomerByEmail(String email) throws EmailNotFoundException;
Customer readCustomerByPhone(String phone) throws PhoneNotFoundException;
}
| 1,181 | 0.812024 | 0.80271 | 36 | 31.805555 | 31.27372 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
1d5f429629654c2c1fcba87fae372d7583b856be | 3,908,420,287,358 | 2a7262a714ae1215372c8b9e2b1adfc423678f95 | /src/Day12/LinkedListEx.java | b559c1de93da690733c53f72ec09a21db0d41fa9 | []
| no_license | prabaprabakaran/Java-Programs | https://github.com/prabaprabakaran/Java-Programs | be9734f3aa0d87303adb68772297b6cd2764e170 | ba14d6e0ab38904b81c8093a0e48a5fce3cf573b | refs/heads/master | 2020-12-30T14:45:09.935000 | 2017-06-06T05:43:05 | 2017-06-06T05:43:05 | 91,085,620 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Day12;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListEx {
public static void main(String[] args) {
LinkedList<String>li=new LinkedList<>();
li.add("one");
li.add("two");
li.add("three");
li.peekFirst();
li.peekLast();
Iterator<String>it=li.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
| UTF-8 | Java | 366 | java | LinkedListEx.java | Java | []
| null | []
| package Day12;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListEx {
public static void main(String[] args) {
LinkedList<String>li=new LinkedList<>();
li.add("one");
li.add("two");
li.add("three");
li.peekFirst();
li.peekLast();
Iterator<String>it=li.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
| 366 | 0.685792 | 0.680328 | 20 | 17.299999 | 13.281942 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15 | false | false | 2 |
0f3b68c0546e39312fbdf007fc9583c0703f2f86 | 14,620,068,732,414 | 37929cc055b34db555c7a92630a471782145e262 | /shopJob/src/main/java/org/dueam/hadoop/jobs/ShopCenter.java | a6bd8c3d4233ab17d6ac9ef30bbc87ecf3d319da | []
| no_license | RyanFu/shopJob | https://github.com/RyanFu/shopJob | 955be0bedc9d0aeafd930e402967346e810210bf | d59bdfc70aac8eb8b352fc85161df94c3a5152da | refs/heads/master | 2021-01-16T22:52:42.116000 | 2013-03-19T00:47:28 | 2013-03-19T00:47:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dueam.hadoop.jobs;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.lib.LongSumReducer;
import org.apache.hadoop.util.ToolRunner;
import org.dueam.hadoop.common.HadoopTable;
import org.dueam.hadoop.common.SimpleMapReduce;
import org.dueam.hadoop.common.tables.AuctionAuctions;
import org.dueam.hadoop.common.tables.BmwShops;
import org.dueam.hadoop.common.util.DateStringUtils;
import org.dueam.hadoop.common.util.Utils;
import javax.rmi.CORBA.Util;
import java.io.IOException;
/**
* 追踪店铺增长情况
*/
public class ShopCenter extends SimpleMapReduce {
@Override
protected String[] getInputPath(String[] args) {
String[] input = HadoopTable.shop(args[0]).getInputPath();
System.out.println("input path => " + Utils.asString(input));
return input;
}
@Override
protected Class getInputFormat() {
return HadoopTable.shop(null).getInputFormat();
}
@Override
protected String getOutputPath(String[] args) {
return "/group/tbdev/xiaodu/suoni/shop_center/" + args[0];
}
@Override
protected void beforeRun(String[] args, JobConf config) {
config.setCombinerClass(LongSumReducer.class);
}
@Override
protected void doWork(String line, OutputCollector<Text, LongWritable> output) throws IOException {
String[] _allCols = StringUtils.splitPreserveAllTokens(line, TAB);
if (_allCols.length < 22) {
return;
}
String queryDate = DateStringUtils.format(inputArgs[0]);
output.collect(Utils.mergeKey("total", "all"), ONE); //所有店铺数
if (Utils.isSameDay(queryDate, _allCols[BmwShops.starts])) {
output.collect(Utils.mergeKey("total", "today"), ONE); //今天开的店铺
}
//店铺状态
output.collect(Utils.mergeKey("approve_status", _allCols[BmwShops.approve_status]), ONE);
//统计正常的店铺
if ("0".equals(_allCols[BmwShops.approve_status])) {
long promotedStatus = NumberUtils.toLong(_allCols[BmwShops.promoted_status]);
for (long status : Utils.toBitArray(promotedStatus)) {
output.collect(Utils.mergeKey("promoted_status", String.valueOf(status)), ONE);
}
long produceCount = NumberUtils.toLong(_allCols[BmwShops.products_count]);
if (produceCount >=0) {
output.collect(Utils.mergeKey("product_count", BmwShops.getArea(produceCount)), ONE);
}
//店铺类型
output.collect(Utils.mergeKey("site", _allCols[BmwShops.siteid]), ONE);
if (Utils.isSameDay(queryDate, _allCols[BmwShops.starts])) {
//店铺类型
output.collect(Utils.mergeKey("today_site", _allCols[BmwShops.siteid]), ONE); //今天开的店铺分布
}
}
}
protected void setup(String[] args) {
this.taskNum = 100;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(),
new ShopCenter(), args);
System.exit(res);
}
}
| GB18030 | Java | 3,534 | java | ShopCenter.java | Java | []
| null | []
| package org.dueam.hadoop.jobs;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.lib.LongSumReducer;
import org.apache.hadoop.util.ToolRunner;
import org.dueam.hadoop.common.HadoopTable;
import org.dueam.hadoop.common.SimpleMapReduce;
import org.dueam.hadoop.common.tables.AuctionAuctions;
import org.dueam.hadoop.common.tables.BmwShops;
import org.dueam.hadoop.common.util.DateStringUtils;
import org.dueam.hadoop.common.util.Utils;
import javax.rmi.CORBA.Util;
import java.io.IOException;
/**
* 追踪店铺增长情况
*/
public class ShopCenter extends SimpleMapReduce {
@Override
protected String[] getInputPath(String[] args) {
String[] input = HadoopTable.shop(args[0]).getInputPath();
System.out.println("input path => " + Utils.asString(input));
return input;
}
@Override
protected Class getInputFormat() {
return HadoopTable.shop(null).getInputFormat();
}
@Override
protected String getOutputPath(String[] args) {
return "/group/tbdev/xiaodu/suoni/shop_center/" + args[0];
}
@Override
protected void beforeRun(String[] args, JobConf config) {
config.setCombinerClass(LongSumReducer.class);
}
@Override
protected void doWork(String line, OutputCollector<Text, LongWritable> output) throws IOException {
String[] _allCols = StringUtils.splitPreserveAllTokens(line, TAB);
if (_allCols.length < 22) {
return;
}
String queryDate = DateStringUtils.format(inputArgs[0]);
output.collect(Utils.mergeKey("total", "all"), ONE); //所有店铺数
if (Utils.isSameDay(queryDate, _allCols[BmwShops.starts])) {
output.collect(Utils.mergeKey("total", "today"), ONE); //今天开的店铺
}
//店铺状态
output.collect(Utils.mergeKey("approve_status", _allCols[BmwShops.approve_status]), ONE);
//统计正常的店铺
if ("0".equals(_allCols[BmwShops.approve_status])) {
long promotedStatus = NumberUtils.toLong(_allCols[BmwShops.promoted_status]);
for (long status : Utils.toBitArray(promotedStatus)) {
output.collect(Utils.mergeKey("promoted_status", String.valueOf(status)), ONE);
}
long produceCount = NumberUtils.toLong(_allCols[BmwShops.products_count]);
if (produceCount >=0) {
output.collect(Utils.mergeKey("product_count", BmwShops.getArea(produceCount)), ONE);
}
//店铺类型
output.collect(Utils.mergeKey("site", _allCols[BmwShops.siteid]), ONE);
if (Utils.isSameDay(queryDate, _allCols[BmwShops.starts])) {
//店铺类型
output.collect(Utils.mergeKey("today_site", _allCols[BmwShops.siteid]), ONE); //今天开的店铺分布
}
}
}
protected void setup(String[] args) {
this.taskNum = 100;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(),
new ShopCenter(), args);
System.exit(res);
}
}
| 3,534 | 0.639744 | 0.636839 | 102 | 31.745098 | 29.739288 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598039 | false | false | 2 |
a101b43c01de1a64c03259270ec2f7059ec2f5bd | 23,562,190,640,876 | 95fcfbdbd712ca46bef3dc11fd9ccd776fcf0d9b | /SmallProject/StudentManagementSystem/src/SmallStuManageSys_mssqlserver_JDBC/StuJTableModel.java | 6ec366e2f7dab5e59dda0a670a4eb940e58301e8 | []
| no_license | yi-master/JavaPractice | https://github.com/yi-master/JavaPractice | 6f317b7919541d451f8ff7d49ebe32351d33bdd9 | d1fec2604c829bcb87faf6b41dcc3cc19bf2b770 | refs/heads/master | 2021-06-28T10:35:54.755000 | 2017-09-16T13:10:19 | 2017-09-16T13:10:19 | 102,678,487 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 建立stu表模型
* 可以对stu表进行操作
*/
package SmallStuManageSys_mssqlserver_JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.*;
public class StuJTableModel extends AbstractTableModel {
// rowData用来存放行数据,columnNames存放字段(列名)
Vector rowData, columnNames;
//构造函数,初始化数据模型
public StuJTableModel(){
this.ShowAllStu();
}
// 查询(其本质是初始化)
public void QueryStu(String sql) {
// 实例化SqlHelper对象,并加载驱动,连接数据库
SqlHelper sh = new SqlHelper();
columnNames = new Vector();
String[] names = { "ID", "Name", "Sex", "Age", "Native Place", "Department" };
// 设置列名(把列名放入到columnNames向量中)
sh.setDatabaseColumn(columnNames, names);
rowData = new Vector();// 存放行数据的向量
//获取sql语句并执行
sh.ExecuteQueryOperation(sql, rowData,columnNames);
}
//对学生表的操作(增,删,改)
public boolean UpdateStu(String sql,String str[]){
//创建SqlHelper(如果程序并发性不考虑,可以把SqlHelper做出static)
SqlHelper sh=new SqlHelper();
return sh.UpdatePerson(sql, str);
}
public void ShowAllStu() {
String sql = "select * from stu";
this.QueryStu(sql);
}
@Override
// 得到共有多少列
public int getRowCount() {
// TODO Auto-generated method stub
// rowData.size()表示列数
return this.rowData.size();
}
@Override
// 得到共有多少行
public int getColumnCount() {
// TODO Auto-generated method stub
// columnNames.size()表示行数
return this.columnNames.size();
}
@Override
// 得到某行某列的数据
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
// 先得到行row,在得到列column
return ((Vector) this.rowData.get(rowIndex)).get(columnIndex);
}
@Override
// 获取列名
public String getColumnName(int column) {
// TODO Auto-generated method stub
// 返回的是String类所以要强制转换
return (String) (this.columnNames.get(column));
}
}
| GB18030 | Java | 2,282 | java | StuJTableModel.java | Java | []
| null | []
| /*
* 建立stu表模型
* 可以对stu表进行操作
*/
package SmallStuManageSys_mssqlserver_JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.*;
public class StuJTableModel extends AbstractTableModel {
// rowData用来存放行数据,columnNames存放字段(列名)
Vector rowData, columnNames;
//构造函数,初始化数据模型
public StuJTableModel(){
this.ShowAllStu();
}
// 查询(其本质是初始化)
public void QueryStu(String sql) {
// 实例化SqlHelper对象,并加载驱动,连接数据库
SqlHelper sh = new SqlHelper();
columnNames = new Vector();
String[] names = { "ID", "Name", "Sex", "Age", "Native Place", "Department" };
// 设置列名(把列名放入到columnNames向量中)
sh.setDatabaseColumn(columnNames, names);
rowData = new Vector();// 存放行数据的向量
//获取sql语句并执行
sh.ExecuteQueryOperation(sql, rowData,columnNames);
}
//对学生表的操作(增,删,改)
public boolean UpdateStu(String sql,String str[]){
//创建SqlHelper(如果程序并发性不考虑,可以把SqlHelper做出static)
SqlHelper sh=new SqlHelper();
return sh.UpdatePerson(sql, str);
}
public void ShowAllStu() {
String sql = "select * from stu";
this.QueryStu(sql);
}
@Override
// 得到共有多少列
public int getRowCount() {
// TODO Auto-generated method stub
// rowData.size()表示列数
return this.rowData.size();
}
@Override
// 得到共有多少行
public int getColumnCount() {
// TODO Auto-generated method stub
// columnNames.size()表示行数
return this.columnNames.size();
}
@Override
// 得到某行某列的数据
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
// 先得到行row,在得到列column
return ((Vector) this.rowData.get(rowIndex)).get(columnIndex);
}
@Override
// 获取列名
public String getColumnName(int column) {
// TODO Auto-generated method stub
// 返回的是String类所以要强制转换
return (String) (this.columnNames.get(column));
}
}
| 2,282 | 0.716597 | 0.716597 | 89 | 20.52809 | 18.09531 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.41573 | false | false | 2 |
92f2c54866bcd014270c1b5ab48e55e96e6d1459 | 18,605,798,329,108 | 5d8ee94397ef7bf37a1637307acbb3d963051fc7 | /src/main/java/com/straders/algo/margin/Quantity.java | 43e33d114fcdcfd83ae59f1fccdf846e81e51c71 | []
| no_license | smdsheriff/algo | https://github.com/smdsheriff/algo | d694449226183e97130dcb629b530f031df53c2e | e579f9ad423617f75eb7aeb097d1d1053f8e04c9 | refs/heads/main | 2023-03-26T13:16:00.994000 | 2021-04-03T08:34:32 | 2021-04-03T08:34:32 | 354,240,045 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.straders.algo.margin;
import com.straders.algo.process.Stocks;
import com.straders.algo.url.URL;
public class Quantity extends Stocks {
private Integer exposure = 8;
private Integer valuePerStock = 5000;
private Integer maxValuePerStock = 10000;
private Integer maxNiftyQunatity = 150;
private Integer maxBankNiftyQuantity = 50;
public Integer getQuantity(Double ltp) {
return Math.round(makeInteger(((valuePerStock / ltp) * exposure)));
}
public Boolean withinRange(Integer quantity, Double ltp) {
return ((quantity * ltp) / exposure) < maxValuePerStock;
}
public Integer withIndexRange(String symbol, Integer oldQuantity) {
if (symbol.equalsIgnoreCase(URL.NIFTY_50.getName())) {
return oldQuantity < maxNiftyQunatity ? oldQuantity + 75 : oldQuantity;
} else {
return oldQuantity < maxBankNiftyQuantity ? oldQuantity + 25 : oldQuantity;
}
}
}
| UTF-8 | Java | 930 | java | Quantity.java | Java | []
| null | []
| package com.straders.algo.margin;
import com.straders.algo.process.Stocks;
import com.straders.algo.url.URL;
public class Quantity extends Stocks {
private Integer exposure = 8;
private Integer valuePerStock = 5000;
private Integer maxValuePerStock = 10000;
private Integer maxNiftyQunatity = 150;
private Integer maxBankNiftyQuantity = 50;
public Integer getQuantity(Double ltp) {
return Math.round(makeInteger(((valuePerStock / ltp) * exposure)));
}
public Boolean withinRange(Integer quantity, Double ltp) {
return ((quantity * ltp) / exposure) < maxValuePerStock;
}
public Integer withIndexRange(String symbol, Integer oldQuantity) {
if (symbol.equalsIgnoreCase(URL.NIFTY_50.getName())) {
return oldQuantity < maxNiftyQunatity ? oldQuantity + 75 : oldQuantity;
} else {
return oldQuantity < maxBankNiftyQuantity ? oldQuantity + 25 : oldQuantity;
}
}
}
| 930 | 0.721505 | 0.698925 | 35 | 24.571428 | 26.390783 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.171429 | false | false | 2 |
34dbffe41161b8c397e5dffec3cb0966f482e509 | 18,605,798,327,342 | e9a9ebd570dba2d6bc19514dcf9c9c1f9f1de879 | /src/main/java/com/yinzhiwu/yiwu/dao/impl/DanceYzwDaoImpl.java | c0cd61b6e960b7050004a80569b53b094f16db80 | []
| no_license | ping-0123/yiwu | https://github.com/ping-0123/yiwu | b868f4b31ee5591e10cfd2818364bb38d0e0a7bd | eeaa6981b0836555f76b8528382e7d461cdacbed | refs/heads/master | 2021-01-19T10:52:52.386000 | 2017-12-08T05:24:36 | 2017-12-08T05:24:36 | 87,905,504 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yinzhiwu.yiwu.dao.impl;
import org.springframework.stereotype.Repository;
import com.yinzhiwu.yiwu.dao.DanceYzwDao;
import com.yinzhiwu.yiwu.entity.yzw.DanceYzw;
/**
*@Author ping
*@Time 创建时间:2017年10月31日下午3:35:12
*
*/
@Repository
public class DanceYzwDaoImpl extends BaseDaoImpl<DanceYzw,String> implements DanceYzwDao {
}
| UTF-8 | Java | 359 | java | DanceYzwDaoImpl.java | Java | [
{
"context": "m.yinzhiwu.yiwu.entity.yzw.DanceYzw;\n\n/**\n*@Author ping\n*@Time 创建时间:2017年10月31日下午3:35:12\n*\n*/\n\n@Reposito",
"end": 194,
"score": 0.8284021019935608,
"start": 190,
"tag": "USERNAME",
"value": "ping"
}
]
| null | []
| package com.yinzhiwu.yiwu.dao.impl;
import org.springframework.stereotype.Repository;
import com.yinzhiwu.yiwu.dao.DanceYzwDao;
import com.yinzhiwu.yiwu.entity.yzw.DanceYzw;
/**
*@Author ping
*@Time 创建时间:2017年10月31日下午3:35:12
*
*/
@Repository
public class DanceYzwDaoImpl extends BaseDaoImpl<DanceYzw,String> implements DanceYzwDao {
}
| 359 | 0.794721 | 0.756598 | 17 | 19.058823 | 25.0305 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 2 |
f1ab1a62b7f7a712a40fe917c469cd67e1a6ca81 | 7,069,516,230,555 | 354d1df2fea63abbe4d726735208b723c2187510 | /app/src/main/java/com/scavi/de/gw2imp/communication/response/items/Details.java | 933805aef6944226e24f65908ad255eebf614141 | [
"Apache-2.0"
]
| permissive | Scavi/Gw2Imp | https://github.com/Scavi/Gw2Imp | 667cc06ab0890e0c60a3da5108324bc174bb5e69 | e1437893091074327a0a763e9f7e0dfd87224d50 | refs/heads/master | 2021-05-07T23:47:34.240000 | 2018-07-15T12:47:57 | 2018-07-15T12:47:57 | 107,571,164 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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.scavi.de.gw2imp.communication.response.items;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Additional item details if applicable, depending on the item type
*/
public class Details {
@SerializedName("type")
@Expose
private String type;
@SerializedName("damage_type")
@Expose
private String damageType;
@SerializedName("min_power")
@Expose
private Integer minPower;
@SerializedName("max_power")
@Expose
private Integer maxPower;
@SerializedName("defense")
@Expose
private Integer defense;
@SerializedName("infusion_slots")
@Expose
private List<Object> infusionSlots;
@SerializedName("infix_upgrade")
@Expose
private InfixUpgrade infixUpgrade;
@SerializedName("suffix_item_id")
@Expose
private Integer suffixItemId;
@SerializedName("secondary_suffix_item_id")
@Expose
private String secondarySuffixItemId;
/**
* @return The weapon type.
* One-handed main hand: Axe, Dagger, Mace, Pistol, Scepter, Sword
* One-handed off hand: Focus, Shield, Torch, Warhorn
* Two-handed: Greatsword, Hammer, LongBow, Rifle, ShortBow, Staff
* Aquatic: Harpoon, Weapon, Trident
* Other: LargeBundle, SmallBundle, Toy, TwoHandedToy
*/
public String getType() {
return type;
}
/**
* @param type The weapon type.
* One-handed main hand: Axe, Dagger, Mace, Pistol, Scepter, Sword
* One-handed off hand: Focus, Shield, Torch, Warhorn
* Two-handed: Greatsword, Hammer, LongBow, Rifle, ShortBow, Staff
* Aquatic: Harpoon, Weapon, Trident
* Other: LargeBundle, SmallBundle, Toy, TwoHandedToy
*/
public void setType(String type) {
this.type = type;
}
/**
* @return The damage type.
* Fire – Fire damage
* Ice – Ice damage
* Lightning – Lighting damage
* Physical – Physical damage.
* Choking – (not used)
*/
public String getDamageType() {
return damageType;
}
/**
* @param damageType The damage type.
* Fire – Fire damage
* Ice – Ice damage
* Lightning – Lighting damage
* Physical – Physical damage.
* Choking – (not used)
*/
public void setDamageType(String damageType) {
this.damageType = damageType;
}
/**
* @return Minimum weapon strength.
*/
public Integer getMinPower() {
return minPower;
}
/**
* @param minPower Minimum weapon strength.
*/
public void setMinPower(Integer minPower) {
this.minPower = minPower;
}
/**
* @return Maximum weapon strength.
*/
public Integer getMaxPower() {
return maxPower;
}
/**
* @param maxPower Maximum weapon strength.
*/
public void setMaxPower(Integer maxPower) {
this.maxPower = maxPower;
}
/**
* @return The defense value of the weapon (for shields).
*/
public Integer getDefense() {
return defense;
}
/**
* @param defense The defense value of the weapon (for shields).
*/
public void setDefense(Integer defense) {
this.defense = defense;
}
/**
* @return Infusion slots of the weapon
*/
public List<Object> getInfusionSlots() { // TODO object
return infusionSlots;
}
/**
* @param infusionSlots Infusion slots of the weapon
*/
public void setInfusionSlots(List<Object> infusionSlots) { // TODO object
this.infusionSlots = infusionSlots;
}
/**
* @return The infix upgrade object
*/
public InfixUpgrade getInfixUpgrade() {
return infixUpgrade;
}
/**
* @param infixUpgrade The infix upgrade object
*/
public void setInfixUpgrade(InfixUpgrade infixUpgrade) {
this.infixUpgrade = infixUpgrade;
}
/**
* @return The suffix item id. This is usually a sigil.
*/
public Integer getSuffixItemId() {
return suffixItemId;
}
/**
* @param suffixItemId The suffix item id. This is usually a sigil.
*/
public void setSuffixItemId(Integer suffixItemId) {
this.suffixItemId = suffixItemId;
}
/**
* @return The secondary suffix item id. Equals to an empty string for all currently discovered items.
*/
public String getSecondarySuffixItemId() {
return secondarySuffixItemId;
}
/**
* @param secondarySuffixItemId The secondary suffix item id. Equals to an empty string for all currently discovered items.
*/
public void setSecondarySuffixItemId(String secondarySuffixItemId) {
this.secondarySuffixItemId = secondarySuffixItemId;
}
// TODO stat_choices
}
| UTF-8 | Java | 5,549 | java | Details.java | Java | []
| null | []
| /*
* 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.scavi.de.gw2imp.communication.response.items;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Additional item details if applicable, depending on the item type
*/
public class Details {
@SerializedName("type")
@Expose
private String type;
@SerializedName("damage_type")
@Expose
private String damageType;
@SerializedName("min_power")
@Expose
private Integer minPower;
@SerializedName("max_power")
@Expose
private Integer maxPower;
@SerializedName("defense")
@Expose
private Integer defense;
@SerializedName("infusion_slots")
@Expose
private List<Object> infusionSlots;
@SerializedName("infix_upgrade")
@Expose
private InfixUpgrade infixUpgrade;
@SerializedName("suffix_item_id")
@Expose
private Integer suffixItemId;
@SerializedName("secondary_suffix_item_id")
@Expose
private String secondarySuffixItemId;
/**
* @return The weapon type.
* One-handed main hand: Axe, Dagger, Mace, Pistol, Scepter, Sword
* One-handed off hand: Focus, Shield, Torch, Warhorn
* Two-handed: Greatsword, Hammer, LongBow, Rifle, ShortBow, Staff
* Aquatic: Harpoon, Weapon, Trident
* Other: LargeBundle, SmallBundle, Toy, TwoHandedToy
*/
public String getType() {
return type;
}
/**
* @param type The weapon type.
* One-handed main hand: Axe, Dagger, Mace, Pistol, Scepter, Sword
* One-handed off hand: Focus, Shield, Torch, Warhorn
* Two-handed: Greatsword, Hammer, LongBow, Rifle, ShortBow, Staff
* Aquatic: Harpoon, Weapon, Trident
* Other: LargeBundle, SmallBundle, Toy, TwoHandedToy
*/
public void setType(String type) {
this.type = type;
}
/**
* @return The damage type.
* Fire – Fire damage
* Ice – Ice damage
* Lightning – Lighting damage
* Physical – Physical damage.
* Choking – (not used)
*/
public String getDamageType() {
return damageType;
}
/**
* @param damageType The damage type.
* Fire – Fire damage
* Ice – Ice damage
* Lightning – Lighting damage
* Physical – Physical damage.
* Choking – (not used)
*/
public void setDamageType(String damageType) {
this.damageType = damageType;
}
/**
* @return Minimum weapon strength.
*/
public Integer getMinPower() {
return minPower;
}
/**
* @param minPower Minimum weapon strength.
*/
public void setMinPower(Integer minPower) {
this.minPower = minPower;
}
/**
* @return Maximum weapon strength.
*/
public Integer getMaxPower() {
return maxPower;
}
/**
* @param maxPower Maximum weapon strength.
*/
public void setMaxPower(Integer maxPower) {
this.maxPower = maxPower;
}
/**
* @return The defense value of the weapon (for shields).
*/
public Integer getDefense() {
return defense;
}
/**
* @param defense The defense value of the weapon (for shields).
*/
public void setDefense(Integer defense) {
this.defense = defense;
}
/**
* @return Infusion slots of the weapon
*/
public List<Object> getInfusionSlots() { // TODO object
return infusionSlots;
}
/**
* @param infusionSlots Infusion slots of the weapon
*/
public void setInfusionSlots(List<Object> infusionSlots) { // TODO object
this.infusionSlots = infusionSlots;
}
/**
* @return The infix upgrade object
*/
public InfixUpgrade getInfixUpgrade() {
return infixUpgrade;
}
/**
* @param infixUpgrade The infix upgrade object
*/
public void setInfixUpgrade(InfixUpgrade infixUpgrade) {
this.infixUpgrade = infixUpgrade;
}
/**
* @return The suffix item id. This is usually a sigil.
*/
public Integer getSuffixItemId() {
return suffixItemId;
}
/**
* @param suffixItemId The suffix item id. This is usually a sigil.
*/
public void setSuffixItemId(Integer suffixItemId) {
this.suffixItemId = suffixItemId;
}
/**
* @return The secondary suffix item id. Equals to an empty string for all currently discovered items.
*/
public String getSecondarySuffixItemId() {
return secondarySuffixItemId;
}
/**
* @param secondarySuffixItemId The secondary suffix item id. Equals to an empty string for all currently discovered items.
*/
public void setSecondarySuffixItemId(String secondarySuffixItemId) {
this.secondarySuffixItemId = secondarySuffixItemId;
}
// TODO stat_choices
}
| 5,549 | 0.62543 | 0.624525 | 201 | 26.507463 | 24.260223 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363184 | false | false | 2 |
efc0544aac52c2d95d244ea5e60480241a1d3dc1 | 7,524,782,763,748 | 4ef930e77f0e9ed5bcd477f650d8b3872f623e64 | /Start/Task3.java | 92fb366708e0440bd13e7d38ce53ec9b017eab21 | []
| no_license | AurovD/Start | https://github.com/AurovD/Start | e0862632aeba48f27178e11baa9be5b27444b419 | b8168c2f6627b1bb0ccc4ede8fc3c341b2798690 | refs/heads/master | 2020-04-15T03:24:50.810000 | 2019-01-06T21:45:38 | 2019-01-06T21:45:38 | 164,347,735 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Input three numbers:");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int min = Math.min(a, Math.min(b, c));
int max = Math.max(a, Math.max(b, c));
int mid = Math.min(max, Math.min(a, Math.max(b, c)));
System.out.println(min + " " + mid + " " + max);
}
}
| UTF-8 | Java | 544 | java | Task3.java | Java | []
| null | []
| import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Input three numbers:");
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
int min = Math.min(a, Math.min(b, c));
int max = Math.max(a, Math.max(b, c));
int mid = Math.min(max, Math.min(a, Math.max(b, c)));
System.out.println(min + " " + mid + " " + max);
}
}
| 544 | 0.511029 | 0.509191 | 20 | 25.450001 | 20.927195 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.85 | false | false | 2 |
b20a078d65e55e972b624218e0d7a26b6847afda | 5,695,126,699,585 | b65e7e706515c699fd7d9cf3602a2065212615d0 | /LoginForm/app/src/main/java/com/example/loginform/LoginActivity.java | 3c2e62949737cd6dd8187dc64e9a28c05b67bb2b | []
| no_license | ThiKiet/Android | https://github.com/ThiKiet/Android | 027c36e1a9de11480e53087f9bf5e4caf7e32e5e | 8b70bea99489b362815e275ce7c4efb11535e2f8 | refs/heads/master | 2020-07-23T20:12:44.212000 | 2019-09-16T01:12:34 | 2019-09-16T01:12:34 | 207,694,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.loginform;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = findViewById(R.id.login);
final EditText editUsername = findViewById(R.id.editUsername);
final EditText editPassword = findViewById(R.id.editpassword);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = editUsername.getText().toString();
String password = editPassword.getText().toString();
Intent loginIntent = new Intent(view.getContext(), MainActivity.class);
loginIntent.putExtra("email", email);
loginIntent.putExtra("password", password);
startActivityForResult(loginIntent, 0);
}
});
}}
| UTF-8 | Java | 1,198 | java | LoginActivity.java | Java | [
{
"context": ";\n loginIntent.putExtra(\"password\", password);\n startActivityForResult(loginInt",
"end": 1105,
"score": 0.9915192723274231,
"start": 1097,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.example.loginform;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = findViewById(R.id.login);
final EditText editUsername = findViewById(R.id.editUsername);
final EditText editPassword = findViewById(R.id.editpassword);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String email = editUsername.getText().toString();
String password = editPassword.getText().toString();
Intent loginIntent = new Intent(view.getContext(), MainActivity.class);
loginIntent.putExtra("email", email);
loginIntent.putExtra("password", <PASSWORD>);
startActivityForResult(loginIntent, 0);
}
});
}}
| 1,200 | 0.669449 | 0.668614 | 34 | 34.205883 | 25.442877 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.676471 | false | false | 2 |
1d61bbe1354f45e57c99f5b3b55b2bc352824bf6 | 11,957,189,014,248 | b1979f178fe4c13b6e6b82f75acc012c8e327412 | /Venice/Venice-Interface-Model/src/main/java/com/gdn/venice/persistence/FinJournalTransaction.java | 2f81c056cd472371734ffbb6dcef62400360821d | [
"Apache-2.0"
]
| permissive | yauritux/venice-legacy | https://github.com/yauritux/venice-legacy | 57ce5ff6c37dcb4e6efd299975326101c7ef6bd5 | 0a04259bed3a3564b2d6663b663fd8901fb67e3c | refs/heads/master | 2016-09-06T12:04:43.249000 | 2013-12-10T18:47:09 | 2013-12-10T18:47:09 | 14,918,264 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gdn.venice.persistence;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the fin_journal_transaction database table.
*
*/
@Entity
@Table(name="fin_journal_transaction")
public class FinJournalTransaction implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="fin_journal_transaction")
@TableGenerator(name="fin_journal_transaction", table="openjpaseq", pkColumnName="id", valueColumnName="sequence_value", allocationSize=1) //flush every 1 insert
@Column(name="transaction_id", unique=true, nullable=false)
private Long transactionId;
@Column(length=1000)
private String comments;
@Column(name="credit_debit_flag", nullable=false)
private Boolean creditDebitFlag;
@Column(name="transaction_amount", nullable=false, precision=20, scale=2)
private BigDecimal transactionAmount;
@Column(name="transaction_timestamp", nullable=false)
private Timestamp transactionTimestamp;
//bi-directional many-to-one association to FinApManualJournalTransaction
@OneToMany(mappedBy="finJournalTransaction")
private List<FinApManualJournalTransaction> finApManualJournalTransactions;
//bi-directional many-to-one association to FinAccount
@ManyToOne
@JoinColumn(name="account_id", nullable=false)
private FinAccount finAccount;
//bi-directional many-to-many association to FinApInvoice
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ap_invoice_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="ap_invoice_id", nullable=false)
}
)
private List<FinApInvoice> finApInvoices;
//bi-directional many-to-many association to FinApPayment
//update by olive to comment out fetchtype.eager
//read http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html for more info
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ap_payment_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="ap_payment_id", nullable=false)
}
)
private List<FinApPayment> finApPayments;
//bi-directional many-to-many association to FinArFundsInReconRecord
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ar_funds_in_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="reconciliation_record_id", nullable=false)
}
)
private List<FinArFundsInReconRecord> finArFundsInReconRecords;
//bi-directional many-to-one association to FinJournal
@ManyToOne
@JoinColumn(name="journal_id", nullable=false)
private FinJournal finJournal;
//bi-directional many-to-one association to FinJournalApprovalGroup
@ManyToOne
@JoinColumn(name="journal_group_id", nullable=false)
private FinJournalApprovalGroup finJournalApprovalGroup;
//bi-directional many-to-one association to FinPeriod
@ManyToOne
@JoinColumn(name="period_id", nullable=false)
private FinPeriod finPeriod;
//bi-directional many-to-one association to FinTransactionStatus
@ManyToOne
@JoinColumn(name="transaction_status_id", nullable=false)
private FinTransactionStatus finTransactionStatus;
//bi-directional many-to-one association to FinTransactionType
@ManyToOne
@JoinColumn(name="transaction_type_id", nullable=false)
private FinTransactionType finTransactionType;
//bi-directional many-to-many association to FinSalesRecord
@ManyToMany(mappedBy="finJournalTransactions")//, fetch=FetchType.EAGER)
private List<FinSalesRecord> finSalesRecords;
//bi-directional many-to-one association to FinArFundsInJournalTransaction
@OneToMany(mappedBy="finJournalTransactions")
private List<FinArFundsInJournalTransaction> finArFundsInJournalTransactions;
//bi-directional many-to-one association to FinPeriod
@ManyToOne
@JoinColumn(name="bank_id")//, nullable=false)
private VenBank venBank;
@Column(name="group_journal", nullable=true)
private Long groupJournal;
@Column(name="unpaid_transaction_amount", precision=20, scale=2)
private BigDecimal unpaidTransactionAmount;
public Long getGroupJournal() {
return groupJournal;
}
public void setGroupJournal(Long groupJournal) {
this.groupJournal = groupJournal;
}
public VenBank getVenBank() {
return venBank;
}
public void setVenBank(VenBank venBank) {
this.venBank = venBank;
}
@Column(name="wcs_order_id", length=100)
private String wcsOrderID;
public FinJournalTransaction() {
}
public Long getTransactionId() {
return this.transactionId;
}
public void setTransactionId(Long transactionId) {
this.transactionId = transactionId;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Boolean getCreditDebitFlag() {
return this.creditDebitFlag;
}
public void setCreditDebitFlag(Boolean creditDebitFlag) {
this.creditDebitFlag = creditDebitFlag;
}
public BigDecimal getTransactionAmount() {
return this.transactionAmount;
}
public void setTransactionAmount(BigDecimal transactionAmount) {
this.transactionAmount = transactionAmount;
}
public Timestamp getTransactionTimestamp() {
return this.transactionTimestamp;
}
public void setTransactionTimestamp(Timestamp transactionTimestamp) {
this.transactionTimestamp = transactionTimestamp;
}
public List<FinApManualJournalTransaction> getFinApManualJournalTransactions() {
return this.finApManualJournalTransactions;
}
public void setFinApManualJournalTransactions(List<FinApManualJournalTransaction> finApManualJournalTransactions) {
this.finApManualJournalTransactions = finApManualJournalTransactions;
}
public FinAccount getFinAccount() {
return this.finAccount;
}
public void setFinAccount(FinAccount finAccount) {
this.finAccount = finAccount;
}
public List<FinApInvoice> getFinApInvoices() {
return this.finApInvoices;
}
public void setFinApInvoices(List<FinApInvoice> finApInvoices) {
this.finApInvoices = finApInvoices;
}
public List<FinApPayment> getFinApPayments() {
return this.finApPayments;
}
public void setFinApPayments(List<FinApPayment> finApPayments) {
this.finApPayments = finApPayments;
}
public List<FinArFundsInReconRecord> getFinArFundsInReconRecords() {
return this.finArFundsInReconRecords;
}
public void setFinArFundsInReconRecords(List<FinArFundsInReconRecord> finArFundsInReconRecords) {
this.finArFundsInReconRecords = finArFundsInReconRecords;
}
public FinJournal getFinJournal() {
return this.finJournal;
}
public void setFinJournal(FinJournal finJournal) {
this.finJournal = finJournal;
}
public FinJournalApprovalGroup getFinJournalApprovalGroup() {
return this.finJournalApprovalGroup;
}
public void setFinJournalApprovalGroup(FinJournalApprovalGroup finJournalApprovalGroup) {
this.finJournalApprovalGroup = finJournalApprovalGroup;
}
public FinPeriod getFinPeriod() {
return this.finPeriod;
}
public void setFinPeriod(FinPeriod finPeriod) {
this.finPeriod = finPeriod;
}
public FinTransactionStatus getFinTransactionStatus() {
return this.finTransactionStatus;
}
public void setFinTransactionStatus(FinTransactionStatus finTransactionStatus) {
this.finTransactionStatus = finTransactionStatus;
}
public FinTransactionType getFinTransactionType() {
return this.finTransactionType;
}
public void setFinTransactionType(FinTransactionType finTransactionType) {
this.finTransactionType = finTransactionType;
}
public List<FinSalesRecord> getFinSalesRecords() {
return this.finSalesRecords;
}
public void setFinSalesRecords(List<FinSalesRecord> finSalesRecords) {
this.finSalesRecords = finSalesRecords;
}
public String getWcsOrderID() {
return this.wcsOrderID;
}
public void setWcsOrderID(String wcsOrderID) {
this.wcsOrderID = wcsOrderID;
}
public List<FinArFundsInJournalTransaction> getFinArFundsInJournalTransactions() {
return finArFundsInJournalTransactions;
}
public void setFinArFundsInJournalTransactions(
List<FinArFundsInJournalTransaction> finArFundsInJournalTransactions) {
this.finArFundsInJournalTransactions = finArFundsInJournalTransactions;
}
public BigDecimal getUnpaidTransactionAmount() {
return unpaidTransactionAmount;
}
public void setUnpaidTransactionAmount(BigDecimal unpaidTransactionAmount) {
this.unpaidTransactionAmount = unpaidTransactionAmount;
}
} | UTF-8 | Java | 8,718 | java | FinJournalTransaction.java | Java | [
{
"context": "o-many association to FinApPayment\n //update by olive to comment out fetchtype.eager \n //read http:/",
"end": 1908,
"score": 0.9634575843811035,
"start": 1903,
"tag": "USERNAME",
"value": "olive"
}
]
| null | []
| package com.gdn.venice.persistence;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the fin_journal_transaction database table.
*
*/
@Entity
@Table(name="fin_journal_transaction")
public class FinJournalTransaction implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="fin_journal_transaction")
@TableGenerator(name="fin_journal_transaction", table="openjpaseq", pkColumnName="id", valueColumnName="sequence_value", allocationSize=1) //flush every 1 insert
@Column(name="transaction_id", unique=true, nullable=false)
private Long transactionId;
@Column(length=1000)
private String comments;
@Column(name="credit_debit_flag", nullable=false)
private Boolean creditDebitFlag;
@Column(name="transaction_amount", nullable=false, precision=20, scale=2)
private BigDecimal transactionAmount;
@Column(name="transaction_timestamp", nullable=false)
private Timestamp transactionTimestamp;
//bi-directional many-to-one association to FinApManualJournalTransaction
@OneToMany(mappedBy="finJournalTransaction")
private List<FinApManualJournalTransaction> finApManualJournalTransactions;
//bi-directional many-to-one association to FinAccount
@ManyToOne
@JoinColumn(name="account_id", nullable=false)
private FinAccount finAccount;
//bi-directional many-to-many association to FinApInvoice
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ap_invoice_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="ap_invoice_id", nullable=false)
}
)
private List<FinApInvoice> finApInvoices;
//bi-directional many-to-many association to FinApPayment
//update by olive to comment out fetchtype.eager
//read http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html for more info
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ap_payment_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="ap_payment_id", nullable=false)
}
)
private List<FinApPayment> finApPayments;
//bi-directional many-to-many association to FinArFundsInReconRecord
@ManyToMany//(fetch=FetchType.EAGER)
@JoinTable(
name="fin_ar_funds_in_journal_transaction"
, joinColumns={
@JoinColumn(name="transaction_id", nullable=false)
}
, inverseJoinColumns={
@JoinColumn(name="reconciliation_record_id", nullable=false)
}
)
private List<FinArFundsInReconRecord> finArFundsInReconRecords;
//bi-directional many-to-one association to FinJournal
@ManyToOne
@JoinColumn(name="journal_id", nullable=false)
private FinJournal finJournal;
//bi-directional many-to-one association to FinJournalApprovalGroup
@ManyToOne
@JoinColumn(name="journal_group_id", nullable=false)
private FinJournalApprovalGroup finJournalApprovalGroup;
//bi-directional many-to-one association to FinPeriod
@ManyToOne
@JoinColumn(name="period_id", nullable=false)
private FinPeriod finPeriod;
//bi-directional many-to-one association to FinTransactionStatus
@ManyToOne
@JoinColumn(name="transaction_status_id", nullable=false)
private FinTransactionStatus finTransactionStatus;
//bi-directional many-to-one association to FinTransactionType
@ManyToOne
@JoinColumn(name="transaction_type_id", nullable=false)
private FinTransactionType finTransactionType;
//bi-directional many-to-many association to FinSalesRecord
@ManyToMany(mappedBy="finJournalTransactions")//, fetch=FetchType.EAGER)
private List<FinSalesRecord> finSalesRecords;
//bi-directional many-to-one association to FinArFundsInJournalTransaction
@OneToMany(mappedBy="finJournalTransactions")
private List<FinArFundsInJournalTransaction> finArFundsInJournalTransactions;
//bi-directional many-to-one association to FinPeriod
@ManyToOne
@JoinColumn(name="bank_id")//, nullable=false)
private VenBank venBank;
@Column(name="group_journal", nullable=true)
private Long groupJournal;
@Column(name="unpaid_transaction_amount", precision=20, scale=2)
private BigDecimal unpaidTransactionAmount;
public Long getGroupJournal() {
return groupJournal;
}
public void setGroupJournal(Long groupJournal) {
this.groupJournal = groupJournal;
}
public VenBank getVenBank() {
return venBank;
}
public void setVenBank(VenBank venBank) {
this.venBank = venBank;
}
@Column(name="wcs_order_id", length=100)
private String wcsOrderID;
public FinJournalTransaction() {
}
public Long getTransactionId() {
return this.transactionId;
}
public void setTransactionId(Long transactionId) {
this.transactionId = transactionId;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Boolean getCreditDebitFlag() {
return this.creditDebitFlag;
}
public void setCreditDebitFlag(Boolean creditDebitFlag) {
this.creditDebitFlag = creditDebitFlag;
}
public BigDecimal getTransactionAmount() {
return this.transactionAmount;
}
public void setTransactionAmount(BigDecimal transactionAmount) {
this.transactionAmount = transactionAmount;
}
public Timestamp getTransactionTimestamp() {
return this.transactionTimestamp;
}
public void setTransactionTimestamp(Timestamp transactionTimestamp) {
this.transactionTimestamp = transactionTimestamp;
}
public List<FinApManualJournalTransaction> getFinApManualJournalTransactions() {
return this.finApManualJournalTransactions;
}
public void setFinApManualJournalTransactions(List<FinApManualJournalTransaction> finApManualJournalTransactions) {
this.finApManualJournalTransactions = finApManualJournalTransactions;
}
public FinAccount getFinAccount() {
return this.finAccount;
}
public void setFinAccount(FinAccount finAccount) {
this.finAccount = finAccount;
}
public List<FinApInvoice> getFinApInvoices() {
return this.finApInvoices;
}
public void setFinApInvoices(List<FinApInvoice> finApInvoices) {
this.finApInvoices = finApInvoices;
}
public List<FinApPayment> getFinApPayments() {
return this.finApPayments;
}
public void setFinApPayments(List<FinApPayment> finApPayments) {
this.finApPayments = finApPayments;
}
public List<FinArFundsInReconRecord> getFinArFundsInReconRecords() {
return this.finArFundsInReconRecords;
}
public void setFinArFundsInReconRecords(List<FinArFundsInReconRecord> finArFundsInReconRecords) {
this.finArFundsInReconRecords = finArFundsInReconRecords;
}
public FinJournal getFinJournal() {
return this.finJournal;
}
public void setFinJournal(FinJournal finJournal) {
this.finJournal = finJournal;
}
public FinJournalApprovalGroup getFinJournalApprovalGroup() {
return this.finJournalApprovalGroup;
}
public void setFinJournalApprovalGroup(FinJournalApprovalGroup finJournalApprovalGroup) {
this.finJournalApprovalGroup = finJournalApprovalGroup;
}
public FinPeriod getFinPeriod() {
return this.finPeriod;
}
public void setFinPeriod(FinPeriod finPeriod) {
this.finPeriod = finPeriod;
}
public FinTransactionStatus getFinTransactionStatus() {
return this.finTransactionStatus;
}
public void setFinTransactionStatus(FinTransactionStatus finTransactionStatus) {
this.finTransactionStatus = finTransactionStatus;
}
public FinTransactionType getFinTransactionType() {
return this.finTransactionType;
}
public void setFinTransactionType(FinTransactionType finTransactionType) {
this.finTransactionType = finTransactionType;
}
public List<FinSalesRecord> getFinSalesRecords() {
return this.finSalesRecords;
}
public void setFinSalesRecords(List<FinSalesRecord> finSalesRecords) {
this.finSalesRecords = finSalesRecords;
}
public String getWcsOrderID() {
return this.wcsOrderID;
}
public void setWcsOrderID(String wcsOrderID) {
this.wcsOrderID = wcsOrderID;
}
public List<FinArFundsInJournalTransaction> getFinArFundsInJournalTransactions() {
return finArFundsInJournalTransactions;
}
public void setFinArFundsInJournalTransactions(
List<FinArFundsInJournalTransaction> finArFundsInJournalTransactions) {
this.finArFundsInJournalTransactions = finArFundsInJournalTransactions;
}
public BigDecimal getUnpaidTransactionAmount() {
return unpaidTransactionAmount;
}
public void setUnpaidTransactionAmount(BigDecimal unpaidTransactionAmount) {
this.unpaidTransactionAmount = unpaidTransactionAmount;
}
} | 8,718 | 0.785157 | 0.782634 | 309 | 27.216829 | 27.210344 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.330097 | false | false | 2 |
bc0963210d562c7c76a72cbb79bc5727cd1bc526 | 27,058,294,024,502 | bfb95073e02340576fe3e63d71617afb0f16a225 | /test-sample/src/test/java/game/GameTest.java | 125535e36948845f64a9001cfc82c91ebbc9f7cb | []
| no_license | sraffalli/test-sample | https://github.com/sraffalli/test-sample | ab132cfee0a20bddf56b189f7964937f0e208c57 | 029285f0489decb56452dd29cdc9df6efb303399 | refs/heads/master | 2016-09-06T05:07:05.558000 | 2012-12-10T13:14:24 | 2012-12-10T13:14:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game;
import game.Game;
import java.util.Arrays;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import player.Player;
import rules.myamerican8.MyAmerican8Rules;
import card.Card;
import card.Color;
import card.Deck;
import card.Value;
@RunWith(MockitoJUnitRunner.class)
public class GameTest {
private static final Card _1_CLUB = Card.of(Value._1, Color.Club);
private static final Card _2_CLUB = Card.of(Value._2, Color.Club);
private static final Card _1_SPADE = Card.of(Value._1, Color.Spade);
private static final Card _1_HEART = Card.of(Value._1, Color.Heart);
@Mock
private MyAmerican8Rules rule;
@Mock
private Deck deck;
@Mock
private Player p1;
@Mock
private Player p2;
private final Game game = new Game();
@Test
public void playAGameWithOnePlayerFinishedHand() throws Exception {
List<Player> players = Arrays.asList(p1, p2);
deck.shuffle();
Mockito.when(deck.size()).thenReturn(4);
Mockito.when(deck.distribute()).thenReturn(_1_CLUB).thenReturn(_1_HEART).thenReturn(_1_SPADE).thenReturn(_2_CLUB);
p1.addCardsToHand(_1_CLUB);
p1.addCardsToHand(_1_SPADE);
p2.addCardsToHand(_1_HEART);
p2.addCardsToHand(_2_CLUB);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p1))).thenReturn(_1_CLUB).thenReturn(_1_HEART);
Mockito.when(rule.shouldStopGame(_1_CLUB, p1)).thenReturn(false);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p2))).thenReturn(_1_SPADE);
Mockito.when(rule.shouldStopGame(_1_SPADE, p2)).thenReturn(false);
Mockito.when(rule.shouldStopGame(_1_HEART, p1)).thenReturn(true);
Mockito.when(rule.findWinner(players)).thenReturn(p1);
Player winner = game.playAGame(rule, deck, players);
Assert.assertSame(p1, winner);
Mockito.verify(rule).shouldStopGame(_1_SPADE, p2);
}
@Test
public void playAGameWithNoPlayerFinishedHand() throws Exception {
List<Player> players = Arrays.asList(p1, p2);
deck.shuffle();
Mockito.when(deck.size()).thenReturn(4);
Mockito.when(deck.distribute()).thenReturn(_1_CLUB).thenReturn(_1_HEART).thenReturn(_1_SPADE).thenReturn(_2_CLUB);
p1.addCardsToHand(_1_CLUB);
p1.addCardsToHand(_1_SPADE);
p2.addCardsToHand(_1_HEART);
p2.addCardsToHand(_2_CLUB);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p1))).thenReturn(_1_CLUB).thenReturn(null);
Mockito.when(rule.shouldStopGame(_1_CLUB, p1)).thenReturn(false);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p2))).thenReturn(_2_CLUB).thenReturn(null);
Mockito.when(rule.shouldStopGame(_2_CLUB, p2)).thenReturn(false);
Mockito.when(rule.shouldStopGame(null, p1)).thenReturn(false);
Mockito.when(rule.shouldStopGame(null, p2)).thenReturn(false);
Mockito.when(rule.findWinner(players)).thenReturn(p1);
Player winner = game.playAGame(rule, deck, players);
Assert.assertSame(p1, winner);
Mockito.verify(rule).shouldStopGame(null, p1);
Mockito.verify(rule).shouldStopGame(null, p2);
}
}
| UTF-8 | Java | 3,123 | java | GameTest.java | Java | []
| null | []
| package game;
import game.Game;
import java.util.Arrays;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import player.Player;
import rules.myamerican8.MyAmerican8Rules;
import card.Card;
import card.Color;
import card.Deck;
import card.Value;
@RunWith(MockitoJUnitRunner.class)
public class GameTest {
private static final Card _1_CLUB = Card.of(Value._1, Color.Club);
private static final Card _2_CLUB = Card.of(Value._2, Color.Club);
private static final Card _1_SPADE = Card.of(Value._1, Color.Spade);
private static final Card _1_HEART = Card.of(Value._1, Color.Heart);
@Mock
private MyAmerican8Rules rule;
@Mock
private Deck deck;
@Mock
private Player p1;
@Mock
private Player p2;
private final Game game = new Game();
@Test
public void playAGameWithOnePlayerFinishedHand() throws Exception {
List<Player> players = Arrays.asList(p1, p2);
deck.shuffle();
Mockito.when(deck.size()).thenReturn(4);
Mockito.when(deck.distribute()).thenReturn(_1_CLUB).thenReturn(_1_HEART).thenReturn(_1_SPADE).thenReturn(_2_CLUB);
p1.addCardsToHand(_1_CLUB);
p1.addCardsToHand(_1_SPADE);
p2.addCardsToHand(_1_HEART);
p2.addCardsToHand(_2_CLUB);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p1))).thenReturn(_1_CLUB).thenReturn(_1_HEART);
Mockito.when(rule.shouldStopGame(_1_CLUB, p1)).thenReturn(false);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p2))).thenReturn(_1_SPADE);
Mockito.when(rule.shouldStopGame(_1_SPADE, p2)).thenReturn(false);
Mockito.when(rule.shouldStopGame(_1_HEART, p1)).thenReturn(true);
Mockito.when(rule.findWinner(players)).thenReturn(p1);
Player winner = game.playAGame(rule, deck, players);
Assert.assertSame(p1, winner);
Mockito.verify(rule).shouldStopGame(_1_SPADE, p2);
}
@Test
public void playAGameWithNoPlayerFinishedHand() throws Exception {
List<Player> players = Arrays.asList(p1, p2);
deck.shuffle();
Mockito.when(deck.size()).thenReturn(4);
Mockito.when(deck.distribute()).thenReturn(_1_CLUB).thenReturn(_1_HEART).thenReturn(_1_SPADE).thenReturn(_2_CLUB);
p1.addCardsToHand(_1_CLUB);
p1.addCardsToHand(_1_SPADE);
p2.addCardsToHand(_1_HEART);
p2.addCardsToHand(_2_CLUB);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p1))).thenReturn(_1_CLUB).thenReturn(null);
Mockito.when(rule.shouldStopGame(_1_CLUB, p1)).thenReturn(false);
Mockito.when(rule.play(Mockito.anyListOf(Card.class), Mockito.eq(p2))).thenReturn(_2_CLUB).thenReturn(null);
Mockito.when(rule.shouldStopGame(_2_CLUB, p2)).thenReturn(false);
Mockito.when(rule.shouldStopGame(null, p1)).thenReturn(false);
Mockito.when(rule.shouldStopGame(null, p2)).thenReturn(false);
Mockito.when(rule.findWinner(players)).thenReturn(p1);
Player winner = game.playAGame(rule, deck, players);
Assert.assertSame(p1, winner);
Mockito.verify(rule).shouldStopGame(null, p1);
Mockito.verify(rule).shouldStopGame(null, p2);
}
}
| 3,123 | 0.743196 | 0.720141 | 98 | 30.867348 | 30.48641 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.816326 | false | false | 2 |
098ca63be4a43b420f0329a3ebe2fba85801d2d6 | 33,543,694,611,338 | 481e1c54a0fdd009571ea2f87cd4d2954079b771 | /src/main/java/klik/backup/File_comparator.java | bbd55aee3da84bac7f83160e634eebcdeafcd3d1 | []
| no_license | philgentric/klik | https://github.com/philgentric/klik | 8369da6327138a523fd719eca835675fc5786ceb | 5cd4e001ccea3a192b2b9392178bde3f2ded3c65 | refs/heads/master | 2023-08-17T05:36:19.821000 | 2023-08-10T06:35:40 | 2023-08-10T06:35:40 | 316,992,461 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package klik.backup;
import klik.util.Logger;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
/*
this is NOT re-entrant : you need one instance per thread
*/
//**********************************************************
public class File_comparator
//**********************************************************
{
private static final int BUFFER_SIZE = 8192;//4096;//1024;
private volatile boolean abort = false;
private boolean debug_flag = true;
private byte[] hashsrc = new byte[BUFFER_SIZE];
private byte[] hashdest = new byte[BUFFER_SIZE];
Logger logger;
//**********************************************************
File_comparator(Logger logger_)
//**********************************************************
{
logger = logger_;
}
//**********************************************************
public void abort()
//**********************************************************
{
abort = true;
}
//**********************************************************
public Similarity_result files_are_same(File file_to_be_copied, File destination_file)
//**********************************************************
{
long ori_s = file_to_be_copied.length();
long des_s = destination_file.length();
if (ori_s != des_s) {
if (debug_flag == true)
logger.log("sizes differ " + file_to_be_copied.getName() + " " + ori_s + " vs " + des_s);
return Similarity_result.not_same;
}
// same size, let us check MD5, block per block
// at the first sign of a difference, return false
try (
BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(file_to_be_copied));
BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream(destination_file));
)
{
boolean quit = false;
for (;;)
{
if (abort)
{
logger.log("abort from files_are_same()");
return Similarity_result.aborted;
}
int available_src = bis1.available();
int available_dest = bis2.available();
if (available_src != available_dest)
{
//if ( debug_flag == true)
{
logger.log("read sizes differ");
}
return Similarity_result.not_same;
}
if (available_src < BUFFER_SIZE)
{
bis1.read(hashsrc, 0, available_src);
bis2.read(hashdest, 0, available_dest);
quit = true;
} else {
bis1.read(hashsrc, 0, BUFFER_SIZE);
bis2.read(hashdest, 0, BUFFER_SIZE);
}
if (Arrays.equals(hashsrc, hashdest) == false) {
//if ( debug_flag == true)
logger.log("content differ");
return Similarity_result.not_same;
}
if (quit == true) break; // last block
}
return Similarity_result.same;
} // end try
catch (Exception ioe) {
logger.log("" + ioe);
return Similarity_result.aborted;
}
}
}
| UTF-8 | Java | 3,489 | java | File_comparator.java | Java | []
| null | []
| package klik.backup;
import klik.util.Logger;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
/*
this is NOT re-entrant : you need one instance per thread
*/
//**********************************************************
public class File_comparator
//**********************************************************
{
private static final int BUFFER_SIZE = 8192;//4096;//1024;
private volatile boolean abort = false;
private boolean debug_flag = true;
private byte[] hashsrc = new byte[BUFFER_SIZE];
private byte[] hashdest = new byte[BUFFER_SIZE];
Logger logger;
//**********************************************************
File_comparator(Logger logger_)
//**********************************************************
{
logger = logger_;
}
//**********************************************************
public void abort()
//**********************************************************
{
abort = true;
}
//**********************************************************
public Similarity_result files_are_same(File file_to_be_copied, File destination_file)
//**********************************************************
{
long ori_s = file_to_be_copied.length();
long des_s = destination_file.length();
if (ori_s != des_s) {
if (debug_flag == true)
logger.log("sizes differ " + file_to_be_copied.getName() + " " + ori_s + " vs " + des_s);
return Similarity_result.not_same;
}
// same size, let us check MD5, block per block
// at the first sign of a difference, return false
try (
BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(file_to_be_copied));
BufferedInputStream bis2 = new BufferedInputStream(new FileInputStream(destination_file));
)
{
boolean quit = false;
for (;;)
{
if (abort)
{
logger.log("abort from files_are_same()");
return Similarity_result.aborted;
}
int available_src = bis1.available();
int available_dest = bis2.available();
if (available_src != available_dest)
{
//if ( debug_flag == true)
{
logger.log("read sizes differ");
}
return Similarity_result.not_same;
}
if (available_src < BUFFER_SIZE)
{
bis1.read(hashsrc, 0, available_src);
bis2.read(hashdest, 0, available_dest);
quit = true;
} else {
bis1.read(hashsrc, 0, BUFFER_SIZE);
bis2.read(hashdest, 0, BUFFER_SIZE);
}
if (Arrays.equals(hashsrc, hashdest) == false) {
//if ( debug_flag == true)
logger.log("content differ");
return Similarity_result.not_same;
}
if (quit == true) break; // last block
}
return Similarity_result.same;
} // end try
catch (Exception ioe) {
logger.log("" + ioe);
return Similarity_result.aborted;
}
}
}
| 3,489 | 0.432502 | 0.425337 | 101 | 33.544556 | 25.496855 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544554 | false | false | 2 |
3ab2d0bda55f4a19764864045eea01cb0221314a | 8,718,783,640,384 | 5403261872bfd5f166ab305567da4a18d3c4ea33 | /plugins/repository-s3/src/test/java/org/opensearch/repositories/s3/S3BlobContainerRetriesTests.java | c9486c8bbfd7811305e7413a2e9874769cbece77 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"SSPL-1.0"
]
| permissive | opensearch-project/OpenSearch | https://github.com/opensearch-project/OpenSearch | 1f1ec7be4bc949937fbc2156c5bdbcd6f50a7372 | e98ded62d4b672a03acb4beb02bd047d7d4e1c69 | refs/heads/main | 2023-09-03T15:28:02.756000 | 2023-09-02T18:55:09 | 2023-09-02T18:55:09 | 334,274,271 | 7,644 | 1,321 | Apache-2.0 | false | 2023-09-14T21:53:11 | 2021-01-29T22:10:00 | 2023-09-14T20:09:00 | 2023-09-14T21:53:10 | 558,185 | 7,536 | 1,182 | 1,403 | Java | false | false | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.repositories.s3;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.io.SdkDigestInputStream;
import software.amazon.awssdk.utils.internal.Base16;
import org.apache.http.HttpStatus;
import org.opensearch.cluster.metadata.RepositoryMetadata;
import org.opensearch.common.CheckedTriFunction;
import org.opensearch.common.Nullable;
import org.opensearch.common.StreamContext;
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.blobstore.BlobContainer;
import org.opensearch.common.blobstore.BlobPath;
import org.opensearch.common.blobstore.VerifyingMultiStreamBlobContainer;
import org.opensearch.common.blobstore.stream.write.StreamContextSupplier;
import org.opensearch.common.blobstore.stream.write.WriteContext;
import org.opensearch.common.blobstore.stream.write.WritePriority;
import org.opensearch.common.blobstore.transfer.stream.OffsetRangeIndexInputStream;
import org.opensearch.common.hash.MessageDigests;
import org.opensearch.common.io.InputStreamContainer;
import org.opensearch.common.io.Streams;
import org.opensearch.common.lucene.store.ByteArrayIndexInput;
import org.opensearch.common.lucene.store.InputStreamIndexInput;
import org.opensearch.common.network.InetAddresses;
import org.opensearch.common.settings.MockSecureSettings;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.util.concurrent.CountDown;
import org.opensearch.common.util.io.IOUtils;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.repositories.blobstore.AbstractBlobContainerRetriesTestCase;
import org.opensearch.repositories.blobstore.ZeroInputStream;
import org.opensearch.repositories.s3.async.AsyncExecutorContainer;
import org.opensearch.repositories.s3.async.AsyncTransferEventLoopGroup;
import org.opensearch.repositories.s3.async.AsyncTransferManager;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.opensearch.repositories.s3.S3ClientSettings.DISABLE_CHUNKED_ENCODING;
import static org.opensearch.repositories.s3.S3ClientSettings.ENDPOINT_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.MAX_RETRIES_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.READ_TIMEOUT_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.REGION;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
/**
* This class tests how a {@link S3BlobContainer} and its underlying AWS S3 client are retrying requests when reading or writing blobs.
*/
@SuppressForbidden(reason = "use a http server")
public class S3BlobContainerRetriesTests extends AbstractBlobContainerRetriesTestCase implements ConfigPathSupport {
private S3Service service;
private String previousOpenSearchPathConf;
private S3AsyncService asyncService;
private ExecutorService futureCompletionService;
private ExecutorService streamReaderService;
private AsyncTransferEventLoopGroup transferNIOGroup;
@Before
public void setUp() throws Exception {
previousOpenSearchPathConf = SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString()));
service = new S3Service(configPath());
asyncService = new S3AsyncService(configPath());
futureCompletionService = Executors.newSingleThreadExecutor();
streamReaderService = Executors.newSingleThreadExecutor();
transferNIOGroup = new AsyncTransferEventLoopGroup(1);
// needed by S3AsyncService
SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString()));
super.setUp();
}
@After
public void tearDown() throws Exception {
IOUtils.close(service, asyncService);
streamReaderService.shutdown();
futureCompletionService.shutdown();
IOUtils.close(transferNIOGroup);
if (previousOpenSearchPathConf != null) {
SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", previousOpenSearchPathConf));
} else {
SocketAccess.doPrivileged(() -> System.clearProperty("opensearch.path.conf"));
}
super.tearDown();
}
@Override
protected String downloadStorageEndpoint(String blob) {
return "/bucket/" + blob;
}
@Override
protected String bytesContentType() {
return "text/plain; charset=utf-8";
}
@Override
protected Class<? extends Exception> unresponsiveExceptionType() {
return SdkClientException.class;
}
@Override
protected VerifyingMultiStreamBlobContainer createBlobContainer(
final @Nullable Integer maxRetries,
final @Nullable TimeValue readTimeout,
final @Nullable Boolean disableChunkedEncoding,
final @Nullable ByteSizeValue bufferSize
) {
final Settings.Builder clientSettings = Settings.builder();
final String clientName = randomAlphaOfLength(5).toLowerCase(Locale.ROOT);
final InetSocketAddress address = httpServer.getAddress();
final String endpoint = "http://" + InetAddresses.toUriString(address.getAddress()) + ":" + address.getPort();
clientSettings.put(ENDPOINT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), endpoint);
clientSettings.put(REGION.getConcreteSettingForNamespace(clientName).getKey(), "region");
if (maxRetries != null) {
clientSettings.put(MAX_RETRIES_SETTING.getConcreteSettingForNamespace(clientName).getKey(), maxRetries);
}
if (readTimeout != null) {
clientSettings.put(READ_TIMEOUT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), readTimeout);
}
if (disableChunkedEncoding != null) {
clientSettings.put(DISABLE_CHUNKED_ENCODING.getConcreteSettingForNamespace(clientName).getKey(), disableChunkedEncoding);
}
final MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString(S3ClientSettings.ACCESS_KEY_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "access");
secureSettings.setString(S3ClientSettings.SECRET_KEY_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "secret");
clientSettings.setSecureSettings(secureSettings);
service.refreshAndClearCache(S3ClientSettings.load(clientSettings.build(), configPath()));
asyncService.refreshAndClearCache(S3ClientSettings.load(clientSettings.build(), configPath()));
final RepositoryMetadata repositoryMetadata = new RepositoryMetadata(
"repository",
S3Repository.TYPE,
Settings.builder().put(S3Repository.CLIENT_NAME.getKey(), clientName).build()
);
AsyncExecutorContainer asyncExecutorContainer = new AsyncExecutorContainer(
futureCompletionService,
streamReaderService,
transferNIOGroup
);
return new S3BlobContainer(
BlobPath.cleanPath(),
new S3BlobStore(
service,
asyncService,
true,
"bucket",
S3Repository.SERVER_SIDE_ENCRYPTION_SETTING.getDefault(Settings.EMPTY),
bufferSize == null ? S3Repository.BUFFER_SIZE_SETTING.getDefault(Settings.EMPTY) : bufferSize,
S3Repository.CANNED_ACL_SETTING.getDefault(Settings.EMPTY),
S3Repository.STORAGE_CLASS_SETTING.getDefault(Settings.EMPTY),
repositoryMetadata,
new AsyncTransferManager(
S3Repository.PARALLEL_MULTIPART_UPLOAD_MINIMUM_PART_SIZE_SETTING.getDefault(Settings.EMPTY).getBytes(),
asyncExecutorContainer.getStreamReader(),
asyncExecutorContainer.getStreamReader()
),
asyncExecutorContainer,
asyncExecutorContainer
)
) {
@Override
public InputStream readBlob(String blobName) throws IOException {
return new AssertingInputStream(super.readBlob(blobName), blobName);
}
@Override
public InputStream readBlob(String blobName, long position, long length) throws IOException {
return new AssertingInputStream(super.readBlob(blobName, position, length), blobName, position, length);
}
};
}
public void testWriteBlobWithRetries() throws Exception {
final int maxRetries = randomInt(5);
final CountDown countDown = new CountDown(maxRetries + 1);
final byte[] bytes = randomBlobContent();
httpServer.createContext("/bucket/write_blob_max_retries", exchange -> {
if ("PUT".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery() == null) {
if (countDown.countDown()) {
final BytesReference body = Streams.readFully(exchange.getRequestBody());
if (Objects.deepEquals(bytes, BytesReference.toBytes(body))) {
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1);
}
exchange.close();
return;
}
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
}
exchange.close();
}
});
final BlobContainer blobContainer = createBlobContainer(maxRetries, null, true, null);
try (InputStream stream = new ByteArrayInputStream(bytes)) {
blobContainer.writeBlob("write_blob_max_retries", stream, bytes.length, false);
}
assertThat(countDown.isCountedDown(), is(true));
}
public void testWriteBlobByStreamsWithRetries() throws Exception {
final int maxRetries = randomInt(5);
final CountDown countDown = new CountDown(maxRetries + 1);
final byte[] bytes = randomBlobContent();
httpServer.createContext("/bucket/write_blob_by_streams_max_retries", exchange -> {
if ("PUT".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery() == null) {
if (countDown.countDown()) {
final BytesReference body = Streams.readFully(exchange.getRequestBody());
if (Objects.deepEquals(bytes, BytesReference.toBytes(body))) {
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1);
}
exchange.close();
return;
}
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
}
exchange.close();
}
});
final VerifyingMultiStreamBlobContainer blobContainer = createBlobContainer(maxRetries, null, true, null);
List<InputStream> openInputStreams = new ArrayList<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicReference<Exception> exceptionRef = new AtomicReference<>();
ActionListener<Void> completionListener = ActionListener.wrap(resp -> { countDownLatch.countDown(); }, ex -> {
exceptionRef.set(ex);
countDownLatch.countDown();
});
blobContainer.asyncBlobUpload(new WriteContext("write_blob_by_streams_max_retries", new StreamContextSupplier() {
@Override
public StreamContext supplyStreamContext(long partSize) {
return new StreamContext(new CheckedTriFunction<Integer, Long, Long, InputStreamContainer, IOException>() {
@Override
public InputStreamContainer apply(Integer partNo, Long size, Long position) throws IOException {
InputStream inputStream = new OffsetRangeIndexInputStream(new ByteArrayIndexInput("desc", bytes), size, position);
openInputStreams.add(inputStream);
return new InputStreamContainer(inputStream, size, position);
}
}, partSize, calculateLastPartSize(bytes.length, partSize), calculateNumberOfParts(bytes.length, partSize));
}
}, bytes.length, false, WritePriority.NORMAL, Assert::assertTrue, false, null), completionListener);
assertTrue(countDownLatch.await(5000, TimeUnit.SECONDS));
assertThat(countDown.isCountedDown(), is(true));
openInputStreams.forEach(inputStream -> {
try {
inputStream.close();
} catch (IOException e) {
fail("Failure while closing open input streams");
}
});
}
private long calculateLastPartSize(long totalSize, long partSize) {
return totalSize % partSize == 0 ? partSize : totalSize % partSize;
}
private int calculateNumberOfParts(long contentLength, long partSize) {
return (int) ((contentLength % partSize) == 0 ? contentLength / partSize : (contentLength / partSize) + 1);
}
public void testWriteBlobWithReadTimeouts() {
final byte[] bytes = randomByteArrayOfLength(randomIntBetween(10, 128));
final TimeValue readTimeout = TimeValue.timeValueMillis(randomIntBetween(100, 500));
final BlobContainer blobContainer = createBlobContainer(1, readTimeout, true, null);
// HTTP server does not send a response
httpServer.createContext("/bucket/write_blob_timeout", exchange -> {
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, bytes.length - 1)]);
} else {
Streams.readFully(exchange.getRequestBody());
}
}
});
Exception exception = expectThrows(IOException.class, () -> {
try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) {
blobContainer.writeBlob("write_blob_timeout", stream, bytes.length, false);
}
});
assertThat(
exception.getMessage().toLowerCase(Locale.ROOT),
containsString("unable to upload object [write_blob_timeout] using a single upload")
);
assertThat(exception.getCause(), instanceOf(SdkClientException.class));
assertThat(exception.getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out"));
assertThat(exception.getCause().getCause(), instanceOf(SocketTimeoutException.class));
assertThat(exception.getCause().getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out"));
}
public void testWriteLargeBlob() throws Exception {
final boolean useTimeout = rarely();
final TimeValue readTimeout = useTimeout ? TimeValue.timeValueMillis(randomIntBetween(100, 500)) : null;
final ByteSizeValue bufferSize = new ByteSizeValue(5, ByteSizeUnit.MB);
final BlobContainer blobContainer = createBlobContainer(null, readTimeout, true, bufferSize);
final int parts = randomIntBetween(1, 5);
final long lastPartSize = randomLongBetween(10, 512);
final long blobSize = (parts * bufferSize.getBytes()) + lastPartSize;
final int nbErrors = 2; // we want all requests to fail at least once
final CountDown countDownInitiate = new CountDown(nbErrors);
final AtomicInteger countDownUploads = new AtomicInteger(nbErrors * (parts + 1));
final CountDown countDownComplete = new CountDown(nbErrors);
httpServer.createContext("/bucket/write_large_blob", exchange -> {
final long contentLength = Long.parseLong(exchange.getRequestHeaders().getFirst("Content-Length"));
if ("POST".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery().equals("uploads")) {
// initiate multipart upload request
if (countDownInitiate.countDown()) {
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<InitiateMultipartUploadResult>\n"
+ " <Bucket>bucket</Bucket>\n"
+ " <Key>write_large_blob</Key>\n"
+ " <UploadId>TEST</UploadId>\n"
+ "</InitiateMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(HttpStatus.SC_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
return;
}
} else if ("PUT".equals(exchange.getRequestMethod())
&& exchange.getRequestURI().getQuery().contains("uploadId=TEST")
&& exchange.getRequestURI().getQuery().contains("partNumber=")) {
// upload part request
SdkDigestInputStream digestInputStream = new SdkDigestInputStream(exchange.getRequestBody(), MessageDigests.md5());
BytesReference bytes = Streams.readFully(digestInputStream);
assertThat((long) bytes.length(), anyOf(equalTo(lastPartSize), equalTo(bufferSize.getBytes())));
assertThat(contentLength, anyOf(equalTo(lastPartSize), equalTo(bufferSize.getBytes())));
if (countDownUploads.decrementAndGet() % 2 == 0) {
exchange.getResponseHeaders().add("ETag", Base16.encodeAsString(digestInputStream.getMessageDigest().digest()));
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
exchange.close();
return;
}
} else if ("POST".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery().equals("uploadId=TEST")) {
// complete multipart upload request
if (countDownComplete.countDown()) {
Streams.readFully(exchange.getRequestBody());
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<CompleteMultipartUploadResult>\n"
+ " <Bucket>bucket</Bucket>\n"
+ " <Key>write_large_blob</Key>\n"
+ "</CompleteMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(HttpStatus.SC_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
return;
}
}
// sends an error back or let the request time out
if (useTimeout == false) {
if (randomBoolean() && contentLength > 0) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.toIntExact(contentLength - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
exchange.close();
}
});
blobContainer.writeBlob("write_large_blob", new ZeroInputStream(blobSize), blobSize, false);
assertThat(countDownInitiate.isCountedDown(), is(true));
assertThat(countDownUploads.get(), equalTo(0));
assertThat(countDownComplete.isCountedDown(), is(true));
}
/**
* Asserts that an InputStream is fully consumed, or aborted, when it is closed
*/
private static class AssertingInputStream extends FilterInputStream {
private final String blobName;
private final boolean range;
private final long position;
private final long length;
AssertingInputStream(InputStream in, String blobName) {
super(in);
this.blobName = blobName;
this.position = 0L;
this.length = Long.MAX_VALUE;
this.range = false;
}
AssertingInputStream(InputStream in, String blobName, long position, long length) {
super(in);
this.blobName = blobName;
this.position = position;
this.length = length;
this.range = true;
}
@Override
public String toString() {
String description = "[blobName='" + blobName + "', range=" + range;
if (range) {
description += ", position=" + position;
description += ", length=" + length;
}
description += ']';
return description;
}
@Override
public void close() throws IOException {
super.close();
if (in instanceof S3RetryingInputStream) {
final S3RetryingInputStream s3Stream = (S3RetryingInputStream) in;
assertTrue(
"Stream "
+ toString()
+ " should have reached EOF or should have been aborted but got [eof="
+ s3Stream.isEof()
+ ", aborted="
+ s3Stream.isAborted()
+ ']',
s3Stream.isEof() || s3Stream.isAborted()
);
} else {
assertThat(in, instanceOf(ByteArrayInputStream.class));
assertThat(((ByteArrayInputStream) in).available(), equalTo(0));
}
}
}
}
| UTF-8 | Java | 25,890 | java | S3BlobContainerRetriesTests.java | Java | []
| null | []
| /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*/
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.repositories.s3;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.io.SdkDigestInputStream;
import software.amazon.awssdk.utils.internal.Base16;
import org.apache.http.HttpStatus;
import org.opensearch.cluster.metadata.RepositoryMetadata;
import org.opensearch.common.CheckedTriFunction;
import org.opensearch.common.Nullable;
import org.opensearch.common.StreamContext;
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.blobstore.BlobContainer;
import org.opensearch.common.blobstore.BlobPath;
import org.opensearch.common.blobstore.VerifyingMultiStreamBlobContainer;
import org.opensearch.common.blobstore.stream.write.StreamContextSupplier;
import org.opensearch.common.blobstore.stream.write.WriteContext;
import org.opensearch.common.blobstore.stream.write.WritePriority;
import org.opensearch.common.blobstore.transfer.stream.OffsetRangeIndexInputStream;
import org.opensearch.common.hash.MessageDigests;
import org.opensearch.common.io.InputStreamContainer;
import org.opensearch.common.io.Streams;
import org.opensearch.common.lucene.store.ByteArrayIndexInput;
import org.opensearch.common.lucene.store.InputStreamIndexInput;
import org.opensearch.common.network.InetAddresses;
import org.opensearch.common.settings.MockSecureSettings;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.util.concurrent.CountDown;
import org.opensearch.common.util.io.IOUtils;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.repositories.blobstore.AbstractBlobContainerRetriesTestCase;
import org.opensearch.repositories.blobstore.ZeroInputStream;
import org.opensearch.repositories.s3.async.AsyncExecutorContainer;
import org.opensearch.repositories.s3.async.AsyncTransferEventLoopGroup;
import org.opensearch.repositories.s3.async.AsyncTransferManager;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.opensearch.repositories.s3.S3ClientSettings.DISABLE_CHUNKED_ENCODING;
import static org.opensearch.repositories.s3.S3ClientSettings.ENDPOINT_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.MAX_RETRIES_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.READ_TIMEOUT_SETTING;
import static org.opensearch.repositories.s3.S3ClientSettings.REGION;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
/**
* This class tests how a {@link S3BlobContainer} and its underlying AWS S3 client are retrying requests when reading or writing blobs.
*/
@SuppressForbidden(reason = "use a http server")
public class S3BlobContainerRetriesTests extends AbstractBlobContainerRetriesTestCase implements ConfigPathSupport {
private S3Service service;
private String previousOpenSearchPathConf;
private S3AsyncService asyncService;
private ExecutorService futureCompletionService;
private ExecutorService streamReaderService;
private AsyncTransferEventLoopGroup transferNIOGroup;
@Before
public void setUp() throws Exception {
previousOpenSearchPathConf = SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString()));
service = new S3Service(configPath());
asyncService = new S3AsyncService(configPath());
futureCompletionService = Executors.newSingleThreadExecutor();
streamReaderService = Executors.newSingleThreadExecutor();
transferNIOGroup = new AsyncTransferEventLoopGroup(1);
// needed by S3AsyncService
SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString()));
super.setUp();
}
@After
public void tearDown() throws Exception {
IOUtils.close(service, asyncService);
streamReaderService.shutdown();
futureCompletionService.shutdown();
IOUtils.close(transferNIOGroup);
if (previousOpenSearchPathConf != null) {
SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", previousOpenSearchPathConf));
} else {
SocketAccess.doPrivileged(() -> System.clearProperty("opensearch.path.conf"));
}
super.tearDown();
}
@Override
protected String downloadStorageEndpoint(String blob) {
return "/bucket/" + blob;
}
@Override
protected String bytesContentType() {
return "text/plain; charset=utf-8";
}
@Override
protected Class<? extends Exception> unresponsiveExceptionType() {
return SdkClientException.class;
}
@Override
protected VerifyingMultiStreamBlobContainer createBlobContainer(
final @Nullable Integer maxRetries,
final @Nullable TimeValue readTimeout,
final @Nullable Boolean disableChunkedEncoding,
final @Nullable ByteSizeValue bufferSize
) {
final Settings.Builder clientSettings = Settings.builder();
final String clientName = randomAlphaOfLength(5).toLowerCase(Locale.ROOT);
final InetSocketAddress address = httpServer.getAddress();
final String endpoint = "http://" + InetAddresses.toUriString(address.getAddress()) + ":" + address.getPort();
clientSettings.put(ENDPOINT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), endpoint);
clientSettings.put(REGION.getConcreteSettingForNamespace(clientName).getKey(), "region");
if (maxRetries != null) {
clientSettings.put(MAX_RETRIES_SETTING.getConcreteSettingForNamespace(clientName).getKey(), maxRetries);
}
if (readTimeout != null) {
clientSettings.put(READ_TIMEOUT_SETTING.getConcreteSettingForNamespace(clientName).getKey(), readTimeout);
}
if (disableChunkedEncoding != null) {
clientSettings.put(DISABLE_CHUNKED_ENCODING.getConcreteSettingForNamespace(clientName).getKey(), disableChunkedEncoding);
}
final MockSecureSettings secureSettings = new MockSecureSettings();
secureSettings.setString(S3ClientSettings.ACCESS_KEY_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "access");
secureSettings.setString(S3ClientSettings.SECRET_KEY_SETTING.getConcreteSettingForNamespace(clientName).getKey(), "secret");
clientSettings.setSecureSettings(secureSettings);
service.refreshAndClearCache(S3ClientSettings.load(clientSettings.build(), configPath()));
asyncService.refreshAndClearCache(S3ClientSettings.load(clientSettings.build(), configPath()));
final RepositoryMetadata repositoryMetadata = new RepositoryMetadata(
"repository",
S3Repository.TYPE,
Settings.builder().put(S3Repository.CLIENT_NAME.getKey(), clientName).build()
);
AsyncExecutorContainer asyncExecutorContainer = new AsyncExecutorContainer(
futureCompletionService,
streamReaderService,
transferNIOGroup
);
return new S3BlobContainer(
BlobPath.cleanPath(),
new S3BlobStore(
service,
asyncService,
true,
"bucket",
S3Repository.SERVER_SIDE_ENCRYPTION_SETTING.getDefault(Settings.EMPTY),
bufferSize == null ? S3Repository.BUFFER_SIZE_SETTING.getDefault(Settings.EMPTY) : bufferSize,
S3Repository.CANNED_ACL_SETTING.getDefault(Settings.EMPTY),
S3Repository.STORAGE_CLASS_SETTING.getDefault(Settings.EMPTY),
repositoryMetadata,
new AsyncTransferManager(
S3Repository.PARALLEL_MULTIPART_UPLOAD_MINIMUM_PART_SIZE_SETTING.getDefault(Settings.EMPTY).getBytes(),
asyncExecutorContainer.getStreamReader(),
asyncExecutorContainer.getStreamReader()
),
asyncExecutorContainer,
asyncExecutorContainer
)
) {
@Override
public InputStream readBlob(String blobName) throws IOException {
return new AssertingInputStream(super.readBlob(blobName), blobName);
}
@Override
public InputStream readBlob(String blobName, long position, long length) throws IOException {
return new AssertingInputStream(super.readBlob(blobName, position, length), blobName, position, length);
}
};
}
public void testWriteBlobWithRetries() throws Exception {
final int maxRetries = randomInt(5);
final CountDown countDown = new CountDown(maxRetries + 1);
final byte[] bytes = randomBlobContent();
httpServer.createContext("/bucket/write_blob_max_retries", exchange -> {
if ("PUT".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery() == null) {
if (countDown.countDown()) {
final BytesReference body = Streams.readFully(exchange.getRequestBody());
if (Objects.deepEquals(bytes, BytesReference.toBytes(body))) {
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1);
}
exchange.close();
return;
}
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
}
exchange.close();
}
});
final BlobContainer blobContainer = createBlobContainer(maxRetries, null, true, null);
try (InputStream stream = new ByteArrayInputStream(bytes)) {
blobContainer.writeBlob("write_blob_max_retries", stream, bytes.length, false);
}
assertThat(countDown.isCountedDown(), is(true));
}
public void testWriteBlobByStreamsWithRetries() throws Exception {
final int maxRetries = randomInt(5);
final CountDown countDown = new CountDown(maxRetries + 1);
final byte[] bytes = randomBlobContent();
httpServer.createContext("/bucket/write_blob_by_streams_max_retries", exchange -> {
if ("PUT".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery() == null) {
if (countDown.countDown()) {
final BytesReference body = Streams.readFully(exchange.getRequestBody());
if (Objects.deepEquals(bytes, BytesReference.toBytes(body))) {
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
} else {
exchange.sendResponseHeaders(HttpStatus.SC_BAD_REQUEST, -1);
}
exchange.close();
return;
}
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.max(1, bytes.length - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
}
exchange.close();
}
});
final VerifyingMultiStreamBlobContainer blobContainer = createBlobContainer(maxRetries, null, true, null);
List<InputStream> openInputStreams = new ArrayList<>();
CountDownLatch countDownLatch = new CountDownLatch(1);
AtomicReference<Exception> exceptionRef = new AtomicReference<>();
ActionListener<Void> completionListener = ActionListener.wrap(resp -> { countDownLatch.countDown(); }, ex -> {
exceptionRef.set(ex);
countDownLatch.countDown();
});
blobContainer.asyncBlobUpload(new WriteContext("write_blob_by_streams_max_retries", new StreamContextSupplier() {
@Override
public StreamContext supplyStreamContext(long partSize) {
return new StreamContext(new CheckedTriFunction<Integer, Long, Long, InputStreamContainer, IOException>() {
@Override
public InputStreamContainer apply(Integer partNo, Long size, Long position) throws IOException {
InputStream inputStream = new OffsetRangeIndexInputStream(new ByteArrayIndexInput("desc", bytes), size, position);
openInputStreams.add(inputStream);
return new InputStreamContainer(inputStream, size, position);
}
}, partSize, calculateLastPartSize(bytes.length, partSize), calculateNumberOfParts(bytes.length, partSize));
}
}, bytes.length, false, WritePriority.NORMAL, Assert::assertTrue, false, null), completionListener);
assertTrue(countDownLatch.await(5000, TimeUnit.SECONDS));
assertThat(countDown.isCountedDown(), is(true));
openInputStreams.forEach(inputStream -> {
try {
inputStream.close();
} catch (IOException e) {
fail("Failure while closing open input streams");
}
});
}
private long calculateLastPartSize(long totalSize, long partSize) {
return totalSize % partSize == 0 ? partSize : totalSize % partSize;
}
private int calculateNumberOfParts(long contentLength, long partSize) {
return (int) ((contentLength % partSize) == 0 ? contentLength / partSize : (contentLength / partSize) + 1);
}
public void testWriteBlobWithReadTimeouts() {
final byte[] bytes = randomByteArrayOfLength(randomIntBetween(10, 128));
final TimeValue readTimeout = TimeValue.timeValueMillis(randomIntBetween(100, 500));
final BlobContainer blobContainer = createBlobContainer(1, readTimeout, true, null);
// HTTP server does not send a response
httpServer.createContext("/bucket/write_blob_timeout", exchange -> {
if (randomBoolean()) {
if (randomBoolean()) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, bytes.length - 1)]);
} else {
Streams.readFully(exchange.getRequestBody());
}
}
});
Exception exception = expectThrows(IOException.class, () -> {
try (InputStream stream = new InputStreamIndexInput(new ByteArrayIndexInput("desc", bytes), bytes.length)) {
blobContainer.writeBlob("write_blob_timeout", stream, bytes.length, false);
}
});
assertThat(
exception.getMessage().toLowerCase(Locale.ROOT),
containsString("unable to upload object [write_blob_timeout] using a single upload")
);
assertThat(exception.getCause(), instanceOf(SdkClientException.class));
assertThat(exception.getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out"));
assertThat(exception.getCause().getCause(), instanceOf(SocketTimeoutException.class));
assertThat(exception.getCause().getCause().getMessage().toLowerCase(Locale.ROOT), containsString("read timed out"));
}
public void testWriteLargeBlob() throws Exception {
final boolean useTimeout = rarely();
final TimeValue readTimeout = useTimeout ? TimeValue.timeValueMillis(randomIntBetween(100, 500)) : null;
final ByteSizeValue bufferSize = new ByteSizeValue(5, ByteSizeUnit.MB);
final BlobContainer blobContainer = createBlobContainer(null, readTimeout, true, bufferSize);
final int parts = randomIntBetween(1, 5);
final long lastPartSize = randomLongBetween(10, 512);
final long blobSize = (parts * bufferSize.getBytes()) + lastPartSize;
final int nbErrors = 2; // we want all requests to fail at least once
final CountDown countDownInitiate = new CountDown(nbErrors);
final AtomicInteger countDownUploads = new AtomicInteger(nbErrors * (parts + 1));
final CountDown countDownComplete = new CountDown(nbErrors);
httpServer.createContext("/bucket/write_large_blob", exchange -> {
final long contentLength = Long.parseLong(exchange.getRequestHeaders().getFirst("Content-Length"));
if ("POST".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery().equals("uploads")) {
// initiate multipart upload request
if (countDownInitiate.countDown()) {
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<InitiateMultipartUploadResult>\n"
+ " <Bucket>bucket</Bucket>\n"
+ " <Key>write_large_blob</Key>\n"
+ " <UploadId>TEST</UploadId>\n"
+ "</InitiateMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(HttpStatus.SC_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
return;
}
} else if ("PUT".equals(exchange.getRequestMethod())
&& exchange.getRequestURI().getQuery().contains("uploadId=TEST")
&& exchange.getRequestURI().getQuery().contains("partNumber=")) {
// upload part request
SdkDigestInputStream digestInputStream = new SdkDigestInputStream(exchange.getRequestBody(), MessageDigests.md5());
BytesReference bytes = Streams.readFully(digestInputStream);
assertThat((long) bytes.length(), anyOf(equalTo(lastPartSize), equalTo(bufferSize.getBytes())));
assertThat(contentLength, anyOf(equalTo(lastPartSize), equalTo(bufferSize.getBytes())));
if (countDownUploads.decrementAndGet() % 2 == 0) {
exchange.getResponseHeaders().add("ETag", Base16.encodeAsString(digestInputStream.getMessageDigest().digest()));
exchange.sendResponseHeaders(HttpStatus.SC_OK, -1);
exchange.close();
return;
}
} else if ("POST".equals(exchange.getRequestMethod()) && exchange.getRequestURI().getQuery().equals("uploadId=TEST")) {
// complete multipart upload request
if (countDownComplete.countDown()) {
Streams.readFully(exchange.getRequestBody());
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<CompleteMultipartUploadResult>\n"
+ " <Bucket>bucket</Bucket>\n"
+ " <Key>write_large_blob</Key>\n"
+ "</CompleteMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(HttpStatus.SC_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
return;
}
}
// sends an error back or let the request time out
if (useTimeout == false) {
if (randomBoolean() && contentLength > 0) {
Streams.readFully(exchange.getRequestBody(), new byte[randomIntBetween(1, Math.toIntExact(contentLength - 1))]);
} else {
Streams.readFully(exchange.getRequestBody());
exchange.sendResponseHeaders(
randomFrom(
HttpStatus.SC_INTERNAL_SERVER_ERROR,
HttpStatus.SC_BAD_GATEWAY,
HttpStatus.SC_SERVICE_UNAVAILABLE,
HttpStatus.SC_GATEWAY_TIMEOUT
),
-1
);
}
exchange.close();
}
});
blobContainer.writeBlob("write_large_blob", new ZeroInputStream(blobSize), blobSize, false);
assertThat(countDownInitiate.isCountedDown(), is(true));
assertThat(countDownUploads.get(), equalTo(0));
assertThat(countDownComplete.isCountedDown(), is(true));
}
/**
* Asserts that an InputStream is fully consumed, or aborted, when it is closed
*/
private static class AssertingInputStream extends FilterInputStream {
private final String blobName;
private final boolean range;
private final long position;
private final long length;
AssertingInputStream(InputStream in, String blobName) {
super(in);
this.blobName = blobName;
this.position = 0L;
this.length = Long.MAX_VALUE;
this.range = false;
}
AssertingInputStream(InputStream in, String blobName, long position, long length) {
super(in);
this.blobName = blobName;
this.position = position;
this.length = length;
this.range = true;
}
@Override
public String toString() {
String description = "[blobName='" + blobName + "', range=" + range;
if (range) {
description += ", position=" + position;
description += ", length=" + length;
}
description += ']';
return description;
}
@Override
public void close() throws IOException {
super.close();
if (in instanceof S3RetryingInputStream) {
final S3RetryingInputStream s3Stream = (S3RetryingInputStream) in;
assertTrue(
"Stream "
+ toString()
+ " should have reached EOF or should have been aborted but got [eof="
+ s3Stream.isEof()
+ ", aborted="
+ s3Stream.isAborted()
+ ']',
s3Stream.isEof() || s3Stream.isAborted()
);
} else {
assertThat(in, instanceOf(ByteArrayInputStream.class));
assertThat(((ByteArrayInputStream) in).available(), equalTo(0));
}
}
}
}
| 25,890 | 0.631943 | 0.626883 | 550 | 46.072727 | 34.247948 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752727 | false | false | 2 |
32296c78f83ed2efe5f7d6742a21de5f22894d51 | 1,348,619,750,044 | 8fd0f9a0a29a0d1fa4e03342f8ba3bf5833b11dd | /FEOP/FEOPServer/FEOPServerBlog/src/main/java/org/personal/mason/feop/server/blog/domain/service/CategoryService.java | 9e7cf75a2cf8a9d269d60b3cf96d3f47f0283ca8 | []
| no_license | freeedu/service | https://github.com/freeedu/service | abaa772676e4d23684d3bedf7b8e32da164e1b22 | 56a758ddc45a1aaf369d18a730cd601d5fd33719 | refs/heads/master | 2016-09-06T12:43:42.516000 | 2014-01-26T18:22:03 | 2014-01-26T18:22:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.personal.mason.feop.server.blog.domain.service;
import org.personal.mason.feop.server.blog.domain.model.Category;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface CategoryService {
void save(Category category);
Category update(Category category);
List<Category> findByCategory(Category category);
List<Category> findByCategoryIsNull();
Page<Category> findByCategory(Category category, Pageable pageable);
Page<Category> findByCategoryIsNull(Pageable pageable);
void delete(Category category);
void delete(Long id);
Category findById(Long categoryId);
Category findByCategoryName(String categoryName);
}
| UTF-8 | Java | 753 | java | CategoryService.java | Java | []
| null | []
| package org.personal.mason.feop.server.blog.domain.service;
import org.personal.mason.feop.server.blog.domain.model.Category;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface CategoryService {
void save(Category category);
Category update(Category category);
List<Category> findByCategory(Category category);
List<Category> findByCategoryIsNull();
Page<Category> findByCategory(Category category, Pageable pageable);
Page<Category> findByCategoryIsNull(Pageable pageable);
void delete(Category category);
void delete(Long id);
Category findById(Long categoryId);
Category findByCategoryName(String categoryName);
}
| 753 | 0.774236 | 0.774236 | 30 | 24.1 | 24.62431 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 2 |
d949d12138591c90333898df2e1173b5ec3a0293 | 9,156,870,309,606 | b1417c3ac52e68a2c78a1daa73ced22e2fa989f8 | /app/src/main/java/ir/arashjahani/countrypedia/data/DataRepository.java | 9bc1d9444b0ffeef8747e84260baedc4d0c4e5c8 | []
| no_license | arash-jahani/CountryPedia | https://github.com/arash-jahani/CountryPedia | 68a00c0a3d5dc0ea625bcb9f669b9326c8d4fe5d | 515e518dd5ad84a63d9355172466079eefd3f6b9 | refs/heads/master | 2020-06-19T20:19:28.712000 | 2019-07-15T18:56:49 | 2019-07-15T18:56:49 | 196,857,463 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ir.arashjahani.countrypedia.data;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import ir.arashjahani.countrypedia.data.local.AppDatabase;
import ir.arashjahani.countrypedia.data.local.CountryDao;
import ir.arashjahani.countrypedia.data.model.ApiResponse;
import ir.arashjahani.countrypedia.data.model.Country;
import ir.arashjahani.countrypedia.data.model.Resource;
import ir.arashjahani.countrypedia.data.network.ApiService;
import ir.arashjahani.countrypedia.utils.AppExecutors;
import ir.arashjahani.countrypedia.data.utils.NetworkProvideResource;
import ir.arashjahani.countrypedia.data.utils.QueryStringConvertor;
/**
* Created By ArashJahani on 07/15
*/
@Singleton
public class DataRepository {
private ApiService mApiService;
private CountryDao mCountryDao;
private AppDatabase mAppDatabase;
private AppExecutors mAppExecutors;
private MutableLiveData<Boolean> countriesIsAvailable;
@Inject
DataRepository(ApiService apiService, CountryDao countryDao, AppDatabase appDatabase, AppExecutors appExecutors) {
mApiService = apiService;
mCountryDao = countryDao;
mAppDatabase = appDatabase;
mAppExecutors = appExecutors;
this.countriesIsAvailable = new MutableLiveData<>();
}
public LiveData<Resource<List<Country>>> getCountriesList(String... filters) {
return new NetworkProvideResource<List<Country>, List<Country>>(mAppExecutors) {
@Override
protected void saveCallResult(@NonNull List<Country> items) {
mCountryDao.insert(items);
}
@Override
protected boolean shouldFetch(@Nullable List<Country> data) {
return data == null || data.isEmpty();
}
@NonNull
@Override
protected LiveData<List<Country>> loadFromDb() {
return mCountryDao.getAll();
}
@NonNull
@Override
protected LiveData<ApiResponse<List<Country>>> createCall() {
return mApiService.getAllCountriesByFilter(QueryStringConvertor.toFields(filters));
}
}.asLiveData();
}
public MutableLiveData<Boolean> CountriesIsAvailable() {
mAppExecutors.diskIO().execute(new Runnable() {
@Override
public void run() {
if (mCountryDao.getRowSize().getValue()!=null && mCountryDao.getRowSize().getValue() > 0) {
countriesIsAvailable.postValue(true);
}
countriesIsAvailable.postValue(false);
}
});
return countriesIsAvailable;
}
}
| UTF-8 | Java | 2,866 | java | DataRepository.java | Java | [
{
"context": "ata.utils.QueryStringConvertor;\n\n/**\n * Created By ArashJahani on 07/15\n */\n@Singleton\npublic class DataReposito",
"end": 850,
"score": 0.999855637550354,
"start": 839,
"tag": "NAME",
"value": "ArashJahani"
}
]
| null | []
| package ir.arashjahani.countrypedia.data;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import ir.arashjahani.countrypedia.data.local.AppDatabase;
import ir.arashjahani.countrypedia.data.local.CountryDao;
import ir.arashjahani.countrypedia.data.model.ApiResponse;
import ir.arashjahani.countrypedia.data.model.Country;
import ir.arashjahani.countrypedia.data.model.Resource;
import ir.arashjahani.countrypedia.data.network.ApiService;
import ir.arashjahani.countrypedia.utils.AppExecutors;
import ir.arashjahani.countrypedia.data.utils.NetworkProvideResource;
import ir.arashjahani.countrypedia.data.utils.QueryStringConvertor;
/**
* Created By ArashJahani on 07/15
*/
@Singleton
public class DataRepository {
private ApiService mApiService;
private CountryDao mCountryDao;
private AppDatabase mAppDatabase;
private AppExecutors mAppExecutors;
private MutableLiveData<Boolean> countriesIsAvailable;
@Inject
DataRepository(ApiService apiService, CountryDao countryDao, AppDatabase appDatabase, AppExecutors appExecutors) {
mApiService = apiService;
mCountryDao = countryDao;
mAppDatabase = appDatabase;
mAppExecutors = appExecutors;
this.countriesIsAvailable = new MutableLiveData<>();
}
public LiveData<Resource<List<Country>>> getCountriesList(String... filters) {
return new NetworkProvideResource<List<Country>, List<Country>>(mAppExecutors) {
@Override
protected void saveCallResult(@NonNull List<Country> items) {
mCountryDao.insert(items);
}
@Override
protected boolean shouldFetch(@Nullable List<Country> data) {
return data == null || data.isEmpty();
}
@NonNull
@Override
protected LiveData<List<Country>> loadFromDb() {
return mCountryDao.getAll();
}
@NonNull
@Override
protected LiveData<ApiResponse<List<Country>>> createCall() {
return mApiService.getAllCountriesByFilter(QueryStringConvertor.toFields(filters));
}
}.asLiveData();
}
public MutableLiveData<Boolean> CountriesIsAvailable() {
mAppExecutors.diskIO().execute(new Runnable() {
@Override
public void run() {
if (mCountryDao.getRowSize().getValue()!=null && mCountryDao.getRowSize().getValue() > 0) {
countriesIsAvailable.postValue(true);
}
countriesIsAvailable.postValue(false);
}
});
return countriesIsAvailable;
}
}
| 2,866 | 0.680042 | 0.678297 | 92 | 30.152174 | 28.032564 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 2 |
155f8e3e2a2eac1d22ff73994704c968e16f6422 | 22,179,211,164,758 | b147bd24d814c3bbb11cd756b6effd22670dd27d | /src/main/java/com/_520/crowdfunding/mapper/TParamMapper.java | 1b7508263e3fe04dd416bcecc80d9eb4b7c4ab97 | []
| no_license | Werdio66/crowdfunding | https://github.com/Werdio66/crowdfunding | d089a13836eba7d754f606f6fe4766ff71b9d512 | 7468ad39a09473ad98e440893888dbe8af6b80ef | refs/heads/master | 2022-12-21T16:01:25.840000 | 2020-01-15T08:40:05 | 2020-01-15T08:40:05 | 232,767,418 | 0 | 0 | null | false | 2022-12-16T05:08:56 | 2020-01-09T09:07:04 | 2020-01-15T09:13:15 | 2022-12-16T05:08:55 | 5,114 | 0 | 0 | 13 | JavaScript | false | false | package com._520.crowdfunding.mapper;
import com._520.crowdfunding.domain.TParam;
import com._520.crowdfunding.domain.TParamExample;
import com._520.crowdfunding.domain.TParamKey;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TParamMapper {
long countByExample(TParamExample example);
int deleteByExample(TParamExample example);
int deleteByPrimaryKey(TParamKey key);
int insert(TParam record);
int insertSelective(TParam record);
List<TParam> selectByExample(TParamExample example);
TParam selectByPrimaryKey(TParamKey key);
int updateByExampleSelective(@Param("record") TParam record, @Param("example") TParamExample example);
int updateByExample(@Param("record") TParam record, @Param("example") TParamExample example);
int updateByPrimaryKeySelective(TParam record);
int updateByPrimaryKey(TParam record);
} | UTF-8 | Java | 905 | java | TParamMapper.java | Java | []
| null | []
| package com._520.crowdfunding.mapper;
import com._520.crowdfunding.domain.TParam;
import com._520.crowdfunding.domain.TParamExample;
import com._520.crowdfunding.domain.TParamKey;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TParamMapper {
long countByExample(TParamExample example);
int deleteByExample(TParamExample example);
int deleteByPrimaryKey(TParamKey key);
int insert(TParam record);
int insertSelective(TParam record);
List<TParam> selectByExample(TParamExample example);
TParam selectByPrimaryKey(TParamKey key);
int updateByExampleSelective(@Param("record") TParam record, @Param("example") TParamExample example);
int updateByExample(@Param("record") TParam record, @Param("example") TParamExample example);
int updateByPrimaryKeySelective(TParam record);
int updateByPrimaryKey(TParam record);
} | 905 | 0.775691 | 0.762431 | 31 | 28.225807 | 28.514523 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 2 |
c8d5f3864afdf6dbb98d42c1231c3484b5bde5b9 | 31,550,829,819,826 | 337ee652dbaf03efc2919bbfad7b3c20272bd898 | /awe-framework/awe-modules/awe-builder/src/main/java/com/almis/awe/builder/client/grid/CopyRowActionBuilder.java | a52f88571fcb95084ca64b18eb481b07135472cf | [
"Apache-2.0"
]
| permissive | java-tools/awe | https://github.com/java-tools/awe | 58db90443b17fb9c7c1f2d124b12c842830790f0 | 30618df0a6f940284851d2a988317eaf3c546186 | refs/heads/master | 2023-03-24T07:55:16.883000 | 2021-02-02T16:04:40 | 2021-02-02T16:04:40 | 345,120,415 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.almis.awe.builder.client.grid;
import com.almis.awe.builder.enumerates.RowPosition;
/**
* Copy rows action builder
*
* @author pgarcia
*/
public class CopyRowActionBuilder extends RowsActionBuilder<CopyRowActionBuilder> {
private static final String TYPE = "copy-row";
/**
* Empty constructor
*/
public CopyRowActionBuilder() {
super(TYPE, RowPosition.BOTTOM);
}
/**
* Add row with position builder
*/
public CopyRowActionBuilder(RowPosition position) {
super(TYPE, position);
}
/**
* Constructor with target
*
* @param position Row position
* @param target Target
*/
public CopyRowActionBuilder(RowPosition position, String target) {
super(TYPE, position, target);
}
/**
* Constructor with target and selected row
*
* @param position Row position
* @param target Target
* @param rowId Selected row to copy
*/
public CopyRowActionBuilder(RowPosition position, String target, String rowId) {
super(TYPE, position, target);
addParameter("selectedRow", rowId);
}
}
| UTF-8 | Java | 1,077 | java | CopyRowActionBuilder.java | Java | [
{
"context": "on;\n\n/**\n * Copy rows action builder\n *\n * @author pgarcia\n */\npublic class CopyRowActionBuilder extends Row",
"end": 151,
"score": 0.998670756816864,
"start": 144,
"tag": "USERNAME",
"value": "pgarcia"
}
]
| null | []
| package com.almis.awe.builder.client.grid;
import com.almis.awe.builder.enumerates.RowPosition;
/**
* Copy rows action builder
*
* @author pgarcia
*/
public class CopyRowActionBuilder extends RowsActionBuilder<CopyRowActionBuilder> {
private static final String TYPE = "copy-row";
/**
* Empty constructor
*/
public CopyRowActionBuilder() {
super(TYPE, RowPosition.BOTTOM);
}
/**
* Add row with position builder
*/
public CopyRowActionBuilder(RowPosition position) {
super(TYPE, position);
}
/**
* Constructor with target
*
* @param position Row position
* @param target Target
*/
public CopyRowActionBuilder(RowPosition position, String target) {
super(TYPE, position, target);
}
/**
* Constructor with target and selected row
*
* @param position Row position
* @param target Target
* @param rowId Selected row to copy
*/
public CopyRowActionBuilder(RowPosition position, String target, String rowId) {
super(TYPE, position, target);
addParameter("selectedRow", rowId);
}
}
| 1,077 | 0.689879 | 0.689879 | 50 | 20.540001 | 22.037432 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 2 |
142c35aa002ade7e44bd6be55978e1aead84aacf | 33,036,888,491,465 | 7cd312ad849456674e709073fa9eab007c4f6254 | /Week_02/G20190343020032/LeetCode_589_0032.java | 81d364e161e2b9f5a5a382a48e0d53d1bec7bf8f | []
| no_license | algorithm005-class01/algorithm005-class01 | https://github.com/algorithm005-class01/algorithm005-class01 | aa7b604fe95f5c795291cf382170b0e3a102f8d3 | 2b7f4a9fefbfd358f8ff31362d60e2007641ca29 | refs/heads/master | 2020-09-22T11:35:18.725000 | 2020-03-02T03:22:31 | 2020-03-02T03:22:31 | 225,175,371 | 27 | 153 | null | false | 2020-03-02T03:22:32 | 2019-12-01T14:31:06 | 2020-03-02T03:18:02 | 2020-03-02T03:22:32 | 113,143 | 19 | 145 | 650 | Java | false | false | class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorder(Node root) {
helper(root);
return list;
}
private void helper(Node root) {
if (root == null) {
return;
}
list.add(root.val);
int size = root.children.size();
for (int i = 0; i < size; i++) {
helper(root.children.get(i));
}
}
public List<Integer> preorder2(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node removedNode = stack.pop();
list.add(removedNode.val);
if (removedNode.children != null && removedNode.children.size() > 0) {
for (int i = removedNode.children.size() - 1; i >= 0; i--) {
stack.push(removedNode.children.get(i));
}
}
}
return list;
}
} | UTF-8 | Java | 1,060 | java | LeetCode_589_0032.java | Java | []
| null | []
| class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorder(Node root) {
helper(root);
return list;
}
private void helper(Node root) {
if (root == null) {
return;
}
list.add(root.val);
int size = root.children.size();
for (int i = 0; i < size; i++) {
helper(root.children.get(i));
}
}
public List<Integer> preorder2(Node root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node removedNode = stack.pop();
list.add(removedNode.val);
if (removedNode.children != null && removedNode.children.size() > 0) {
for (int i = removedNode.children.size() - 1; i >= 0; i--) {
stack.push(removedNode.children.get(i));
}
}
}
return list;
}
} | 1,060 | 0.480189 | 0.475472 | 38 | 26.921053 | 20.155163 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 2 |
4bf1240f04e0ec380cb6804c1b3f2c10a1103176 | 10,737,418,274,310 | 680c4453d7572e5708e3d3358ba4bf56cee2d1a3 | /zhiwang123/app/src/main/java/com/zhiwang123/mobile/phone/adapter/LocalListAdapter.java | 67aed08684da69eaaec785bf67c5ccad1b7faf25 | []
| no_license | zhangheng08/zw | https://github.com/zhangheng08/zw | 625fe5ed78fe848536beb238e3a52596d78e616e | cf4761a1057a40125464dc08cbfe63b0ebbd9cfd | refs/heads/master | 2021-06-21T13:14:26.931000 | 2017-08-17T17:08:41 | 2017-08-17T17:08:41 | 100,437,789 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhiwang123.mobile.phone.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.zhiwang123.mobile.R;
import com.zhiwang123.mobile.phone.activity.LocalVideoListActivity;
import com.zhiwang123.mobile.phone.activity.OffLineListActivity;
import com.zhiwang123.mobile.phone.activity.VideoPlayActivity;
import com.zhiwang123.mobile.phone.bean.LocalVideo;
import com.zhiwang123.mobile.phone.db.AsyncDBHelper;
import com.zhiwang123.mobile.phone.widget.listview.XRestrictListView;
import com.zhiwang123.mobile.phone.widget.listview.XRestrictSideSlipCell;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
/**
* Created by ty on 2016/6/22.
*/
public class LocalListAdapter extends BaseZwAdapter {
private static final String TAG = "OfflineListAdapter";
private Activity mContext;
private LayoutInflater mInflater;
private ArrayList<LocalVideo> mOfflineDataList;
private View mLoadDirItem;
private XRestrictListView mHostListView;
public boolean isExpandAll = false;
public LocalListAdapter(Activity c) {
super(c);
mContext = c;
mInflater = LayoutInflater.from(c);
mLoadDirItem = mInflater.inflate(R.layout.offline_list_item_loading, null);
}
public LocalListAdapter(Activity c, ArrayList<LocalVideo> list, XRestrictListView hostlistView) {
this(c);
mOfflineDataList = list;
mHostListView = hostlistView;
}
public void addDataList(ArrayList<LocalVideo> dataList) {
if(mOfflineDataList == null) mOfflineDataList = new ArrayList<>();
mOfflineDataList.addAll(dataList);
}
public void setDataList(ArrayList<LocalVideo> dataList) {
if(mOfflineDataList != null) mOfflineDataList.clear();
else mOfflineDataList = new ArrayList<>();
mOfflineDataList.addAll(dataList);
}
@Override
public int getCount() {
return mOfflineDataList.size();
}
@Override
public LocalVideo getItem(int position) {
return mOfflineDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return mOfflineDataList.get(position).type;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
LocalVideo lv = mOfflineDataList.get(position);
if(LocalVideo.DIR == type) {
TextView tx = (TextView) mLoadDirItem.findViewById(R.id.offline_loading_sub_title);
tx.setText(mContext.getString(R.string.offline_loading_num, lv.taskNum));
convertView = mLoadDirItem;
convertView.setTag(new Integer(0x0));
convertView.setOnClickListener(onClickListener);
} else if(LocalVideo.FIL == type) {
CellHolder holder = null;
View contentView = null;
if(convertView == null || convertView.getTag() instanceof Integer) {
contentView = mContext.getLayoutInflater().inflate(R.layout.offline_local_list_item, null);
convertView = mContext.getLayoutInflater().inflate(R.layout.zh_list_item_layout, null);
((ViewGroup)convertView.findViewById(R.id.content_layer)).addView(contentView);
holder = new CellHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CellHolder) convertView.getTag();
}
holder.mVideo = lv;
holder.titleTv.setText(lv.title);
DecimalFormat df = new DecimalFormat("#.0");
Double size = (lv.currentBits / 1024.0) / 1024.0;
holder.subTv.setText(df.format(size) + "MB");
// holder.imageView.setImageBitmap(lv.fileImg);
Glide.with(mContext).load(Uri.fromFile( new File( lv.filePath ) )).crossFade().into(holder.imageView);
}
return convertView;
}
private class CellHolder implements XRestrictSideSlipCell.Callback {
public LocalVideo mVideo;
public TextView titleTv;
public TextView subTv;
public ImageView imageView;
public XRestrictSideSlipCell scrollContainer;
public TextView mDeleteTriggerView;
public CellHolder(View cellView) {
titleTv = (TextView) cellView.findViewById(R.id.local_item_title);
subTv = (TextView) cellView.findViewById(R.id.local_item_sub_title);
imageView = (ImageView) cellView.findViewById(R.id.local_item_left_img);
scrollContainer = (XRestrictSideSlipCell) cellView.findViewById(R.id.scroll_container);
mDeleteTriggerView = (TextView) cellView.findViewById(R.id.click_event_trigger);
scrollContainer.setListView(mHostListView);
scrollContainer.setCallback(this);
scrollContainer.notifyLayerState(isExpandAll);
}
@Override
public void delete(Context context) {
AsyncDBHelper.deleteVideoCacheDB(mContext, mVideo, null);
mOfflineDataList.remove(mVideo);
notifyDataSetChanged();
}
@Override
public void expand(boolean isExpand) {
}
@Override
public void clickEvent() {
Intent intent = new Intent(mContext, VideoPlayActivity.class);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VNAME, mVideo.title);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VIMG, mVideo.cover);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VID, mVideo.videoId);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_LOCPLY, true);
mContext.startActivity(intent);
}
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getTag() instanceof Integer) {
Intent intent = new Intent(mContext, OffLineListActivity.class);
mContext.startActivityForResult(intent, LocalVideoListActivity.REQUEST_CODE_FOR_REFRESH);
}
}
};
}
| UTF-8 | Java | 6,488 | java | LocalListAdapter.java | Java | []
| null | []
| package com.zhiwang123.mobile.phone.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.zhiwang123.mobile.R;
import com.zhiwang123.mobile.phone.activity.LocalVideoListActivity;
import com.zhiwang123.mobile.phone.activity.OffLineListActivity;
import com.zhiwang123.mobile.phone.activity.VideoPlayActivity;
import com.zhiwang123.mobile.phone.bean.LocalVideo;
import com.zhiwang123.mobile.phone.db.AsyncDBHelper;
import com.zhiwang123.mobile.phone.widget.listview.XRestrictListView;
import com.zhiwang123.mobile.phone.widget.listview.XRestrictSideSlipCell;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
/**
* Created by ty on 2016/6/22.
*/
public class LocalListAdapter extends BaseZwAdapter {
private static final String TAG = "OfflineListAdapter";
private Activity mContext;
private LayoutInflater mInflater;
private ArrayList<LocalVideo> mOfflineDataList;
private View mLoadDirItem;
private XRestrictListView mHostListView;
public boolean isExpandAll = false;
public LocalListAdapter(Activity c) {
super(c);
mContext = c;
mInflater = LayoutInflater.from(c);
mLoadDirItem = mInflater.inflate(R.layout.offline_list_item_loading, null);
}
public LocalListAdapter(Activity c, ArrayList<LocalVideo> list, XRestrictListView hostlistView) {
this(c);
mOfflineDataList = list;
mHostListView = hostlistView;
}
public void addDataList(ArrayList<LocalVideo> dataList) {
if(mOfflineDataList == null) mOfflineDataList = new ArrayList<>();
mOfflineDataList.addAll(dataList);
}
public void setDataList(ArrayList<LocalVideo> dataList) {
if(mOfflineDataList != null) mOfflineDataList.clear();
else mOfflineDataList = new ArrayList<>();
mOfflineDataList.addAll(dataList);
}
@Override
public int getCount() {
return mOfflineDataList.size();
}
@Override
public LocalVideo getItem(int position) {
return mOfflineDataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return mOfflineDataList.get(position).type;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
LocalVideo lv = mOfflineDataList.get(position);
if(LocalVideo.DIR == type) {
TextView tx = (TextView) mLoadDirItem.findViewById(R.id.offline_loading_sub_title);
tx.setText(mContext.getString(R.string.offline_loading_num, lv.taskNum));
convertView = mLoadDirItem;
convertView.setTag(new Integer(0x0));
convertView.setOnClickListener(onClickListener);
} else if(LocalVideo.FIL == type) {
CellHolder holder = null;
View contentView = null;
if(convertView == null || convertView.getTag() instanceof Integer) {
contentView = mContext.getLayoutInflater().inflate(R.layout.offline_local_list_item, null);
convertView = mContext.getLayoutInflater().inflate(R.layout.zh_list_item_layout, null);
((ViewGroup)convertView.findViewById(R.id.content_layer)).addView(contentView);
holder = new CellHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CellHolder) convertView.getTag();
}
holder.mVideo = lv;
holder.titleTv.setText(lv.title);
DecimalFormat df = new DecimalFormat("#.0");
Double size = (lv.currentBits / 1024.0) / 1024.0;
holder.subTv.setText(df.format(size) + "MB");
// holder.imageView.setImageBitmap(lv.fileImg);
Glide.with(mContext).load(Uri.fromFile( new File( lv.filePath ) )).crossFade().into(holder.imageView);
}
return convertView;
}
private class CellHolder implements XRestrictSideSlipCell.Callback {
public LocalVideo mVideo;
public TextView titleTv;
public TextView subTv;
public ImageView imageView;
public XRestrictSideSlipCell scrollContainer;
public TextView mDeleteTriggerView;
public CellHolder(View cellView) {
titleTv = (TextView) cellView.findViewById(R.id.local_item_title);
subTv = (TextView) cellView.findViewById(R.id.local_item_sub_title);
imageView = (ImageView) cellView.findViewById(R.id.local_item_left_img);
scrollContainer = (XRestrictSideSlipCell) cellView.findViewById(R.id.scroll_container);
mDeleteTriggerView = (TextView) cellView.findViewById(R.id.click_event_trigger);
scrollContainer.setListView(mHostListView);
scrollContainer.setCallback(this);
scrollContainer.notifyLayerState(isExpandAll);
}
@Override
public void delete(Context context) {
AsyncDBHelper.deleteVideoCacheDB(mContext, mVideo, null);
mOfflineDataList.remove(mVideo);
notifyDataSetChanged();
}
@Override
public void expand(boolean isExpand) {
}
@Override
public void clickEvent() {
Intent intent = new Intent(mContext, VideoPlayActivity.class);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VNAME, mVideo.title);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VIMG, mVideo.cover);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_VID, mVideo.videoId);
intent.putExtra(VideoPlayActivity.EXTRA_KEY_LOCPLY, true);
mContext.startActivity(intent);
}
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.getTag() instanceof Integer) {
Intent intent = new Intent(mContext, OffLineListActivity.class);
mContext.startActivityForResult(intent, LocalVideoListActivity.REQUEST_CODE_FOR_REFRESH);
}
}
};
}
| 6,488 | 0.669081 | 0.661837 | 214 | 29.317757 | 29.522713 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528037 | false | false | 2 |
fbfe2c132ad0db9974f8eb7bb82d4a4449a34f3b | 6,055,903,927,517 | 6fbbfa4b889e9a44bdffdbf01ee5aaf84202a05a | /bse/bse-baseinfo-api/src/main/java/com/deppon/foss/module/base/baseinfo/api/shared/vo/JobGridVo.java | 3577a57f14fec9a4d8d61ff2f82cd491ed45c355 | []
| no_license | moutainhigh/foss | https://github.com/moutainhigh/foss | d98436816181ef038a9b8b983bb42df36cfe617c | 5b1d46b3a25f29ae9906abc536dfb436f65fde04 | refs/heads/master | 2021-06-15T15:40:42.782000 | 2017-05-04T13:47:43 | 2017-05-04T13:47:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.deppon.foss.module.base.baseinfo.api.shared.vo;
import java.io.Serializable;
import java.util.List;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridClusterEntity;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridLoggingsEntity;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridSchedulesEntity;
public class JobGridVo implements Serializable {
private static final long serialVersionUID = 8406555223816776082L;
private String selectorParam;
private List<JobGridSchedulesEntity> jobGridSchedulesEntityList;
private JobGridClusterEntity jobGridClusterEntity;/**任务分组**/
private List<JobGridLoggingsEntity> jobGridLoggingsEntityList;
private List<JobGridClusterEntity> JobGridClusterEntityList;
private String active;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
private JobGridSchedulesEntity jobGridSchedulesEntity = new JobGridSchedulesEntity();
private JobGridLoggingsEntity jobGridLoggingsEntity = new JobGridLoggingsEntity();
public List<JobGridSchedulesEntity> getJobGridSchedulesEntityList() {
return jobGridSchedulesEntityList;
}
public void setJobGridSchedulesEntityList(
List<JobGridSchedulesEntity> jobGridSchedulesEntityList) {
this.jobGridSchedulesEntityList = jobGridSchedulesEntityList;
}
public List<JobGridLoggingsEntity> getJobGridLoggingsEntityList() {
return jobGridLoggingsEntityList;
}
public void setJobGridLoggingsEntityList(
List<JobGridLoggingsEntity> jobGridLoggingsEntityList) {
this.jobGridLoggingsEntityList = jobGridLoggingsEntityList;
}
public JobGridSchedulesEntity getJobGridSchedulesEntity() {
return jobGridSchedulesEntity;
}
public void setJobGridSchedulesEntity(
JobGridSchedulesEntity jobGridSchedulesEntity) {
this.jobGridSchedulesEntity = jobGridSchedulesEntity;
}
public JobGridLoggingsEntity getJobGridLoggingsEntity() {
return jobGridLoggingsEntity;
}
public String getSelectorParam() {
return selectorParam;
}
public void setSelectorParam(String selectorParam) {
this.selectorParam = selectorParam;
}
public List<JobGridClusterEntity> getJobGridClusterEntityList() {
return JobGridClusterEntityList;
}
public void setJobGridClusterEntityList(
List<JobGridClusterEntity> jobGridClusterEntityList) {
JobGridClusterEntityList = jobGridClusterEntityList;
}
public JobGridClusterEntity getJobGridClusterEntity() {
return jobGridClusterEntity;
}
public void setJobGridClusterEntity(JobGridClusterEntity jobGridClusterEntity) {
this.jobGridClusterEntity = jobGridClusterEntity;
}
public void setJobGridLoggingsEntity(JobGridLoggingsEntity jobGridLoggingsEntity) {
this.jobGridLoggingsEntity = jobGridLoggingsEntity;
}
}
| UTF-8 | Java | 2,815 | java | JobGridVo.java | Java | []
| null | []
| package com.deppon.foss.module.base.baseinfo.api.shared.vo;
import java.io.Serializable;
import java.util.List;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridClusterEntity;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridLoggingsEntity;
import com.deppon.foss.module.base.baseinfo.api.shared.domain.JobGridSchedulesEntity;
public class JobGridVo implements Serializable {
private static final long serialVersionUID = 8406555223816776082L;
private String selectorParam;
private List<JobGridSchedulesEntity> jobGridSchedulesEntityList;
private JobGridClusterEntity jobGridClusterEntity;/**任务分组**/
private List<JobGridLoggingsEntity> jobGridLoggingsEntityList;
private List<JobGridClusterEntity> JobGridClusterEntityList;
private String active;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
private JobGridSchedulesEntity jobGridSchedulesEntity = new JobGridSchedulesEntity();
private JobGridLoggingsEntity jobGridLoggingsEntity = new JobGridLoggingsEntity();
public List<JobGridSchedulesEntity> getJobGridSchedulesEntityList() {
return jobGridSchedulesEntityList;
}
public void setJobGridSchedulesEntityList(
List<JobGridSchedulesEntity> jobGridSchedulesEntityList) {
this.jobGridSchedulesEntityList = jobGridSchedulesEntityList;
}
public List<JobGridLoggingsEntity> getJobGridLoggingsEntityList() {
return jobGridLoggingsEntityList;
}
public void setJobGridLoggingsEntityList(
List<JobGridLoggingsEntity> jobGridLoggingsEntityList) {
this.jobGridLoggingsEntityList = jobGridLoggingsEntityList;
}
public JobGridSchedulesEntity getJobGridSchedulesEntity() {
return jobGridSchedulesEntity;
}
public void setJobGridSchedulesEntity(
JobGridSchedulesEntity jobGridSchedulesEntity) {
this.jobGridSchedulesEntity = jobGridSchedulesEntity;
}
public JobGridLoggingsEntity getJobGridLoggingsEntity() {
return jobGridLoggingsEntity;
}
public String getSelectorParam() {
return selectorParam;
}
public void setSelectorParam(String selectorParam) {
this.selectorParam = selectorParam;
}
public List<JobGridClusterEntity> getJobGridClusterEntityList() {
return JobGridClusterEntityList;
}
public void setJobGridClusterEntityList(
List<JobGridClusterEntity> jobGridClusterEntityList) {
JobGridClusterEntityList = jobGridClusterEntityList;
}
public JobGridClusterEntity getJobGridClusterEntity() {
return jobGridClusterEntity;
}
public void setJobGridClusterEntity(JobGridClusterEntity jobGridClusterEntity) {
this.jobGridClusterEntity = jobGridClusterEntity;
}
public void setJobGridLoggingsEntity(JobGridLoggingsEntity jobGridLoggingsEntity) {
this.jobGridLoggingsEntity = jobGridLoggingsEntity;
}
}
| 2,815 | 0.826505 | 0.819736 | 92 | 29.51087 | 28.858536 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.271739 | false | false | 2 |
722ac51b3a3efbc482bd95dbcef3a89e0e9461ff | 13,821,204,789,569 | a78d891e7050e39d7f1f60f2e7fa4fb5bdcf6d26 | /Aula2/src/Novo.java | 2b34097e2808b5588998bca274930b88285acce4 | []
| no_license | leosk52/INE5404 | https://github.com/leosk52/INE5404 | 019b8bdb85e74d852d7aa0d0e8d97fa735ca9feb | 6caf9a319997ca651e345958a2f072051e8d82a6 | refs/heads/master | 2021-04-03T07:01:22.264000 | 2018-05-23T00:36:54 | 2018-05-23T00:36:54 | 123,607,667 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Novo extends Imovel {
double adicional=20000;
public void valorNovo() {
System.out.println(adicional + preco);
}
public double getAdicional() {
return adicional;
}
public void setAdicional(double adicional) {
this.adicional = adicional;
}
}
| UTF-8 | Java | 282 | java | Novo.java | Java | []
| null | []
|
public class Novo extends Imovel {
double adicional=20000;
public void valorNovo() {
System.out.println(adicional + preco);
}
public double getAdicional() {
return adicional;
}
public void setAdicional(double adicional) {
this.adicional = adicional;
}
}
| 282 | 0.691489 | 0.673759 | 20 | 13.05 | 15.634817 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1 | false | false | 2 |
73935543b862ec6766c27f3555e0aa1c8b8bd399 | 13,821,204,789,591 | 5ea4a1d99f92ee8b81c94b3175220be1ceebbc12 | /app/src/main/java/com/hellowo/myclass/AppDateFormat.java | c2d278bac5629f1c7046703993583c81a7d314b7 | []
| no_license | KyeonghunSeo/MyClass | https://github.com/KyeonghunSeo/MyClass | 0006480495a6027f459324e45bca15bb092ef3d7 | c5d00ffce5517b4f5495eaf2e77e67b621f108de | refs/heads/master | 2021-01-22T19:04:29.531000 | 2017-04-06T00:33:21 | 2017-04-06T00:33:21 | 85,156,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hellowo.myclass;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class AppDateFormat {
public static DateFormat ym;
public static DateFormat mdeDate;
public static DateFormat time;
public static DateFormat ymdkey;
public static DateFormat smallmdeDate;
public static void init(App app) {
ym = new SimpleDateFormat("yyyy년 M월");
mdeDate = new SimpleDateFormat("M월 d일 E요일");
time = new SimpleDateFormat("a hh:mm");
ymdkey = new SimpleDateFormat("yyyyMMdd");
smallmdeDate = new SimpleDateFormat("M. d. E");
}
}
| UTF-8 | Java | 625 | java | AppDateFormat.java | Java | []
| null | []
| package com.hellowo.myclass;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class AppDateFormat {
public static DateFormat ym;
public static DateFormat mdeDate;
public static DateFormat time;
public static DateFormat ymdkey;
public static DateFormat smallmdeDate;
public static void init(App app) {
ym = new SimpleDateFormat("yyyy년 M월");
mdeDate = new SimpleDateFormat("M월 d일 E요일");
time = new SimpleDateFormat("a hh:mm");
ymdkey = new SimpleDateFormat("yyyyMMdd");
smallmdeDate = new SimpleDateFormat("M. d. E");
}
}
| 625 | 0.693312 | 0.693312 | 20 | 29.65 | 18.108768 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 2 |
a1756a96d4c3248e8a9c1717a58a34f3ca3d3f10 | 8,538,394,998,768 | 384cb2c475e56a8dd752e04e1cbb1ae63452d571 | /src/main/java/com/wi/bean/DataBean.java | 78659393e823869b7861566a598377cbd3447add | []
| no_license | EugineE/WeekEndIdeas | https://github.com/EugineE/WeekEndIdeas | ba301a1de8e406118e6b700c572a5dfdedb12658 | 1167468d18f4a6467237f23fc4d585137a0f0e4e | refs/heads/master | 2023-06-15T03:55:36.927000 | 2021-07-10T14:10:05 | 2021-07-10T14:10:05 | 380,663,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //$Id$
package com.wi.bean;
public interface DataBean {
}
| UTF-8 | Java | 60 | java | DataBean.java | Java | []
| null | []
| //$Id$
package com.wi.bean;
public interface DataBean {
}
| 60 | 0.683333 | 0.683333 | 6 | 9 | 10.645813 | 27 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 2 |
29211142198026ab3cf1c0e3af65cc3408aab731 | 2,388,001,878,274 | f8734d8eb2cfd95884e66ecd26404784bf6e4f11 | /leetcode/src/test/java/tao/data/structure/simple/string/longest/palindromic/string/SolutionTest.java | 3f056379b73646f043553e7ccc9eb67b8f4f24a1 | []
| no_license | nicolas2lee/interview-prepartion | https://github.com/nicolas2lee/interview-prepartion | 01bd217014c78075d8777317d3dc617f3c0af41e | b6a8baacc40c1d9fe2fa206336b4e5bef11932e0 | refs/heads/master | 2021-07-19T21:43:31.764000 | 2020-09-15T13:58:27 | 2020-09-15T13:58:27 | 210,211,817 | 0 | 0 | null | false | 2020-10-14T00:28:57 | 2019-09-22T20:45:00 | 2020-09-15T13:59:00 | 2020-10-14T00:28:56 | 406 | 0 | 0 | 3 | Java | false | false | package tao.data.structure.simple.string.longest.palindromic.string;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class SolutionTest {
private Solution solution;
@Before
public void setUp() throws Exception {
solution = new Solution();
}
@Test
public void case_odd() {
final String result = solution.longestPalindrome("babad");
assertThat(result).isEqualTo("bab");
}
@Test
public void case_even() {
final String result = solution.longestPalindrome("cbbd");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_even2() {
final String result = solution.longestPalindrome("bb");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_even3() {
final String result = solution.longestPalindrome("abb");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_empty() {
final String result = solution.longestPalindrome("");
assertThat(result).isEqualTo("");
}
} | UTF-8 | Java | 1,137 | java | SolutionTest.java | Java | []
| null | []
| package tao.data.structure.simple.string.longest.palindromic.string;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class SolutionTest {
private Solution solution;
@Before
public void setUp() throws Exception {
solution = new Solution();
}
@Test
public void case_odd() {
final String result = solution.longestPalindrome("babad");
assertThat(result).isEqualTo("bab");
}
@Test
public void case_even() {
final String result = solution.longestPalindrome("cbbd");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_even2() {
final String result = solution.longestPalindrome("bb");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_even3() {
final String result = solution.longestPalindrome("abb");
assertThat(result).isEqualTo("bb");
}
@Test
public void case_empty() {
final String result = solution.longestPalindrome("");
assertThat(result).isEqualTo("");
}
} | 1,137 | 0.645558 | 0.643799 | 50 | 21.76 | 23.050865 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false | 2 |
de06711162fc4de05d6bb4cc1590680ecbecfdd2 | 15,264,313,801,172 | ac37264b59df810b6edd2d765093116315784d2a | /mvdXMLCheckerCore1underscore1/src/main/java/generated/mvdxml1underscore1/rule_operators/MvdXMLv1_1Parser.java | 7375d3e69f7030a05ad5b66054a2a13c60ed5520 | []
| no_license | jyrkioraskari/mvdXMLChecker | https://github.com/jyrkioraskari/mvdXMLChecker | 660d2014c833cea8b7c8ca9061b79d9515d6d265 | fa417fdd92e39c00b78f60dc2d428157ede3c142 | refs/heads/master | 2023-07-22T18:43:20.170000 | 2022-06-07T23:37:08 | 2022-06-07T23:37:08 | 241,197,708 | 6 | 3 | null | false | 2023-07-07T21:54:04 | 2020-02-17T20:08:28 | 2022-09-22T02:24:14 | 2023-07-07T21:54:03 | 172,077 | 7 | 4 | 3 | Java | false | false | // $ANTLR 3.5.2 MvdXMLv1_1.g 2020-05-05 16:37:25
package generated.mvdxml1underscore1.rule_operators;
import java.util.HashMap;
import org.antlr.runtime.BitSet;
import org.antlr.runtime.MismatchedSetException;
import org.antlr.runtime.NoViableAltException;
import org.antlr.runtime.Parser;
import org.antlr.runtime.ParserRuleReturnScope;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.RecognizerSharedState;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenStream;
import org.buildingsmart_tech.mvdxml.mvdxml1_1.AbstractRule;
import nl.tue.ddss.ifc_check.IfcHashMapBuilder.ObjectToValue;
import nl.tue.ddss.ifc_check.Metric;
import nl.tue.ddss.ifc_check.Parameter;
import nl.tue.ddss.rule_parse.AndOperator;
import nl.tue.ddss.rule_parse.EqualOperator;
import nl.tue.ddss.rule_parse.GreaterEqualOperator;
import nl.tue.ddss.rule_parse.GreaterOperator;
import nl.tue.ddss.rule_parse.InEqualOperator;
import nl.tue.ddss.rule_parse.LessEqualOperator;
import nl.tue.ddss.rule_parse.LessOperator;
import nl.tue.ddss.rule_parse.OrOperator;
import nl.tue.ddss.rule_parse.XorOperator;
@SuppressWarnings("all")
public class MvdXMLv1_1Parser extends Parser {
private final String userId;
public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "AND", "DIGIT",
"EQUAL", "ESC_SEQ", "FALSE", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "HEX_DIGIT", "INT", "LESS_THAN",
"LESS_THAN_OR_EQUAL", "LETTER", "LPAREN", "NOT_EQUAL", "OCTAL_ESC", "OR", "RPAREN", "SIMPLEID", "SIZE",
"STRING", "TRUE", "TYPE", "UNICODE_ESC", "UNIQUE", "UNKNOWN", "VALUE", "WS", "XOR", "'+'", "'-'", "'.'",
"'e'", "'reg'" };
public static final int EOF = -1;
public static final int T__32 = 32;
public static final int T__33 = 33;
public static final int T__34 = 34;
public static final int T__35 = 35;
public static final int T__36 = 36;
public static final int AND = 4;
public static final int DIGIT = 5;
public static final int EQUAL = 6;
public static final int ESC_SEQ = 7;
public static final int FALSE = 8;
public static final int GREATER_THAN = 9;
public static final int GREATER_THAN_OR_EQUAL = 10;
public static final int HEX_DIGIT = 11;
public static final int INT = 12;
public static final int LESS_THAN = 13;
public static final int LESS_THAN_OR_EQUAL = 14;
public static final int LETTER = 15;
public static final int LPAREN = 16;
public static final int NOT_EQUAL = 17;
public static final int OCTAL_ESC = 18;
public static final int OR = 19;
public static final int RPAREN = 20;
public static final int SIMPLEID = 21;
public static final int SIZE = 22;
public static final int STRING = 23;
public static final int TRUE = 24;
public static final int TYPE = 25;
public static final int UNICODE_ESC = 26;
public static final int UNIQUE = 27;
public static final int UNKNOWN = 28;
public static final int VALUE = 29;
public static final int WS = 30;
public static final int XOR = 31;
// delegates
public Parser[] getDelegates() {
return new Parser[] {};
}
// delegators
public MvdXMLv1_1Parser(String userId, TokenStream input) {
this(userId, input, new RecognizerSharedState());
}
public MvdXMLv1_1Parser(String userId, TokenStream input, RecognizerSharedState state) {
super(input, state);
this.userId = userId;
}
@Override
public String[] getTokenNames() {
return MvdXMLv1_1Parser.tokenNames;
}
@Override
public String getGrammarFileName() {
return "MvdXMLv1_1.g";
}
HashMap<AbstractRule, ObjectToValue> hashMap;
public MvdXMLv1_1Parser(String userId, TokenStream input, HashMap<AbstractRule, ObjectToValue> hashMap) {
this(userId, input, new RecognizerSharedState());
this.hashMap = hashMap;
}
// $ANTLR start "expression"
// MvdXMLv1_1.g:47:1: expression returns [Boolean expressionReturns] :
// boolean_expression ;
public final Boolean expression() throws RecognitionException {
Boolean expressionReturns = null;
Boolean boolean_expression1 = null;
try {
// MvdXMLv1_1.g:48:2: ( boolean_expression )
// MvdXMLv1_1.g:48:4: boolean_expression
{
pushFollow(FOLLOW_boolean_expression_in_expression37);
boolean_expression1 = boolean_expression();
state._fsp--;
expressionReturns = boolean_expression1;
}
} catch (RecognitionException re) {
}
finally {
// do for sure before leaving
}
return expressionReturns;
}
// $ANTLR end "expression"
// $ANTLR start "boolean_expression"
// MvdXMLv1_1.g:53:1: boolean_expression returns [Boolean result] : left=
// boolean_term ( AND right= boolean_expression )? ( OR right=
// boolean_expression )? ( XOR right= boolean_expression )? ;
public final Boolean boolean_expression() throws RecognitionException {
Boolean result = null;
Boolean left = null;
Boolean right = null;
try {
// MvdXMLv1_1.g:54:6: (left= boolean_term ( AND right= boolean_expression )? (
// OR right= boolean_expression )? ( XOR right= boolean_expression )? )
// MvdXMLv1_1.g:54:8: left= boolean_term ( AND right= boolean_expression )? ( OR
// right= boolean_expression )? ( XOR right= boolean_expression )?
{
pushFollow(FOLLOW_boolean_term_in_boolean_expression64);
left = boolean_term();
state._fsp--;
result = left;
// MvdXMLv1_1.g:54:41: ( AND right= boolean_expression )?
int alt1 = 2;
int LA1_0 = input.LA(1);
if ((LA1_0 == AND)) {
alt1 = 1;
}
switch (alt1) {
case 1:
// MvdXMLv1_1.g:54:42: AND right= boolean_expression
{
match(input, AND, FOLLOW_AND_in_boolean_expression68);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression72);
right = boolean_expression();
state._fsp--;
AndOperator andOperator = new AndOperator(left, right);
result = andOperator.getResult();
}
break;
}
// MvdXMLv1_1.g:59:6: ( OR right= boolean_expression )?
int alt2 = 2;
int LA2_0 = input.LA(1);
if ((LA2_0 == OR)) {
alt2 = 1;
}
switch (alt2) {
case 1:
// MvdXMLv1_1.g:59:7: OR right= boolean_expression
{
match(input, OR, FOLLOW_OR_in_boolean_expression91);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression95);
right = boolean_expression();
state._fsp--;
OrOperator orOperator = new OrOperator(left, right);
result = orOperator.getResult();
}
break;
}
// MvdXMLv1_1.g:64:6: ( XOR right= boolean_expression )?
int alt3 = 2;
int LA3_0 = input.LA(1);
if ((LA3_0 == XOR)) {
alt3 = 1;
}
switch (alt3) {
case 1:
// MvdXMLv1_1.g:64:7: XOR right= boolean_expression
{
match(input, XOR, FOLLOW_XOR_in_boolean_expression114);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression118);
right = boolean_expression();
state._fsp--;
XorOperator xorOperator = new XorOperator(left, right);
}
break;
}
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return result;
}
// $ANTLR end "boolean_expression"
// $ANTLR start "boolean_term"
// MvdXMLv1_1.g:71:1: boolean_term returns [Boolean boolTermReturns] : ( (
// (leftOperand= parameter (leftOperand= metric[leftOperand] )? ) op= operator
// (rightOperand= value |rightOperand= parameter (rightOperand=
// metric[rightOperand] )? ) ) | ( LPAREN valueReturns= boolean_expression
// RPAREN ) );
public final Boolean boolean_term() throws RecognitionException {
Boolean boolTermReturns = null;
Object leftOperand = null;
String op = null;
Object rightOperand = null;
Boolean valueReturns = null;
try {
// MvdXMLv1_1.g:72:2: ( ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) ) | ( LPAREN valueReturns=
// boolean_expression RPAREN ) )
int alt7 = 2;
int LA7_0 = input.LA(1);
if ((LA7_0 == SIMPLEID)) {
alt7 = 1;
} else if ((LA7_0 == LPAREN)) {
alt7 = 2;
}
else {
NoViableAltException nvae = new NoViableAltException("", 7, 0, input);
throw nvae;
}
switch (alt7) {
case 1:
// MvdXMLv1_1.g:72:4: ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) )
{
// MvdXMLv1_1.g:72:4: ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) )
// MvdXMLv1_1.g:72:5: (leftOperand= parameter (leftOperand= metric[leftOperand]
// )? ) op= operator (rightOperand= value |rightOperand= parameter
// (rightOperand= metric[rightOperand] )? )
{
// MvdXMLv1_1.g:72:5: (leftOperand= parameter (leftOperand= metric[leftOperand]
// )? )
// MvdXMLv1_1.g:72:7: leftOperand= parameter (leftOperand= metric[leftOperand]
// )?
{
pushFollow(FOLLOW_parameter_in_boolean_term166);
leftOperand = parameter();
state._fsp--;
// MvdXMLv1_1.g:72:29: (leftOperand= metric[leftOperand] )?
int alt4 = 2;
int LA4_0 = input.LA(1);
if ((LA4_0 == SIZE || LA4_0 == TYPE || LA4_0 == UNIQUE || LA4_0 == VALUE)) {
alt4 = 1;
}
switch (alt4) {
case 1:
// MvdXMLv1_1.g:72:31: leftOperand= metric[leftOperand]
{
pushFollow(FOLLOW_metric_in_boolean_term172);
leftOperand = metric(leftOperand);
state._fsp--;
}
break;
}
}
pushFollow(FOLLOW_operator_in_boolean_term181);
op = operator();
state._fsp--;
// MvdXMLv1_1.g:72:79: (rightOperand= value |rightOperand= parameter
// (rightOperand= metric[rightOperand] )? )
int alt6 = 2;
int LA6_0 = input.LA(1);
if ((LA6_0 == DIGIT || LA6_0 == FALSE || LA6_0 == INT || (LA6_0 >= STRING && LA6_0 <= TRUE)
|| LA6_0 == UNKNOWN || (LA6_0 >= 32 && LA6_0 <= 33) || LA6_0 == 36)) {
alt6 = 1;
} else if ((LA6_0 == SIMPLEID)) {
alt6 = 2;
}
else {
NoViableAltException nvae = new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1:
// MvdXMLv1_1.g:72:81: rightOperand= value
{
pushFollow(FOLLOW_value_in_boolean_term187);
rightOperand = value();
state._fsp--;
}
break;
case 2:
// MvdXMLv1_1.g:72:102: rightOperand= parameter (rightOperand=
// metric[rightOperand] )?
{
pushFollow(FOLLOW_parameter_in_boolean_term193);
rightOperand = parameter();
state._fsp--;
// MvdXMLv1_1.g:72:125: (rightOperand= metric[rightOperand] )?
int alt5 = 2;
int LA5_0 = input.LA(1);
if ((LA5_0 == SIZE || LA5_0 == TYPE || LA5_0 == UNIQUE || LA5_0 == VALUE)) {
alt5 = 1;
}
switch (alt5) {
case 1:
// MvdXMLv1_1.g:72:127: rightOperand= metric[rightOperand]
{
pushFollow(FOLLOW_metric_in_boolean_term199);
rightOperand = metric(rightOperand);
state._fsp--;
}
break;
}
}
break;
}
}
if (op.equals("=")) {
EqualOperator equalOperator = new EqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = equalOperator.getResult();
}
if (op.equals(">")) {
GreaterOperator greaterOperator = new GreaterOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = greaterOperator.getResult();
}
if (op.equals("<")) {
LessOperator lessOperator = new LessOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = lessOperator.getResult();
}
if (op.equals(">=")) {
GreaterEqualOperator greaterEqualOperator = new GreaterEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = greaterEqualOperator.getResult();
}
if (op.equals("<=")) {
LessEqualOperator lessEqualOperator = new LessEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = lessEqualOperator.getResult();
}
if (op.equals("!=")) {
InEqualOperator inEqualOperator = new InEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = inEqualOperator.getResult();
}
}
break;
case 2:
// MvdXMLv1_1.g:92:5: ( LPAREN valueReturns= boolean_expression RPAREN )
{
// MvdXMLv1_1.g:92:5: ( LPAREN valueReturns= boolean_expression RPAREN )
// MvdXMLv1_1.g:92:7: LPAREN valueReturns= boolean_expression RPAREN
{
match(input, LPAREN, FOLLOW_LPAREN_in_boolean_term217);
pushFollow(FOLLOW_boolean_expression_in_boolean_term221);
valueReturns = boolean_expression();
state._fsp--;
match(input, RPAREN, FOLLOW_RPAREN_in_boolean_term223);
}
boolTermReturns = valueReturns;
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return boolTermReturns;
}
// $ANTLR end "boolean_term"
// $ANTLR start "parameter"
// MvdXMLv1_1.g:95:1: parameter returns [Object paraReturns] : SIMPLEID ;
public final Object parameter() throws RecognitionException {
Object paraReturns = null;
Token SIMPLEID2 = null;
try {
// MvdXMLv1_1.g:96:2: ( SIMPLEID )
// MvdXMLv1_1.g:96:4: SIMPLEID
{
SIMPLEID2 = (Token) match(input, SIMPLEID, FOLLOW_SIMPLEID_in_parameter241);
Parameter parameter = new Parameter((SIMPLEID2 != null ? SIMPLEID2.getText() : null), hashMap);
paraReturns = parameter.getResult();
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return paraReturns;
}
// $ANTLR end "parameter"
// $ANTLR start "metric"
// MvdXMLv1_1.g:100:1: metric[Object value] returns [Object metricReturns] : (
// VALUE | SIZE | TYPE | UNIQUE );
public final Object metric(Object value) throws RecognitionException {
Object metricReturns = null;
try {
// MvdXMLv1_1.g:101:2: ( VALUE | SIZE | TYPE | UNIQUE )
int alt8 = 4;
switch (input.LA(1)) {
case VALUE: {
alt8 = 1;
}
break;
case SIZE: {
alt8 = 2;
}
break;
case TYPE: {
alt8 = 3;
}
break;
case UNIQUE: {
alt8 = 4;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 8, 0, input);
throw nvae;
}
switch (alt8) {
case 1:
// MvdXMLv1_1.g:101:4: VALUE
{
match(input, VALUE, FOLLOW_VALUE_in_metric260);
Metric metric = new Metric(value);
metricReturns = metric.getMetricValue();
}
break;
case 2:
// MvdXMLv1_1.g:102:4: SIZE
{
match(input, SIZE, FOLLOW_SIZE_in_metric267);
Metric metric = new Metric(value);
metricReturns = metric.getMetricSize();
}
break;
case 3:
// MvdXMLv1_1.g:103:4: TYPE
{
match(input, TYPE, FOLLOW_TYPE_in_metric274);
Metric metric = new Metric(value);
metricReturns = metric.getMetricType();
}
break;
case 4:
// MvdXMLv1_1.g:103:84: UNIQUE
{
match(input, UNIQUE, FOLLOW_UNIQUE_in_metric279);
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return metricReturns;
}
// $ANTLR end "metric"
// $ANTLR start "operator"
// MvdXMLv1_1.g:106:1: operator returns [String op] : ( EQUAL | NOT_EQUAL |
// GREATER_THAN | GREATER_THAN_OR_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL );
public final String operator() throws RecognitionException {
String op = null;
try {
// MvdXMLv1_1.g:107:2: ( EQUAL | NOT_EQUAL | GREATER_THAN |
// GREATER_THAN_OR_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL )
int alt9 = 6;
switch (input.LA(1)) {
case EQUAL: {
alt9 = 1;
}
break;
case NOT_EQUAL: {
alt9 = 2;
}
break;
case GREATER_THAN: {
alt9 = 3;
}
break;
case GREATER_THAN_OR_EQUAL: {
alt9 = 4;
}
break;
case LESS_THAN: {
alt9 = 5;
}
break;
case LESS_THAN_OR_EQUAL: {
alt9 = 6;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1:
// MvdXMLv1_1.g:107:4: EQUAL
{
match(input, EQUAL, FOLLOW_EQUAL_in_operator293);
op = "=";
}
break;
case 2:
// MvdXMLv1_1.g:107:22: NOT_EQUAL
{
match(input, NOT_EQUAL, FOLLOW_NOT_EQUAL_in_operator298);
op = "!=";
}
break;
case 3:
// MvdXMLv1_1.g:107:45: GREATER_THAN
{
match(input, GREATER_THAN, FOLLOW_GREATER_THAN_in_operator303);
op = ">";
}
break;
case 4:
// MvdXMLv1_1.g:107:71: GREATER_THAN_OR_EQUAL
{
match(input, GREATER_THAN_OR_EQUAL, FOLLOW_GREATER_THAN_OR_EQUAL_in_operator309);
op = ">=";
}
break;
case 5:
// MvdXMLv1_1.g:107:106: LESS_THAN
{
match(input, LESS_THAN, FOLLOW_LESS_THAN_in_operator314);
op = "<";
}
break;
case 6:
// MvdXMLv1_1.g:107:128: LESS_THAN_OR_EQUAL
{
match(input, LESS_THAN_OR_EQUAL, FOLLOW_LESS_THAN_OR_EQUAL_in_operator319);
op = "<=";
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return op;
}
// $ANTLR end "operator"
// $ANTLR start "value"
// MvdXMLv1_1.g:109:1: value returns [Object valueReturns] : ( logical_literal |
// real_literal | string_literal | regular_expression );
public final Object value() throws RecognitionException {
Object valueReturns = null;
Boolean logical_literal3 = null;
ParserRuleReturnScope real_literal4 = null;
String string_literal5 = null;
String regular_expression6 = null;
try {
// MvdXMLv1_1.g:110:2: ( logical_literal | real_literal | string_literal |
// regular_expression )
int alt10 = 4;
switch (input.LA(1)) {
case FALSE:
case TRUE:
case UNKNOWN: {
alt10 = 1;
}
break;
case DIGIT:
case INT:
case 32:
case 33: {
alt10 = 2;
}
break;
case STRING: {
alt10 = 3;
}
break;
case 36: {
alt10 = 4;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1:
// MvdXMLv1_1.g:110:4: logical_literal
{
pushFollow(FOLLOW_logical_literal_in_value334);
logical_literal3 = logical_literal();
state._fsp--;
valueReturns = logical_literal3;
}
break;
case 2:
// MvdXMLv1_1.g:112:6: real_literal
{
pushFollow(FOLLOW_real_literal_in_value339);
real_literal4 = real_literal();
state._fsp--;
valueReturns = (real_literal4 != null
? ((MvdXMLv1_1Parser.real_literal_return) real_literal4).realReturns
: null);
}
break;
case 3:
// MvdXMLv1_1.g:114:6: string_literal
{
pushFollow(FOLLOW_string_literal_in_value344);
string_literal5 = string_literal();
state._fsp--;
valueReturns = string_literal5;
}
break;
case 4:
// MvdXMLv1_1.g:116:6: regular_expression
{
pushFollow(FOLLOW_regular_expression_in_value349);
regular_expression6 = regular_expression();
state._fsp--;
valueReturns = regular_expression6;
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return valueReturns;
}
// $ANTLR end "value"
// $ANTLR start "logical_literal"
// MvdXMLv1_1.g:120:1: logical_literal returns [Boolean logicalReturns] : (
// FALSE | TRUE | UNKNOWN );
public final Boolean logical_literal() throws RecognitionException {
Boolean logicalReturns = null;
try {
// MvdXMLv1_1.g:121:2: ( FALSE | TRUE | UNKNOWN )
int alt11 = 3;
switch (input.LA(1)) {
case FALSE: {
alt11 = 1;
}
break;
case TRUE: {
alt11 = 2;
}
break;
case UNKNOWN: {
alt11 = 3;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1:
// MvdXMLv1_1.g:121:5: FALSE
{
match(input, FALSE, FOLLOW_FALSE_in_logical_literal365);
logicalReturns = false;
}
break;
case 2:
// MvdXMLv1_1.g:121:37: TRUE
{
match(input, TRUE, FOLLOW_TRUE_in_logical_literal370);
logicalReturns = true;
}
break;
case 3:
// MvdXMLv1_1.g:121:67: UNKNOWN
{
match(input, UNKNOWN, FOLLOW_UNKNOWN_in_logical_literal375);
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return logicalReturns;
}
// $ANTLR end "logical_literal"
public static class real_literal_return extends ParserRuleReturnScope {
public Double realReturns;
};
// $ANTLR start "real_literal"
// MvdXMLv1_1.g:123:1: real_literal returns [Double realReturns] : ( sign )? (
// DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )? ( 'e' ( sign )? ( DIGIT | INT )
// )? ;
public final MvdXMLv1_1Parser.real_literal_return real_literal() throws RecognitionException {
MvdXMLv1_1Parser.real_literal_return retval = new MvdXMLv1_1Parser.real_literal_return();
retval.start = input.LT(1);
try {
// MvdXMLv1_1.g:124:2: ( ( sign )? ( DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )?
// ( 'e' ( sign )? ( DIGIT | INT ) )? )
// MvdXMLv1_1.g:124:4: ( sign )? ( DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )? (
// 'e' ( sign )? ( DIGIT | INT ) )?
{
// MvdXMLv1_1.g:124:4: ( sign )?
int alt12 = 2;
int LA12_0 = input.LA(1);
if (((LA12_0 >= 32 && LA12_0 <= 33))) {
alt12 = 1;
}
switch (alt12) {
case 1:
// MvdXMLv1_1.g:124:5: sign
{
pushFollow(FOLLOW_sign_in_real_literal390);
sign();
state._fsp--;
}
break;
}
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
// MvdXMLv1_1.g:124:28: ( '.' )?
int alt13 = 2;
int LA13_0 = input.LA(1);
if ((LA13_0 == 34)) {
alt13 = 1;
}
switch (alt13) {
case 1:
// MvdXMLv1_1.g:124:29: '.'
{
match(input, 34, FOLLOW_34_in_real_literal405);
}
break;
}
// MvdXMLv1_1.g:124:35: ( ( DIGIT | INT ) )?
int alt14 = 2;
int LA14_0 = input.LA(1);
if ((LA14_0 == DIGIT || LA14_0 == INT)) {
alt14 = 1;
}
switch (alt14) {
case 1:
// MvdXMLv1_1.g:
{
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
break;
}
// MvdXMLv1_1.g:124:56: ( 'e' ( sign )? ( DIGIT | INT ) )?
int alt16 = 2;
int LA16_0 = input.LA(1);
if ((LA16_0 == 35)) {
alt16 = 1;
}
switch (alt16) {
case 1:
// MvdXMLv1_1.g:124:58: 'e' ( sign )? ( DIGIT | INT )
{
match(input, 35, FOLLOW_35_in_real_literal426);
// MvdXMLv1_1.g:124:62: ( sign )?
int alt15 = 2;
int LA15_0 = input.LA(1);
if (((LA15_0 >= 32 && LA15_0 <= 33))) {
alt15 = 1;
}
switch (alt15) {
case 1:
// MvdXMLv1_1.g:124:63: sign
{
pushFollow(FOLLOW_sign_in_real_literal429);
sign();
state._fsp--;
}
break;
}
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
break;
}
retval.realReturns = Double.parseDouble(input.toString(retval.start, input.LT(-1)));
}
retval.stop = input.LT(-1);
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "real_literal"
// $ANTLR start "string_literal"
// MvdXMLv1_1.g:126:1: string_literal returns [String stringReturns] : STRING ;
public final String string_literal() throws RecognitionException {
String stringReturns = null;
Token STRING7 = null;
try {
// MvdXMLv1_1.g:127:2: ( STRING )
// MvdXMLv1_1.g:127:4: STRING
{
STRING7 = (Token) match(input, STRING, FOLLOW_STRING_in_string_literal460);
stringReturns = (STRING7 != null ? STRING7.getText() : null).substring(1,
(STRING7 != null ? STRING7.getText() : null).length() - 1);
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return stringReturns;
}
// $ANTLR end "string_literal"
// $ANTLR start "regular_expression"
// MvdXMLv1_1.g:129:1: regular_expression returns [String regReturns] : 'reg'
// STRING ;
public final String regular_expression() throws RecognitionException {
String regReturns = null;
Token STRING8 = null;
try {
// MvdXMLv1_1.g:130:2: ( 'reg' STRING )
// MvdXMLv1_1.g:130:4: 'reg' STRING
{
match(input, 36, FOLLOW_36_in_regular_expression476);
STRING8 = (Token) match(input, STRING, FOLLOW_STRING_in_regular_expression478);
regReturns = "reg " + (STRING8 != null ? STRING8.getText() : null).substring(1,
(STRING8 != null ? STRING8.getText() : null).length() - 1);
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return regReturns;
}
// $ANTLR end "regular_expression"
// $ANTLR start "sign"
// MvdXMLv1_1.g:131:1: sign : ( '+' | '-' );
public final void sign() throws RecognitionException {
try {
// MvdXMLv1_1.g:132:2: ( '+' | '-' )
// MvdXMLv1_1.g:
{
if ((input.LA(1) >= 32 && input.LA(1) <= 33)) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
}
// $ANTLR end "sign"
// Delegated rules
public static final BitSet FOLLOW_boolean_expression_in_expression37 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_boolean_term_in_boolean_expression64 = new BitSet(
new long[] { 0x0000000080080012L });
public static final BitSet FOLLOW_AND_in_boolean_expression68 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression72 = new BitSet(
new long[] { 0x0000000080080002L });
public static final BitSet FOLLOW_OR_in_boolean_expression91 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression95 = new BitSet(
new long[] { 0x0000000080000002L });
public static final BitSet FOLLOW_XOR_in_boolean_expression114 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression118 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_parameter_in_boolean_term166 = new BitSet(new long[] { 0x000000002A426640L });
public static final BitSet FOLLOW_metric_in_boolean_term172 = new BitSet(new long[] { 0x0000000000026640L });
public static final BitSet FOLLOW_operator_in_boolean_term181 = new BitSet(new long[] { 0x0000001311A01120L });
public static final BitSet FOLLOW_value_in_boolean_term187 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_parameter_in_boolean_term193 = new BitSet(new long[] { 0x000000002A400002L });
public static final BitSet FOLLOW_metric_in_boolean_term199 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LPAREN_in_boolean_term217 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_term221 = new BitSet(
new long[] { 0x0000000000100000L });
public static final BitSet FOLLOW_RPAREN_in_boolean_term223 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_SIMPLEID_in_parameter241 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_VALUE_in_metric260 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_SIZE_in_metric267 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_TYPE_in_metric274 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_UNIQUE_in_metric279 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_EQUAL_in_operator293 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_NOT_EQUAL_in_operator298 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_GREATER_THAN_in_operator303 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_GREATER_THAN_OR_EQUAL_in_operator309 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LESS_THAN_in_operator314 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LESS_THAN_OR_EQUAL_in_operator319 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_logical_literal_in_value334 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_real_literal_in_value339 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_string_literal_in_value344 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_regular_expression_in_value349 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_FALSE_in_logical_literal365 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_TRUE_in_logical_literal370 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_UNKNOWN_in_logical_literal375 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_sign_in_real_literal390 = new BitSet(new long[] { 0x0000000000001020L });
public static final BitSet FOLLOW_set_in_real_literal394 = new BitSet(new long[] { 0x0000000C00001022L });
public static final BitSet FOLLOW_34_in_real_literal405 = new BitSet(new long[] { 0x0000000800001022L });
public static final BitSet FOLLOW_35_in_real_literal426 = new BitSet(new long[] { 0x0000000300001020L });
public static final BitSet FOLLOW_sign_in_real_literal429 = new BitSet(new long[] { 0x0000000000001020L });
public static final BitSet FOLLOW_set_in_real_literal433 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_STRING_in_string_literal460 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_36_in_regular_expression476 = new BitSet(new long[] { 0x0000000000800000L });
public static final BitSet FOLLOW_STRING_in_regular_expression478 = new BitSet(new long[] { 0x0000000000000002L });
}
| UTF-8 | Java | 31,340 | java | MvdXMLv1_1Parser.java | Java | []
| null | []
| // $ANTLR 3.5.2 MvdXMLv1_1.g 2020-05-05 16:37:25
package generated.mvdxml1underscore1.rule_operators;
import java.util.HashMap;
import org.antlr.runtime.BitSet;
import org.antlr.runtime.MismatchedSetException;
import org.antlr.runtime.NoViableAltException;
import org.antlr.runtime.Parser;
import org.antlr.runtime.ParserRuleReturnScope;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.RecognizerSharedState;
import org.antlr.runtime.Token;
import org.antlr.runtime.TokenStream;
import org.buildingsmart_tech.mvdxml.mvdxml1_1.AbstractRule;
import nl.tue.ddss.ifc_check.IfcHashMapBuilder.ObjectToValue;
import nl.tue.ddss.ifc_check.Metric;
import nl.tue.ddss.ifc_check.Parameter;
import nl.tue.ddss.rule_parse.AndOperator;
import nl.tue.ddss.rule_parse.EqualOperator;
import nl.tue.ddss.rule_parse.GreaterEqualOperator;
import nl.tue.ddss.rule_parse.GreaterOperator;
import nl.tue.ddss.rule_parse.InEqualOperator;
import nl.tue.ddss.rule_parse.LessEqualOperator;
import nl.tue.ddss.rule_parse.LessOperator;
import nl.tue.ddss.rule_parse.OrOperator;
import nl.tue.ddss.rule_parse.XorOperator;
@SuppressWarnings("all")
public class MvdXMLv1_1Parser extends Parser {
private final String userId;
public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "AND", "DIGIT",
"EQUAL", "ESC_SEQ", "FALSE", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "HEX_DIGIT", "INT", "LESS_THAN",
"LESS_THAN_OR_EQUAL", "LETTER", "LPAREN", "NOT_EQUAL", "OCTAL_ESC", "OR", "RPAREN", "SIMPLEID", "SIZE",
"STRING", "TRUE", "TYPE", "UNICODE_ESC", "UNIQUE", "UNKNOWN", "VALUE", "WS", "XOR", "'+'", "'-'", "'.'",
"'e'", "'reg'" };
public static final int EOF = -1;
public static final int T__32 = 32;
public static final int T__33 = 33;
public static final int T__34 = 34;
public static final int T__35 = 35;
public static final int T__36 = 36;
public static final int AND = 4;
public static final int DIGIT = 5;
public static final int EQUAL = 6;
public static final int ESC_SEQ = 7;
public static final int FALSE = 8;
public static final int GREATER_THAN = 9;
public static final int GREATER_THAN_OR_EQUAL = 10;
public static final int HEX_DIGIT = 11;
public static final int INT = 12;
public static final int LESS_THAN = 13;
public static final int LESS_THAN_OR_EQUAL = 14;
public static final int LETTER = 15;
public static final int LPAREN = 16;
public static final int NOT_EQUAL = 17;
public static final int OCTAL_ESC = 18;
public static final int OR = 19;
public static final int RPAREN = 20;
public static final int SIMPLEID = 21;
public static final int SIZE = 22;
public static final int STRING = 23;
public static final int TRUE = 24;
public static final int TYPE = 25;
public static final int UNICODE_ESC = 26;
public static final int UNIQUE = 27;
public static final int UNKNOWN = 28;
public static final int VALUE = 29;
public static final int WS = 30;
public static final int XOR = 31;
// delegates
public Parser[] getDelegates() {
return new Parser[] {};
}
// delegators
public MvdXMLv1_1Parser(String userId, TokenStream input) {
this(userId, input, new RecognizerSharedState());
}
public MvdXMLv1_1Parser(String userId, TokenStream input, RecognizerSharedState state) {
super(input, state);
this.userId = userId;
}
@Override
public String[] getTokenNames() {
return MvdXMLv1_1Parser.tokenNames;
}
@Override
public String getGrammarFileName() {
return "MvdXMLv1_1.g";
}
HashMap<AbstractRule, ObjectToValue> hashMap;
public MvdXMLv1_1Parser(String userId, TokenStream input, HashMap<AbstractRule, ObjectToValue> hashMap) {
this(userId, input, new RecognizerSharedState());
this.hashMap = hashMap;
}
// $ANTLR start "expression"
// MvdXMLv1_1.g:47:1: expression returns [Boolean expressionReturns] :
// boolean_expression ;
public final Boolean expression() throws RecognitionException {
Boolean expressionReturns = null;
Boolean boolean_expression1 = null;
try {
// MvdXMLv1_1.g:48:2: ( boolean_expression )
// MvdXMLv1_1.g:48:4: boolean_expression
{
pushFollow(FOLLOW_boolean_expression_in_expression37);
boolean_expression1 = boolean_expression();
state._fsp--;
expressionReturns = boolean_expression1;
}
} catch (RecognitionException re) {
}
finally {
// do for sure before leaving
}
return expressionReturns;
}
// $ANTLR end "expression"
// $ANTLR start "boolean_expression"
// MvdXMLv1_1.g:53:1: boolean_expression returns [Boolean result] : left=
// boolean_term ( AND right= boolean_expression )? ( OR right=
// boolean_expression )? ( XOR right= boolean_expression )? ;
public final Boolean boolean_expression() throws RecognitionException {
Boolean result = null;
Boolean left = null;
Boolean right = null;
try {
// MvdXMLv1_1.g:54:6: (left= boolean_term ( AND right= boolean_expression )? (
// OR right= boolean_expression )? ( XOR right= boolean_expression )? )
// MvdXMLv1_1.g:54:8: left= boolean_term ( AND right= boolean_expression )? ( OR
// right= boolean_expression )? ( XOR right= boolean_expression )?
{
pushFollow(FOLLOW_boolean_term_in_boolean_expression64);
left = boolean_term();
state._fsp--;
result = left;
// MvdXMLv1_1.g:54:41: ( AND right= boolean_expression )?
int alt1 = 2;
int LA1_0 = input.LA(1);
if ((LA1_0 == AND)) {
alt1 = 1;
}
switch (alt1) {
case 1:
// MvdXMLv1_1.g:54:42: AND right= boolean_expression
{
match(input, AND, FOLLOW_AND_in_boolean_expression68);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression72);
right = boolean_expression();
state._fsp--;
AndOperator andOperator = new AndOperator(left, right);
result = andOperator.getResult();
}
break;
}
// MvdXMLv1_1.g:59:6: ( OR right= boolean_expression )?
int alt2 = 2;
int LA2_0 = input.LA(1);
if ((LA2_0 == OR)) {
alt2 = 1;
}
switch (alt2) {
case 1:
// MvdXMLv1_1.g:59:7: OR right= boolean_expression
{
match(input, OR, FOLLOW_OR_in_boolean_expression91);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression95);
right = boolean_expression();
state._fsp--;
OrOperator orOperator = new OrOperator(left, right);
result = orOperator.getResult();
}
break;
}
// MvdXMLv1_1.g:64:6: ( XOR right= boolean_expression )?
int alt3 = 2;
int LA3_0 = input.LA(1);
if ((LA3_0 == XOR)) {
alt3 = 1;
}
switch (alt3) {
case 1:
// MvdXMLv1_1.g:64:7: XOR right= boolean_expression
{
match(input, XOR, FOLLOW_XOR_in_boolean_expression114);
pushFollow(FOLLOW_boolean_expression_in_boolean_expression118);
right = boolean_expression();
state._fsp--;
XorOperator xorOperator = new XorOperator(left, right);
}
break;
}
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return result;
}
// $ANTLR end "boolean_expression"
// $ANTLR start "boolean_term"
// MvdXMLv1_1.g:71:1: boolean_term returns [Boolean boolTermReturns] : ( (
// (leftOperand= parameter (leftOperand= metric[leftOperand] )? ) op= operator
// (rightOperand= value |rightOperand= parameter (rightOperand=
// metric[rightOperand] )? ) ) | ( LPAREN valueReturns= boolean_expression
// RPAREN ) );
public final Boolean boolean_term() throws RecognitionException {
Boolean boolTermReturns = null;
Object leftOperand = null;
String op = null;
Object rightOperand = null;
Boolean valueReturns = null;
try {
// MvdXMLv1_1.g:72:2: ( ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) ) | ( LPAREN valueReturns=
// boolean_expression RPAREN ) )
int alt7 = 2;
int LA7_0 = input.LA(1);
if ((LA7_0 == SIMPLEID)) {
alt7 = 1;
} else if ((LA7_0 == LPAREN)) {
alt7 = 2;
}
else {
NoViableAltException nvae = new NoViableAltException("", 7, 0, input);
throw nvae;
}
switch (alt7) {
case 1:
// MvdXMLv1_1.g:72:4: ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) )
{
// MvdXMLv1_1.g:72:4: ( (leftOperand= parameter (leftOperand=
// metric[leftOperand] )? ) op= operator (rightOperand= value |rightOperand=
// parameter (rightOperand= metric[rightOperand] )? ) )
// MvdXMLv1_1.g:72:5: (leftOperand= parameter (leftOperand= metric[leftOperand]
// )? ) op= operator (rightOperand= value |rightOperand= parameter
// (rightOperand= metric[rightOperand] )? )
{
// MvdXMLv1_1.g:72:5: (leftOperand= parameter (leftOperand= metric[leftOperand]
// )? )
// MvdXMLv1_1.g:72:7: leftOperand= parameter (leftOperand= metric[leftOperand]
// )?
{
pushFollow(FOLLOW_parameter_in_boolean_term166);
leftOperand = parameter();
state._fsp--;
// MvdXMLv1_1.g:72:29: (leftOperand= metric[leftOperand] )?
int alt4 = 2;
int LA4_0 = input.LA(1);
if ((LA4_0 == SIZE || LA4_0 == TYPE || LA4_0 == UNIQUE || LA4_0 == VALUE)) {
alt4 = 1;
}
switch (alt4) {
case 1:
// MvdXMLv1_1.g:72:31: leftOperand= metric[leftOperand]
{
pushFollow(FOLLOW_metric_in_boolean_term172);
leftOperand = metric(leftOperand);
state._fsp--;
}
break;
}
}
pushFollow(FOLLOW_operator_in_boolean_term181);
op = operator();
state._fsp--;
// MvdXMLv1_1.g:72:79: (rightOperand= value |rightOperand= parameter
// (rightOperand= metric[rightOperand] )? )
int alt6 = 2;
int LA6_0 = input.LA(1);
if ((LA6_0 == DIGIT || LA6_0 == FALSE || LA6_0 == INT || (LA6_0 >= STRING && LA6_0 <= TRUE)
|| LA6_0 == UNKNOWN || (LA6_0 >= 32 && LA6_0 <= 33) || LA6_0 == 36)) {
alt6 = 1;
} else if ((LA6_0 == SIMPLEID)) {
alt6 = 2;
}
else {
NoViableAltException nvae = new NoViableAltException("", 6, 0, input);
throw nvae;
}
switch (alt6) {
case 1:
// MvdXMLv1_1.g:72:81: rightOperand= value
{
pushFollow(FOLLOW_value_in_boolean_term187);
rightOperand = value();
state._fsp--;
}
break;
case 2:
// MvdXMLv1_1.g:72:102: rightOperand= parameter (rightOperand=
// metric[rightOperand] )?
{
pushFollow(FOLLOW_parameter_in_boolean_term193);
rightOperand = parameter();
state._fsp--;
// MvdXMLv1_1.g:72:125: (rightOperand= metric[rightOperand] )?
int alt5 = 2;
int LA5_0 = input.LA(1);
if ((LA5_0 == SIZE || LA5_0 == TYPE || LA5_0 == UNIQUE || LA5_0 == VALUE)) {
alt5 = 1;
}
switch (alt5) {
case 1:
// MvdXMLv1_1.g:72:127: rightOperand= metric[rightOperand]
{
pushFollow(FOLLOW_metric_in_boolean_term199);
rightOperand = metric(rightOperand);
state._fsp--;
}
break;
}
}
break;
}
}
if (op.equals("=")) {
EqualOperator equalOperator = new EqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = equalOperator.getResult();
}
if (op.equals(">")) {
GreaterOperator greaterOperator = new GreaterOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = greaterOperator.getResult();
}
if (op.equals("<")) {
LessOperator lessOperator = new LessOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = lessOperator.getResult();
}
if (op.equals(">=")) {
GreaterEqualOperator greaterEqualOperator = new GreaterEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = greaterEqualOperator.getResult();
}
if (op.equals("<=")) {
LessEqualOperator lessEqualOperator = new LessEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = lessEqualOperator.getResult();
}
if (op.equals("!=")) {
InEqualOperator inEqualOperator = new InEqualOperator(this.userId,leftOperand, rightOperand);
boolTermReturns = inEqualOperator.getResult();
}
}
break;
case 2:
// MvdXMLv1_1.g:92:5: ( LPAREN valueReturns= boolean_expression RPAREN )
{
// MvdXMLv1_1.g:92:5: ( LPAREN valueReturns= boolean_expression RPAREN )
// MvdXMLv1_1.g:92:7: LPAREN valueReturns= boolean_expression RPAREN
{
match(input, LPAREN, FOLLOW_LPAREN_in_boolean_term217);
pushFollow(FOLLOW_boolean_expression_in_boolean_term221);
valueReturns = boolean_expression();
state._fsp--;
match(input, RPAREN, FOLLOW_RPAREN_in_boolean_term223);
}
boolTermReturns = valueReturns;
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return boolTermReturns;
}
// $ANTLR end "boolean_term"
// $ANTLR start "parameter"
// MvdXMLv1_1.g:95:1: parameter returns [Object paraReturns] : SIMPLEID ;
public final Object parameter() throws RecognitionException {
Object paraReturns = null;
Token SIMPLEID2 = null;
try {
// MvdXMLv1_1.g:96:2: ( SIMPLEID )
// MvdXMLv1_1.g:96:4: SIMPLEID
{
SIMPLEID2 = (Token) match(input, SIMPLEID, FOLLOW_SIMPLEID_in_parameter241);
Parameter parameter = new Parameter((SIMPLEID2 != null ? SIMPLEID2.getText() : null), hashMap);
paraReturns = parameter.getResult();
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return paraReturns;
}
// $ANTLR end "parameter"
// $ANTLR start "metric"
// MvdXMLv1_1.g:100:1: metric[Object value] returns [Object metricReturns] : (
// VALUE | SIZE | TYPE | UNIQUE );
public final Object metric(Object value) throws RecognitionException {
Object metricReturns = null;
try {
// MvdXMLv1_1.g:101:2: ( VALUE | SIZE | TYPE | UNIQUE )
int alt8 = 4;
switch (input.LA(1)) {
case VALUE: {
alt8 = 1;
}
break;
case SIZE: {
alt8 = 2;
}
break;
case TYPE: {
alt8 = 3;
}
break;
case UNIQUE: {
alt8 = 4;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 8, 0, input);
throw nvae;
}
switch (alt8) {
case 1:
// MvdXMLv1_1.g:101:4: VALUE
{
match(input, VALUE, FOLLOW_VALUE_in_metric260);
Metric metric = new Metric(value);
metricReturns = metric.getMetricValue();
}
break;
case 2:
// MvdXMLv1_1.g:102:4: SIZE
{
match(input, SIZE, FOLLOW_SIZE_in_metric267);
Metric metric = new Metric(value);
metricReturns = metric.getMetricSize();
}
break;
case 3:
// MvdXMLv1_1.g:103:4: TYPE
{
match(input, TYPE, FOLLOW_TYPE_in_metric274);
Metric metric = new Metric(value);
metricReturns = metric.getMetricType();
}
break;
case 4:
// MvdXMLv1_1.g:103:84: UNIQUE
{
match(input, UNIQUE, FOLLOW_UNIQUE_in_metric279);
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return metricReturns;
}
// $ANTLR end "metric"
// $ANTLR start "operator"
// MvdXMLv1_1.g:106:1: operator returns [String op] : ( EQUAL | NOT_EQUAL |
// GREATER_THAN | GREATER_THAN_OR_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL );
public final String operator() throws RecognitionException {
String op = null;
try {
// MvdXMLv1_1.g:107:2: ( EQUAL | NOT_EQUAL | GREATER_THAN |
// GREATER_THAN_OR_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL )
int alt9 = 6;
switch (input.LA(1)) {
case EQUAL: {
alt9 = 1;
}
break;
case NOT_EQUAL: {
alt9 = 2;
}
break;
case GREATER_THAN: {
alt9 = 3;
}
break;
case GREATER_THAN_OR_EQUAL: {
alt9 = 4;
}
break;
case LESS_THAN: {
alt9 = 5;
}
break;
case LESS_THAN_OR_EQUAL: {
alt9 = 6;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 9, 0, input);
throw nvae;
}
switch (alt9) {
case 1:
// MvdXMLv1_1.g:107:4: EQUAL
{
match(input, EQUAL, FOLLOW_EQUAL_in_operator293);
op = "=";
}
break;
case 2:
// MvdXMLv1_1.g:107:22: NOT_EQUAL
{
match(input, NOT_EQUAL, FOLLOW_NOT_EQUAL_in_operator298);
op = "!=";
}
break;
case 3:
// MvdXMLv1_1.g:107:45: GREATER_THAN
{
match(input, GREATER_THAN, FOLLOW_GREATER_THAN_in_operator303);
op = ">";
}
break;
case 4:
// MvdXMLv1_1.g:107:71: GREATER_THAN_OR_EQUAL
{
match(input, GREATER_THAN_OR_EQUAL, FOLLOW_GREATER_THAN_OR_EQUAL_in_operator309);
op = ">=";
}
break;
case 5:
// MvdXMLv1_1.g:107:106: LESS_THAN
{
match(input, LESS_THAN, FOLLOW_LESS_THAN_in_operator314);
op = "<";
}
break;
case 6:
// MvdXMLv1_1.g:107:128: LESS_THAN_OR_EQUAL
{
match(input, LESS_THAN_OR_EQUAL, FOLLOW_LESS_THAN_OR_EQUAL_in_operator319);
op = "<=";
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return op;
}
// $ANTLR end "operator"
// $ANTLR start "value"
// MvdXMLv1_1.g:109:1: value returns [Object valueReturns] : ( logical_literal |
// real_literal | string_literal | regular_expression );
public final Object value() throws RecognitionException {
Object valueReturns = null;
Boolean logical_literal3 = null;
ParserRuleReturnScope real_literal4 = null;
String string_literal5 = null;
String regular_expression6 = null;
try {
// MvdXMLv1_1.g:110:2: ( logical_literal | real_literal | string_literal |
// regular_expression )
int alt10 = 4;
switch (input.LA(1)) {
case FALSE:
case TRUE:
case UNKNOWN: {
alt10 = 1;
}
break;
case DIGIT:
case INT:
case 32:
case 33: {
alt10 = 2;
}
break;
case STRING: {
alt10 = 3;
}
break;
case 36: {
alt10 = 4;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1:
// MvdXMLv1_1.g:110:4: logical_literal
{
pushFollow(FOLLOW_logical_literal_in_value334);
logical_literal3 = logical_literal();
state._fsp--;
valueReturns = logical_literal3;
}
break;
case 2:
// MvdXMLv1_1.g:112:6: real_literal
{
pushFollow(FOLLOW_real_literal_in_value339);
real_literal4 = real_literal();
state._fsp--;
valueReturns = (real_literal4 != null
? ((MvdXMLv1_1Parser.real_literal_return) real_literal4).realReturns
: null);
}
break;
case 3:
// MvdXMLv1_1.g:114:6: string_literal
{
pushFollow(FOLLOW_string_literal_in_value344);
string_literal5 = string_literal();
state._fsp--;
valueReturns = string_literal5;
}
break;
case 4:
// MvdXMLv1_1.g:116:6: regular_expression
{
pushFollow(FOLLOW_regular_expression_in_value349);
regular_expression6 = regular_expression();
state._fsp--;
valueReturns = regular_expression6;
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return valueReturns;
}
// $ANTLR end "value"
// $ANTLR start "logical_literal"
// MvdXMLv1_1.g:120:1: logical_literal returns [Boolean logicalReturns] : (
// FALSE | TRUE | UNKNOWN );
public final Boolean logical_literal() throws RecognitionException {
Boolean logicalReturns = null;
try {
// MvdXMLv1_1.g:121:2: ( FALSE | TRUE | UNKNOWN )
int alt11 = 3;
switch (input.LA(1)) {
case FALSE: {
alt11 = 1;
}
break;
case TRUE: {
alt11 = 2;
}
break;
case UNKNOWN: {
alt11 = 3;
}
break;
default:
NoViableAltException nvae = new NoViableAltException("", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1:
// MvdXMLv1_1.g:121:5: FALSE
{
match(input, FALSE, FOLLOW_FALSE_in_logical_literal365);
logicalReturns = false;
}
break;
case 2:
// MvdXMLv1_1.g:121:37: TRUE
{
match(input, TRUE, FOLLOW_TRUE_in_logical_literal370);
logicalReturns = true;
}
break;
case 3:
// MvdXMLv1_1.g:121:67: UNKNOWN
{
match(input, UNKNOWN, FOLLOW_UNKNOWN_in_logical_literal375);
}
break;
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return logicalReturns;
}
// $ANTLR end "logical_literal"
public static class real_literal_return extends ParserRuleReturnScope {
public Double realReturns;
};
// $ANTLR start "real_literal"
// MvdXMLv1_1.g:123:1: real_literal returns [Double realReturns] : ( sign )? (
// DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )? ( 'e' ( sign )? ( DIGIT | INT )
// )? ;
public final MvdXMLv1_1Parser.real_literal_return real_literal() throws RecognitionException {
MvdXMLv1_1Parser.real_literal_return retval = new MvdXMLv1_1Parser.real_literal_return();
retval.start = input.LT(1);
try {
// MvdXMLv1_1.g:124:2: ( ( sign )? ( DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )?
// ( 'e' ( sign )? ( DIGIT | INT ) )? )
// MvdXMLv1_1.g:124:4: ( sign )? ( DIGIT | INT ) ( '.' )? ( ( DIGIT | INT ) )? (
// 'e' ( sign )? ( DIGIT | INT ) )?
{
// MvdXMLv1_1.g:124:4: ( sign )?
int alt12 = 2;
int LA12_0 = input.LA(1);
if (((LA12_0 >= 32 && LA12_0 <= 33))) {
alt12 = 1;
}
switch (alt12) {
case 1:
// MvdXMLv1_1.g:124:5: sign
{
pushFollow(FOLLOW_sign_in_real_literal390);
sign();
state._fsp--;
}
break;
}
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
// MvdXMLv1_1.g:124:28: ( '.' )?
int alt13 = 2;
int LA13_0 = input.LA(1);
if ((LA13_0 == 34)) {
alt13 = 1;
}
switch (alt13) {
case 1:
// MvdXMLv1_1.g:124:29: '.'
{
match(input, 34, FOLLOW_34_in_real_literal405);
}
break;
}
// MvdXMLv1_1.g:124:35: ( ( DIGIT | INT ) )?
int alt14 = 2;
int LA14_0 = input.LA(1);
if ((LA14_0 == DIGIT || LA14_0 == INT)) {
alt14 = 1;
}
switch (alt14) {
case 1:
// MvdXMLv1_1.g:
{
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
break;
}
// MvdXMLv1_1.g:124:56: ( 'e' ( sign )? ( DIGIT | INT ) )?
int alt16 = 2;
int LA16_0 = input.LA(1);
if ((LA16_0 == 35)) {
alt16 = 1;
}
switch (alt16) {
case 1:
// MvdXMLv1_1.g:124:58: 'e' ( sign )? ( DIGIT | INT )
{
match(input, 35, FOLLOW_35_in_real_literal426);
// MvdXMLv1_1.g:124:62: ( sign )?
int alt15 = 2;
int LA15_0 = input.LA(1);
if (((LA15_0 >= 32 && LA15_0 <= 33))) {
alt15 = 1;
}
switch (alt15) {
case 1:
// MvdXMLv1_1.g:124:63: sign
{
pushFollow(FOLLOW_sign_in_real_literal429);
sign();
state._fsp--;
}
break;
}
if (input.LA(1) == DIGIT || input.LA(1) == INT) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
break;
}
retval.realReturns = Double.parseDouble(input.toString(retval.start, input.LT(-1)));
}
retval.stop = input.LT(-1);
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return retval;
}
// $ANTLR end "real_literal"
// $ANTLR start "string_literal"
// MvdXMLv1_1.g:126:1: string_literal returns [String stringReturns] : STRING ;
public final String string_literal() throws RecognitionException {
String stringReturns = null;
Token STRING7 = null;
try {
// MvdXMLv1_1.g:127:2: ( STRING )
// MvdXMLv1_1.g:127:4: STRING
{
STRING7 = (Token) match(input, STRING, FOLLOW_STRING_in_string_literal460);
stringReturns = (STRING7 != null ? STRING7.getText() : null).substring(1,
(STRING7 != null ? STRING7.getText() : null).length() - 1);
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return stringReturns;
}
// $ANTLR end "string_literal"
// $ANTLR start "regular_expression"
// MvdXMLv1_1.g:129:1: regular_expression returns [String regReturns] : 'reg'
// STRING ;
public final String regular_expression() throws RecognitionException {
String regReturns = null;
Token STRING8 = null;
try {
// MvdXMLv1_1.g:130:2: ( 'reg' STRING )
// MvdXMLv1_1.g:130:4: 'reg' STRING
{
match(input, 36, FOLLOW_36_in_regular_expression476);
STRING8 = (Token) match(input, STRING, FOLLOW_STRING_in_regular_expression478);
regReturns = "reg " + (STRING8 != null ? STRING8.getText() : null).substring(1,
(STRING8 != null ? STRING8.getText() : null).length() - 1);
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
return regReturns;
}
// $ANTLR end "regular_expression"
// $ANTLR start "sign"
// MvdXMLv1_1.g:131:1: sign : ( '+' | '-' );
public final void sign() throws RecognitionException {
try {
// MvdXMLv1_1.g:132:2: ( '+' | '-' )
// MvdXMLv1_1.g:
{
if ((input.LA(1) >= 32 && input.LA(1) <= 33)) {
input.consume();
state.errorRecovery = false;
} else {
MismatchedSetException mse = new MismatchedSetException(null, input);
throw mse;
}
}
} catch (RecognitionException re) {
reportError(re);
recover(input, re);
} finally {
// do for sure before leaving
}
}
// $ANTLR end "sign"
// Delegated rules
public static final BitSet FOLLOW_boolean_expression_in_expression37 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_boolean_term_in_boolean_expression64 = new BitSet(
new long[] { 0x0000000080080012L });
public static final BitSet FOLLOW_AND_in_boolean_expression68 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression72 = new BitSet(
new long[] { 0x0000000080080002L });
public static final BitSet FOLLOW_OR_in_boolean_expression91 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression95 = new BitSet(
new long[] { 0x0000000080000002L });
public static final BitSet FOLLOW_XOR_in_boolean_expression114 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_expression118 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_parameter_in_boolean_term166 = new BitSet(new long[] { 0x000000002A426640L });
public static final BitSet FOLLOW_metric_in_boolean_term172 = new BitSet(new long[] { 0x0000000000026640L });
public static final BitSet FOLLOW_operator_in_boolean_term181 = new BitSet(new long[] { 0x0000001311A01120L });
public static final BitSet FOLLOW_value_in_boolean_term187 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_parameter_in_boolean_term193 = new BitSet(new long[] { 0x000000002A400002L });
public static final BitSet FOLLOW_metric_in_boolean_term199 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LPAREN_in_boolean_term217 = new BitSet(new long[] { 0x0000000000210000L });
public static final BitSet FOLLOW_boolean_expression_in_boolean_term221 = new BitSet(
new long[] { 0x0000000000100000L });
public static final BitSet FOLLOW_RPAREN_in_boolean_term223 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_SIMPLEID_in_parameter241 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_VALUE_in_metric260 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_SIZE_in_metric267 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_TYPE_in_metric274 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_UNIQUE_in_metric279 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_EQUAL_in_operator293 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_NOT_EQUAL_in_operator298 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_GREATER_THAN_in_operator303 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_GREATER_THAN_OR_EQUAL_in_operator309 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LESS_THAN_in_operator314 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_LESS_THAN_OR_EQUAL_in_operator319 = new BitSet(
new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_logical_literal_in_value334 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_real_literal_in_value339 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_string_literal_in_value344 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_regular_expression_in_value349 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_FALSE_in_logical_literal365 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_TRUE_in_logical_literal370 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_UNKNOWN_in_logical_literal375 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_sign_in_real_literal390 = new BitSet(new long[] { 0x0000000000001020L });
public static final BitSet FOLLOW_set_in_real_literal394 = new BitSet(new long[] { 0x0000000C00001022L });
public static final BitSet FOLLOW_34_in_real_literal405 = new BitSet(new long[] { 0x0000000800001022L });
public static final BitSet FOLLOW_35_in_real_literal426 = new BitSet(new long[] { 0x0000000300001020L });
public static final BitSet FOLLOW_sign_in_real_literal429 = new BitSet(new long[] { 0x0000000000001020L });
public static final BitSet FOLLOW_set_in_real_literal433 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_STRING_in_string_literal460 = new BitSet(new long[] { 0x0000000000000002L });
public static final BitSet FOLLOW_36_in_regular_expression476 = new BitSet(new long[] { 0x0000000000800000L });
public static final BitSet FOLLOW_STRING_in_regular_expression478 = new BitSet(new long[] { 0x0000000000000002L });
}
| 31,340 | 0.64649 | 0.584078 | 1,059 | 28.593956 | 28.451097 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.418319 | false | false | 2 |
5815eaaf67f254ceaab1e8e1017f0f67017a202b | 26,130,581,046,471 | 9642c0c367f56f8907f064268007df716f23a3b2 | /Multi-Player Game/src/com/GameName/Cube/Cubes/TestCube.java | 72ff8908dc6727c6792cd7a367dbc3506462e54c | []
| no_license | QuantumCoding/MultiPlayer-Game | https://github.com/QuantumCoding/MultiPlayer-Game | 481a773a162c6dbfd374ee4896a2a9143d3c3202 | 40c72b677998651f63920d4c1f4b7b829e4f1f5b | refs/heads/master | 2021-01-10T20:16:59.530000 | 2017-10-27T11:26:54 | 2017-10-27T11:26:54 | 23,199,547 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.GameName.Cube.Cubes;
import com.GameName.Cube.Cube;
public class TestCube extends Cube {
public TestCube() {
super("TestCube");
setDisplayName("Text Cube");
}
}
| UTF-8 | Java | 198 | java | TestCube.java | Java | []
| null | []
| package com.GameName.Cube.Cubes;
import com.GameName.Cube.Cube;
public class TestCube extends Cube {
public TestCube() {
super("TestCube");
setDisplayName("Text Cube");
}
}
| 198 | 0.661616 | 0.661616 | 12 | 14.5 | 14.162745 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.083333 | false | false | 2 |
47e4612bdf1cbb6315f2f2c9d34bf73ad0e9a60c | 14,611,478,795,904 | ebeb745d087e4936a2d6abbeac9471b0bf9661bd | /src/com/undi/crazy8/CardGraphic.java | fd4fdf10d5aebfda620d24ba2ba59ec881b812c7 | []
| no_license | compmstr/Crazy8 | https://github.com/compmstr/Crazy8 | 2d3afa0828bd96d53842054e9942f89f691d7ae5 | 3efa1dd90e466426a3307c45ba9a97faf6cc1f57 | refs/heads/master | 2021-01-23T00:06:21.201000 | 2013-09-04T20:10:48 | 2013-09-04T20:10:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.undi.crazy8;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
/**
* Singleton class to hold the card graphics
* @author corey
*
*/
public class CardGraphic {
private Bitmap cardBack;
private Bitmap cardFaces;
private float cardWidthPercent;
private int cardWidth;
private int cardHeight;
private Rect srcRect = new Rect();
private Rect destRect = new Rect();
private Context context;
private int screenW, screenH;
public CardGraphic(Context context, float cardWidthPercent){
this.cardWidthPercent = cardWidthPercent;
this.context = context;
}
/**
* Callback for when the screen size changes.
* Updates screenW and screenH, and reloads graphics
* @param screenW
* @param screenH
*/
public void onResize(int screenW, int screenH){
this.screenW = screenW;
this.screenH = screenH;
load();
}
/**
* Loads the graphics for the cards, and scales them appropriately
* to the provided screen width/height
* @param screenW
* @param screenH
*/
public void load(){
Bitmap raw = BitmapFactory.decodeResource(context.getResources(), R.drawable.card_fronts);
cardWidth = (int) (cardWidthPercent * screenW);
cardHeight = cardWidth * 2;
cardFaces = Bitmap.createScaledBitmap(raw, cardWidth * 13, cardHeight * 4, false);
raw = BitmapFactory.decodeResource(context.getResources(), R.drawable.card_back);
cardBack = Bitmap.createScaledBitmap(raw, cardWidth, cardHeight, false);
}
public void drawCardBackPercent(Canvas canvas, float percentX, float percentY){
if(cardBack != null){
canvas.drawBitmap(cardBack, percentX * screenW, percentY * screenH, null);
}
}
public void drawCardBack(Canvas canvas, int x, int y){
if(cardBack != null){
canvas.drawBitmap(cardBack, x, y, null);
}
}
public void drawCardPercent(Canvas canvas, CardRef ref, float percentX, float percentY){
if(ref == CardRef.CARD_BACK){
drawCardBackPercent(canvas, percentX, percentY);
}else{
if(cardFaces != null){
destRect.left = (int) (percentX * screenW);
destRect.right = destRect.left + cardWidth;
destRect.top = (int) (percentY * screenH);
destRect.bottom = destRect.top + cardHeight;
srcRect.left = ref.getRankNum() * cardWidth;
srcRect.right = srcRect.left + cardWidth;
srcRect.top = ref.getSuitNum() * cardHeight;
srcRect.bottom = srcRect.top + cardHeight;
canvas.drawBitmap(cardFaces, srcRect, destRect, null);
}
}
}
public void drawCard(Canvas canvas, CardRef ref, int x, int y){
if(ref == CardRef.CARD_BACK){
drawCardBack(canvas, x, y);
}else{
if(cardFaces != null){
destRect.left = x;
destRect.right = x + cardWidth;
destRect.top = y;
destRect.bottom = y + cardHeight;
srcRect.left = ref.getRankNum() * cardWidth;
srcRect.right = srcRect.left + cardWidth;
srcRect.top = ref.getSuitNum() * cardHeight;
srcRect.bottom = srcRect.top + cardHeight;
canvas.drawBitmap(cardFaces, srcRect, destRect, null);
}
}
}
public float getCardHeightPercent(){
return (float)cardHeight / screenH;
}
public int getCardWidth(){ return cardWidth; }
public int getCardHeight(){ return cardHeight; }
}
| UTF-8 | Java | 3,269 | java | CardGraphic.java | Java | [
{
"context": "ngleton class to hold the card graphics\n * @author corey\n *\n */\npublic class CardGraphic {\n\tprivate Bitmap",
"end": 257,
"score": 0.9929442405700684,
"start": 252,
"tag": "USERNAME",
"value": "corey"
}
]
| null | []
| package com.undi.crazy8;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
/**
* Singleton class to hold the card graphics
* @author corey
*
*/
public class CardGraphic {
private Bitmap cardBack;
private Bitmap cardFaces;
private float cardWidthPercent;
private int cardWidth;
private int cardHeight;
private Rect srcRect = new Rect();
private Rect destRect = new Rect();
private Context context;
private int screenW, screenH;
public CardGraphic(Context context, float cardWidthPercent){
this.cardWidthPercent = cardWidthPercent;
this.context = context;
}
/**
* Callback for when the screen size changes.
* Updates screenW and screenH, and reloads graphics
* @param screenW
* @param screenH
*/
public void onResize(int screenW, int screenH){
this.screenW = screenW;
this.screenH = screenH;
load();
}
/**
* Loads the graphics for the cards, and scales them appropriately
* to the provided screen width/height
* @param screenW
* @param screenH
*/
public void load(){
Bitmap raw = BitmapFactory.decodeResource(context.getResources(), R.drawable.card_fronts);
cardWidth = (int) (cardWidthPercent * screenW);
cardHeight = cardWidth * 2;
cardFaces = Bitmap.createScaledBitmap(raw, cardWidth * 13, cardHeight * 4, false);
raw = BitmapFactory.decodeResource(context.getResources(), R.drawable.card_back);
cardBack = Bitmap.createScaledBitmap(raw, cardWidth, cardHeight, false);
}
public void drawCardBackPercent(Canvas canvas, float percentX, float percentY){
if(cardBack != null){
canvas.drawBitmap(cardBack, percentX * screenW, percentY * screenH, null);
}
}
public void drawCardBack(Canvas canvas, int x, int y){
if(cardBack != null){
canvas.drawBitmap(cardBack, x, y, null);
}
}
public void drawCardPercent(Canvas canvas, CardRef ref, float percentX, float percentY){
if(ref == CardRef.CARD_BACK){
drawCardBackPercent(canvas, percentX, percentY);
}else{
if(cardFaces != null){
destRect.left = (int) (percentX * screenW);
destRect.right = destRect.left + cardWidth;
destRect.top = (int) (percentY * screenH);
destRect.bottom = destRect.top + cardHeight;
srcRect.left = ref.getRankNum() * cardWidth;
srcRect.right = srcRect.left + cardWidth;
srcRect.top = ref.getSuitNum() * cardHeight;
srcRect.bottom = srcRect.top + cardHeight;
canvas.drawBitmap(cardFaces, srcRect, destRect, null);
}
}
}
public void drawCard(Canvas canvas, CardRef ref, int x, int y){
if(ref == CardRef.CARD_BACK){
drawCardBack(canvas, x, y);
}else{
if(cardFaces != null){
destRect.left = x;
destRect.right = x + cardWidth;
destRect.top = y;
destRect.bottom = y + cardHeight;
srcRect.left = ref.getRankNum() * cardWidth;
srcRect.right = srcRect.left + cardWidth;
srcRect.top = ref.getSuitNum() * cardHeight;
srcRect.bottom = srcRect.top + cardHeight;
canvas.drawBitmap(cardFaces, srcRect, destRect, null);
}
}
}
public float getCardHeightPercent(){
return (float)cardHeight / screenH;
}
public int getCardWidth(){ return cardWidth; }
public int getCardHeight(){ return cardHeight; }
}
| 3,269 | 0.711533 | 0.710003 | 107 | 29.551401 | 23.195726 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.551402 | false | false | 2 |
a3d4fb1421f8b5e96755799205eff6f2d5082f08 | 14,611,478,797,587 | 29cce0b4b6372e24bd48abcb238fc7ef65d02a1b | /Proyecto_2_Programacion_4/src/controlador/FiltroSesionActiva.java | 6885e1efaab922e9ef8fbfb45453b2bcfb18b138 | []
| no_license | yancarq/proyecto2Progra | https://github.com/yancarq/proyecto2Progra | 09b24b5bda4c9b7df0739161ccc221789f944421 | 0213c607af43df817c32ac5f8b8c97716d1bae5e | refs/heads/master | 2021-01-22T08:34:23.680000 | 2017-06-14T14:54:09 | 2017-06-14T14:54:09 | 92,624,312 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controlador;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class FiltroSesionActiva
*/
@WebFilter("/FiltroSesionActiva")
public class FiltroSesionActiva implements Filter {
/**
* Default constructor.
*/
public FiltroSesionActiva() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("FILTER");
// Cargamos la sesion
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
Object usuario = null;
// Preguntamos por un objeto en la sesion
if (session != null)
usuario = session.getAttribute("nombre");
if (session == null || usuario == null)
System.out.println("Session Invalid");
else
System.out.println("Session valid");
if (session == null || usuario == null) {// if we have no session
try {
httpRequest.getRequestDispatcher("/timeout.html").forward(request, response);
return;
} catch (ServletException e) {
} catch (IOException e) {
}
}
try {
chain.doFilter(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 1,978 | java | FiltroSesionActiva.java | Java | []
| null | []
| package controlador;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class FiltroSesionActiva
*/
@WebFilter("/FiltroSesionActiva")
public class FiltroSesionActiva implements Filter {
/**
* Default constructor.
*/
public FiltroSesionActiva() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("FILTER");
// Cargamos la sesion
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpSession session = httpRequest.getSession(false);
Object usuario = null;
// Preguntamos por un objeto en la sesion
if (session != null)
usuario = session.getAttribute("nombre");
if (session == null || usuario == null)
System.out.println("Session Invalid");
else
System.out.println("Session valid");
if (session == null || usuario == null) {// if we have no session
try {
httpRequest.getRequestDispatcher("/timeout.html").forward(request, response);
return;
} catch (ServletException e) {
} catch (IOException e) {
}
}
try {
chain.doFilter(request, response);
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
| 1,978 | 0.72548 | 0.72548 | 75 | 25.346666 | 21.623131 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.746667 | false | false | 2 |
f06ba598367605a9031fcc5288caabc60afe5d42 | 15,977,278,397,046 | fadfc40528c5473c8454a4835ba534a83468bb3b | /domain-services/jbb-posting/src/main/java/org/jbb/posting/impl/base/PostRemoveHandler.java | fb77a2828523899ec71b33ac2dcc422a2b949136 | [
"Apache-2.0"
]
| permissive | jbb-project/jbb | https://github.com/jbb-project/jbb | 8d04e72b2f2d6c088b870e9a6c9dba8aa2e1768e | cefa12cda40804395b2d6e8bea0fb8352610b761 | refs/heads/develop | 2023-08-06T15:26:08.537000 | 2019-08-25T21:32:19 | 2019-08-25T21:32:19 | 60,918,871 | 4 | 3 | Apache-2.0 | false | 2023-09-01T22:21:04 | 2016-06-11T17:20:33 | 2020-08-03T22:00:17 | 2023-09-01T22:21:04 | 7,366 | 4 | 2 | 95 | Java | false | false | /*
* Copyright (C) 2019 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.posting.impl.base;
import org.jbb.lib.eventbus.JbbEventBus;
import org.jbb.posting.event.PostRemovedEvent;
import org.jbb.posting.event.TopicChangedEvent;
import org.jbb.posting.event.TopicRemovedEvent;
import org.jbb.posting.impl.base.dao.PostRepository;
import org.jbb.posting.impl.base.dao.TopicRepository;
import org.jbb.posting.impl.base.model.PostEntity;
import org.jbb.posting.impl.base.model.TopicEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class PostRemoveHandler {
private final PostRepository postRepository;
private final TopicRepository topicRepository;
private final JbbEventBus eventBus;
public void removePost(PostEntity postToRemove) {
TopicEntity topic = postToRemove.getTopic();
if (removingFirstPostOfTopic(topic, postToRemove)) {
updateTopicFirstPost(topic);
} else if (removingLastPostOfTopic(topic, postToRemove)) {
updateTopicLastPost(topic);
} else {
eventBus.post(new TopicChangedEvent(topic.getId()));
}
postRepository.delete(postToRemove);
eventBus.post(new PostRemovedEvent(postToRemove.getId(), topic.getId()));
}
private boolean removingFirstPostOfTopic(TopicEntity topic, PostEntity postToRemove) {
return topic.getFirstPost().getId().equals(postToRemove.getId());
}
private boolean removingLastPostOfTopic(TopicEntity topic, PostEntity postToRemove) {
return topic.getLastPost().getId().equals(postToRemove.getId());
}
private void updateTopicFirstPost(TopicEntity topic) {
Page<PostEntity> firstTwoPosts = postRepository
.findByTopic(topic, PageRequest.of(0, 2, Direction.ASC, "createDateTime"));
if (firstTwoPosts.getTotalElements() == 1) {
// remove topic
PostEntity lastPost = firstTwoPosts.getContent().get(0);
topicRepository.delete(topic);
eventBus
.post(new TopicRemovedEvent(topic.getId()));
} else {
// update first post
PostEntity secondPost = firstTwoPosts.getContent().get(1);
topic.setFirstPost(secondPost);
topicRepository.save(topic);
eventBus.post(new TopicChangedEvent(topic.getId()));
}
}
private void updateTopicLastPost(TopicEntity topic) {
Page<PostEntity> lastTwoPosts = postRepository
.findByTopic(topic, PageRequest.of(0, 2, Direction.DESC, "createDateTime"));
PostEntity lastButOnePost = lastTwoPosts.getContent().get(1);
topic.setLastPost(lastButOnePost);
topicRepository.save(topic);
eventBus.post(new TopicChangedEvent(topic.getId()));
}
}
| UTF-8 | Java | 3,242 | java | PostRemoveHandler.java | Java | []
| null | []
| /*
* Copyright (C) 2019 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.posting.impl.base;
import org.jbb.lib.eventbus.JbbEventBus;
import org.jbb.posting.event.PostRemovedEvent;
import org.jbb.posting.event.TopicChangedEvent;
import org.jbb.posting.event.TopicRemovedEvent;
import org.jbb.posting.impl.base.dao.PostRepository;
import org.jbb.posting.impl.base.dao.TopicRepository;
import org.jbb.posting.impl.base.model.PostEntity;
import org.jbb.posting.impl.base.model.TopicEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor
public class PostRemoveHandler {
private final PostRepository postRepository;
private final TopicRepository topicRepository;
private final JbbEventBus eventBus;
public void removePost(PostEntity postToRemove) {
TopicEntity topic = postToRemove.getTopic();
if (removingFirstPostOfTopic(topic, postToRemove)) {
updateTopicFirstPost(topic);
} else if (removingLastPostOfTopic(topic, postToRemove)) {
updateTopicLastPost(topic);
} else {
eventBus.post(new TopicChangedEvent(topic.getId()));
}
postRepository.delete(postToRemove);
eventBus.post(new PostRemovedEvent(postToRemove.getId(), topic.getId()));
}
private boolean removingFirstPostOfTopic(TopicEntity topic, PostEntity postToRemove) {
return topic.getFirstPost().getId().equals(postToRemove.getId());
}
private boolean removingLastPostOfTopic(TopicEntity topic, PostEntity postToRemove) {
return topic.getLastPost().getId().equals(postToRemove.getId());
}
private void updateTopicFirstPost(TopicEntity topic) {
Page<PostEntity> firstTwoPosts = postRepository
.findByTopic(topic, PageRequest.of(0, 2, Direction.ASC, "createDateTime"));
if (firstTwoPosts.getTotalElements() == 1) {
// remove topic
PostEntity lastPost = firstTwoPosts.getContent().get(0);
topicRepository.delete(topic);
eventBus
.post(new TopicRemovedEvent(topic.getId()));
} else {
// update first post
PostEntity secondPost = firstTwoPosts.getContent().get(1);
topic.setFirstPost(secondPost);
topicRepository.save(topic);
eventBus.post(new TopicChangedEvent(topic.getId()));
}
}
private void updateTopicLastPost(TopicEntity topic) {
Page<PostEntity> lastTwoPosts = postRepository
.findByTopic(topic, PageRequest.of(0, 2, Direction.DESC, "createDateTime"));
PostEntity lastButOnePost = lastTwoPosts.getContent().get(1);
topic.setLastPost(lastButOnePost);
topicRepository.save(topic);
eventBus.post(new TopicChangedEvent(topic.getId()));
}
}
| 3,242 | 0.703887 | 0.698951 | 85 | 37.141178 | 26.489134 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623529 | false | false | 2 |
8a24ce23d8f16d331d791cc100c95858e12123ff | 9,594,956,941,023 | a86377bb0c7931e64c68617cb5fadcc3ff42a698 | /src/com/huolong/xtsz/model/Kmfx.java | 9bb78cb886b3958e9d206778e3f1b7ca181dda56 | []
| no_license | luotianwen/account | https://github.com/luotianwen/account | 2f7a7a92aa66b8a8de0abf63df733ebb9aa858d7 | e943951f034e4b72d814b22c0edbe2ece228e908 | refs/heads/master | 2021-06-24T17:24:06.915000 | 2017-09-09T16:22:27 | 2017-09-09T16:22:27 | 102,968,531 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huolong.xtsz.model;
import java.io.Serializable;
public class Kmfx implements Serializable{
/**
* ½è·½
*/
public static final int KMFX_JF = 101400;
/**
* ´û·½
*/
public static final int KMFX_DF = 101401;
} | WINDOWS-1252 | Java | 241 | java | Kmfx.java | Java | []
| null | []
| package com.huolong.xtsz.model;
import java.io.Serializable;
public class Kmfx implements Serializable{
/**
* ½è·½
*/
public static final int KMFX_JF = 101400;
/**
* ´û·½
*/
public static final int KMFX_DF = 101401;
} | 241 | 0.669528 | 0.60515 | 16 | 13.625 | 16.31669 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 2 |
c83f725b644f314c41a0dfe0d9d3ad2553fb3b7b | 9,594,956,942,180 | 3e0b61454545475b9d9c0714c105fb224b7be79f | /app/src/main/java/users/UserPersonalData.java | 17eb0fa3c8281c318c251bf79aa9ca7d2aaeef14 | []
| no_license | FlaviusFUDULU/SmartMed | https://github.com/FlaviusFUDULU/SmartMed | 37c020764bf7be7eb5e0c7267b03967c2d21efd2 | 3d6d867aa3264856a3d10e558e2bfe3aa0cb98b7 | refs/heads/master | 2021-01-23T10:44:03.875000 | 2017-06-13T23:51:32 | 2017-06-13T23:51:32 | 93,088,234 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package users;
import java.io.Serializable;
import java.util.Vector;
/**
* Created by ffudulu on 06-Apr-17.
*/
public class UserPersonalData implements Serializable {
private String uId;
private String firstName;
private String lastName;
private String email;
private String cnp;
private String id;
private String age;
private String photoUrl;
private String sex;
private String address;
private String phoneNumber;
private String assuranceCode;
private String room;
private Vector<String> analisys;
private String dateOfAddmitance;
private String diagnostic;
private Vector<String> treatment;
public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,
String id, String age, String photoUrl, String address,
String phoneNumber, String assuranceCode, String dateOfAddmitance,
String sex, String room) {
this.uId = uId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.cnp = cnp;
this.id = id;
this.age = age;
this.photoUrl = photoUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.assuranceCode = assuranceCode;
this.dateOfAddmitance = dateOfAddmitance;
this.sex = sex;
this.room = room;
}
public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,
String id, String age, String photoUrl, String address,
String phoneNumber, String assuranceCode, String dateOfAddmitance,
String diagnostic, Vector<String> treatment, String sex, String room,
Vector<String> analisys) {
this.uId = uId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.cnp = cnp;
this.id = id;
this.age = age;
this.photoUrl = photoUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.assuranceCode = assuranceCode;
this.dateOfAddmitance = dateOfAddmitance;
this.diagnostic = diagnostic;
this.treatment = treatment;
this.sex = sex;
this.room = room;
this.analisys = analisys;
}
public UserPersonalData(String uId, String email) {
this.uId = uId;
this.email = email;
}
public UserPersonalData() {
}
public String getRoom() {
return room;
}
public Vector<String> getAnalisys() {
return analisys;
}
public String getSex() {
return sex;
}
public String getAddress() {
return address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getAssuranceCode() {
return assuranceCode;
}
public String getDateOfAddmitance() {
return dateOfAddmitance;
}
public String getDiagnostic() {
return diagnostic;
}
public Vector<String> getTreatment() {
return treatment;
}
public String getPhotoUrl() {
return photoUrl;
}
public String getuId() {
return uId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getCnp() {
return cnp;
}
public String getId() {
return id;
}
public String getAge() {
return age;
}
}
| UTF-8 | Java | 3,861 | java | UserPersonalData.java | Java | [
{
"context": "e;\r\nimport java.util.Vector;\r\n\r\n/**\r\n * Created by ffudulu on 06-Apr-17.\r\n */\r\npublic class UserPersonalData",
"end": 102,
"score": 0.998278796672821,
"start": 95,
"tag": "USERNAME",
"value": "ffudulu"
},
{
"context": "ble {\r\n private String uId;\r\n private String firstName;\r\n private String lastName;\r\n private Strin",
"end": 233,
"score": 0.9950405955314636,
"start": 224,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n private String firstName;\r\n private String lastName;\r\n private String email;\r\n private String c",
"end": 263,
"score": 0.9966922998428345,
"start": 255,
"tag": "NAME",
"value": "lastName"
},
{
"context": "\r\n\r\n public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,\r\n ",
"end": 752,
"score": 0.9989016056060791,
"start": 743,
"tag": "NAME",
"value": "firstName"
},
{
"context": "rPersonalData(String uId, String firstName, String lastName, String email, String cnp,\r\n ",
"end": 769,
"score": 0.9990334510803223,
"start": 761,
"tag": "NAME",
"value": "lastName"
},
{
"context": "\n this.uId = uId;\r\n this.firstName = firstName;\r\n this.lastName = lastName;\r\n this",
"end": 1094,
"score": 0.9994851350784302,
"start": 1085,
"tag": "NAME",
"value": "firstName"
},
{
"context": "is.firstName = firstName;\r\n this.lastName = lastName;\r\n this.email = email;\r\n this.cnp =",
"end": 1129,
"score": 0.9993895292282104,
"start": 1121,
"tag": "NAME",
"value": "lastName"
},
{
"context": "\r\n\r\n public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,\r\n ",
"end": 1556,
"score": 0.9989714026451111,
"start": 1547,
"tag": "NAME",
"value": "firstName"
},
{
"context": "rPersonalData(String uId, String firstName, String lastName, String email, String cnp,\r\n ",
"end": 1573,
"score": 0.9991253018379211,
"start": 1565,
"tag": "NAME",
"value": "lastName"
},
{
"context": "\n this.uId = uId;\r\n this.firstName = firstName;\r\n this.lastName = lastName;\r\n this",
"end": 1997,
"score": 0.9994981288909912,
"start": 1988,
"tag": "NAME",
"value": "firstName"
},
{
"context": "is.firstName = firstName;\r\n this.lastName = lastName;\r\n this.email = email;\r\n this.cnp =",
"end": 2032,
"score": 0.9994074106216431,
"start": 2024,
"tag": "NAME",
"value": "lastName"
}
]
| null | []
| package users;
import java.io.Serializable;
import java.util.Vector;
/**
* Created by ffudulu on 06-Apr-17.
*/
public class UserPersonalData implements Serializable {
private String uId;
private String firstName;
private String lastName;
private String email;
private String cnp;
private String id;
private String age;
private String photoUrl;
private String sex;
private String address;
private String phoneNumber;
private String assuranceCode;
private String room;
private Vector<String> analisys;
private String dateOfAddmitance;
private String diagnostic;
private Vector<String> treatment;
public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,
String id, String age, String photoUrl, String address,
String phoneNumber, String assuranceCode, String dateOfAddmitance,
String sex, String room) {
this.uId = uId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.cnp = cnp;
this.id = id;
this.age = age;
this.photoUrl = photoUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.assuranceCode = assuranceCode;
this.dateOfAddmitance = dateOfAddmitance;
this.sex = sex;
this.room = room;
}
public UserPersonalData(String uId, String firstName, String lastName, String email, String cnp,
String id, String age, String photoUrl, String address,
String phoneNumber, String assuranceCode, String dateOfAddmitance,
String diagnostic, Vector<String> treatment, String sex, String room,
Vector<String> analisys) {
this.uId = uId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.cnp = cnp;
this.id = id;
this.age = age;
this.photoUrl = photoUrl;
this.address = address;
this.phoneNumber = phoneNumber;
this.assuranceCode = assuranceCode;
this.dateOfAddmitance = dateOfAddmitance;
this.diagnostic = diagnostic;
this.treatment = treatment;
this.sex = sex;
this.room = room;
this.analisys = analisys;
}
public UserPersonalData(String uId, String email) {
this.uId = uId;
this.email = email;
}
public UserPersonalData() {
}
public String getRoom() {
return room;
}
public Vector<String> getAnalisys() {
return analisys;
}
public String getSex() {
return sex;
}
public String getAddress() {
return address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getAssuranceCode() {
return assuranceCode;
}
public String getDateOfAddmitance() {
return dateOfAddmitance;
}
public String getDiagnostic() {
return diagnostic;
}
public Vector<String> getTreatment() {
return treatment;
}
public String getPhotoUrl() {
return photoUrl;
}
public String getuId() {
return uId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getCnp() {
return cnp;
}
public String getId() {
return id;
}
public String getAge() {
return age;
}
}
| 3,861 | 0.570578 | 0.569542 | 151 | 23.569536 | 21.293755 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662252 | false | false | 2 |
fda51207b8535282dd7fd0c3ed31a03142d37fba | 9,594,956,943,172 | d1dd99b98a40d6f7cb484ef27be3a44ad9a711a4 | /GerenciamentoMemoria/src/SegundaChance/Processo.java | 98c448c5058ef2724e7824c9f0d07b9359f740be | []
| no_license | AmauryTavares/GerenciamentoMemoria | https://github.com/AmauryTavares/GerenciamentoMemoria | 20f23b75c291d2d7c81d596513bd591306a917ab | 35e5d5e28eabf10db893e2ee1b81ab01e128aa51 | refs/heads/master | 2020-04-04T17:19:49.964000 | 2018-11-13T01:54:48 | 2018-11-13T01:54:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package SegundaChance;
import java.util.ArrayList;
import java.util.Random;
public class Processo extends Thread{
private int numProcesso;
private ArrayList<Integer> paginasVituais;
private String estado;
public Processo(int numProcesso, ArrayList<Integer> paginasVituais, String estado) {
this.numProcesso = numProcesso;
this.paginasVituais = paginasVituais;
this.estado = estado;
printarInicio();
}
private void printarInicio() {
String texto = "Processo " + this.numProcesso + " criado, paginas virtuais: ";
for (int i : paginasVituais) {
texto += i + " ";
}
System.out.println(texto);
}
@Override
public void run() {
System.out.println("Processo " + numProcesso + " iniciado!");
Random rand = new Random();
for (int i = 0; i < 10; i++) {
try {
int paginaSelecionada = paginasVituais.get(rand.nextInt(paginasVituais.size()));
System.out.println("O Processo " + numProcesso + " solicitou a pagina virtual " + paginaSelecionada + " .");
CPU.requisitar(paginaSelecionada, numProcesso);
Thread.sleep(rand.nextInt(3000) + 800); // tempo processando
} catch (InterruptedException e) {
e.printStackTrace();
}
}
estado = "encerrado";
System.out.println("Processo " + numProcesso + " encerrado!");
}
public int getNumProcesso() {
return numProcesso;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| UTF-8 | Java | 1,533 | java | Processo.java | Java | []
| null | []
| package SegundaChance;
import java.util.ArrayList;
import java.util.Random;
public class Processo extends Thread{
private int numProcesso;
private ArrayList<Integer> paginasVituais;
private String estado;
public Processo(int numProcesso, ArrayList<Integer> paginasVituais, String estado) {
this.numProcesso = numProcesso;
this.paginasVituais = paginasVituais;
this.estado = estado;
printarInicio();
}
private void printarInicio() {
String texto = "Processo " + this.numProcesso + " criado, paginas virtuais: ";
for (int i : paginasVituais) {
texto += i + " ";
}
System.out.println(texto);
}
@Override
public void run() {
System.out.println("Processo " + numProcesso + " iniciado!");
Random rand = new Random();
for (int i = 0; i < 10; i++) {
try {
int paginaSelecionada = paginasVituais.get(rand.nextInt(paginasVituais.size()));
System.out.println("O Processo " + numProcesso + " solicitou a pagina virtual " + paginaSelecionada + " .");
CPU.requisitar(paginaSelecionada, numProcesso);
Thread.sleep(rand.nextInt(3000) + 800); // tempo processando
} catch (InterruptedException e) {
e.printStackTrace();
}
}
estado = "encerrado";
System.out.println("Processo " + numProcesso + " encerrado!");
}
public int getNumProcesso() {
return numProcesso;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| 1,533 | 0.654273 | 0.647749 | 63 | 22.333334 | 24.809752 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.047619 | false | false | 2 |
dfa07d4cc410e56f9a76bff54498f79c2dcabd1f | 21,157,008,904,631 | b634de75a070612d159c91865872a38ce4333718 | /kie-spring/src/main/java/org/kie/spring/persistence/AbstractKieSpringJpaManager.java | eb1aeaca4c87d6c02a9b574cd259e6d34c7ed3e8 | [
"Apache-2.0"
]
| permissive | garmanli/droolsjbpm-integration | https://github.com/garmanli/droolsjbpm-integration | 2b9046a0d65269cc7b0f470826a181e714e07413 | 4fb2e41a776546b7251c932fb2f1abbf57861c2c | refs/heads/master | 2021-01-23T20:40:11.341000 | 2014-08-12T16:00:45 | 2014-08-12T16:00:45 | 23,016,006 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2010 JBoss Inc
*
* 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 org.kie.spring.persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.drools.persistence.PersistenceContext;
import org.drools.persistence.jpa.JpaPersistenceContext;
import org.jbpm.persistence.JpaProcessPersistenceContext;
import org.jbpm.persistence.ProcessPersistenceContext;
import org.jbpm.persistence.ProcessPersistenceContextManager;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public abstract class AbstractKieSpringJpaManager
{
Logger logger = LoggerFactory.getLogger(getClass());
protected Environment env;
protected EntityManagerFactory emf;
protected EntityManager appScopedEntityManager;
protected boolean internalAppScopedEntityManager;
protected boolean isJTA;
public AbstractKieSpringJpaManager(Environment env) {
this.env = env;
this.emf = (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
isJTA = true;
Boolean bool = (Boolean) env.get("IS_JTA_TRANSACTION");
if (bool != null) {
isJTA = bool.booleanValue();
}
}
public EntityManager getApplicationScopedEntityManager() {
if (this.appScopedEntityManager == null) {
// Use the App scoped EntityManager if the user has provided it, and it is open.
this.appScopedEntityManager = (EntityManager) this.env.get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
if (this.appScopedEntityManager != null && !this.appScopedEntityManager.isOpen()) {
throw new RuntimeException("Provided APP_SCOPED_ENTITY_MANAGER is not open");
}
if (this.appScopedEntityManager == null) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(this.emf);
if (emHolder == null) {
this.appScopedEntityManager = this.emf.createEntityManager();
emHolder = new EntityManagerHolder(this.appScopedEntityManager);
TransactionSynchronizationManager.bindResource(this.emf, emHolder);
internalAppScopedEntityManager = true;
} else {
this.appScopedEntityManager = emHolder.getEntityManager();
}
this.env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER,
emHolder.getEntityManager());
}
}
if (TransactionSynchronizationManager.isActualTransactionActive() && isJTA) {
this.appScopedEntityManager.joinTransaction();
}
return this.appScopedEntityManager;
}
public EntityManager getCommandScopedEntityManager() {
EntityManager cmdScopedEntityManager = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
if (cmdScopedEntityManager == null || !cmdScopedEntityManager.isOpen()) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource("cmdEM");
EntityManager em = null;
if (emHolder == null) {
em = this.emf.createEntityManager();
emHolder = new EntityManagerHolder(em);
TransactionSynchronizationManager.bindResource("cmdEM", emHolder);
} else {
em = emHolder.getEntityManager();
}
this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, em);
}
return cmdScopedEntityManager;
}
public abstract void endCommandScopedEntityManager();
public void dispose() {
logger.trace("Disposing KieSpringJpaManager");
if (internalAppScopedEntityManager) {
//TransactionSynchronizationManager.unbindResource( "appEM" );
TransactionSynchronizationManager.unbindResource(this.emf);
if (this.appScopedEntityManager != null && this.appScopedEntityManager.isOpen()) {
this.appScopedEntityManager.close();
this.internalAppScopedEntityManager = false;
this.env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER,
null);
this.appScopedEntityManager = null;
}
this.endCommandScopedEntityManager();
}
}
}
| UTF-8 | Java | 5,139 | java | AbstractKieSpringJpaManager.java | Java | []
| null | []
| /*
* Copyright 2010 JBoss Inc
*
* 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 org.kie.spring.persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.drools.persistence.PersistenceContext;
import org.drools.persistence.jpa.JpaPersistenceContext;
import org.jbpm.persistence.JpaProcessPersistenceContext;
import org.jbpm.persistence.ProcessPersistenceContext;
import org.jbpm.persistence.ProcessPersistenceContextManager;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public abstract class AbstractKieSpringJpaManager
{
Logger logger = LoggerFactory.getLogger(getClass());
protected Environment env;
protected EntityManagerFactory emf;
protected EntityManager appScopedEntityManager;
protected boolean internalAppScopedEntityManager;
protected boolean isJTA;
public AbstractKieSpringJpaManager(Environment env) {
this.env = env;
this.emf = (EntityManagerFactory) env.get(EnvironmentName.ENTITY_MANAGER_FACTORY);
isJTA = true;
Boolean bool = (Boolean) env.get("IS_JTA_TRANSACTION");
if (bool != null) {
isJTA = bool.booleanValue();
}
}
public EntityManager getApplicationScopedEntityManager() {
if (this.appScopedEntityManager == null) {
// Use the App scoped EntityManager if the user has provided it, and it is open.
this.appScopedEntityManager = (EntityManager) this.env.get(EnvironmentName.APP_SCOPED_ENTITY_MANAGER);
if (this.appScopedEntityManager != null && !this.appScopedEntityManager.isOpen()) {
throw new RuntimeException("Provided APP_SCOPED_ENTITY_MANAGER is not open");
}
if (this.appScopedEntityManager == null) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(this.emf);
if (emHolder == null) {
this.appScopedEntityManager = this.emf.createEntityManager();
emHolder = new EntityManagerHolder(this.appScopedEntityManager);
TransactionSynchronizationManager.bindResource(this.emf, emHolder);
internalAppScopedEntityManager = true;
} else {
this.appScopedEntityManager = emHolder.getEntityManager();
}
this.env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER,
emHolder.getEntityManager());
}
}
if (TransactionSynchronizationManager.isActualTransactionActive() && isJTA) {
this.appScopedEntityManager.joinTransaction();
}
return this.appScopedEntityManager;
}
public EntityManager getCommandScopedEntityManager() {
EntityManager cmdScopedEntityManager = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
if (cmdScopedEntityManager == null || !cmdScopedEntityManager.isOpen()) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.getResource("cmdEM");
EntityManager em = null;
if (emHolder == null) {
em = this.emf.createEntityManager();
emHolder = new EntityManagerHolder(em);
TransactionSynchronizationManager.bindResource("cmdEM", emHolder);
} else {
em = emHolder.getEntityManager();
}
this.env.set(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, em);
}
return cmdScopedEntityManager;
}
public abstract void endCommandScopedEntityManager();
public void dispose() {
logger.trace("Disposing KieSpringJpaManager");
if (internalAppScopedEntityManager) {
//TransactionSynchronizationManager.unbindResource( "appEM" );
TransactionSynchronizationManager.unbindResource(this.emf);
if (this.appScopedEntityManager != null && this.appScopedEntityManager.isOpen()) {
this.appScopedEntityManager.close();
this.internalAppScopedEntityManager = false;
this.env.set(EnvironmentName.APP_SCOPED_ENTITY_MANAGER,
null);
this.appScopedEntityManager = null;
}
this.endCommandScopedEntityManager();
}
}
}
| 5,139 | 0.680677 | 0.678731 | 125 | 40.112 | 31.909676 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536 | false | false | 2 |
fe7027676c97394acbbb267bf4c2380dee9f6d12 | 94,489,288,784 | c01d2d124b1072e17c06e73307fd92f656d99f69 | /src/main/java/al/tonikolaba/handlers/Content.java | 7f89534f06595abbebbc80c5ba2de6eb639bde2b | [
"MIT"
]
| permissive | tonikolaba/BatBat-Game | https://github.com/tonikolaba/BatBat-Game | 85984f6995b77297847b2f721a9dfd8c40dbbbec | 868737de84cb00d5a303e0c9486f148d1ef75c23 | refs/heads/master | 2023-08-05T08:50:35.108000 | 2022-10-04T19:01:50 | 2022-10-04T19:01:50 | 91,010,224 | 18 | 36 | MIT | false | 2023-07-25T05:06:28 | 2017-05-11T18:15:51 | 2023-06-21T18:43:26 | 2023-07-25T05:06:28 | 4,343 | 17 | 34 | 1 | Java | false | false | package al.tonikolaba.handlers;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
/**
* @author ArtOfSoul
*/
// this class loads resources on boot.
// spritesheets are taken from here.
public class Content {
private static final BufferedImage[][] ENERGY_PARTICLE = load("/Sprites/Player/EnergyParticle.gif", 5, 5);
private static final BufferedImage[][] EXPLOSIONS = load("/Sprites/Enemies/ExplosionRed.gif", 30, 30);
private static final BufferedImage[][] ZOGU = load("/Sprites/Enemies/Zogu.gif", 39, 20);
private static final BufferedImage[][] UFO = load("/Sprites/Enemies/Ufo.gif", 30, 30);
private static final BufferedImage[][] XHELBAT = load("/Sprites/Enemies/XhelBat.gif", 25, 25);
private static final BufferedImage[][] RED_ENERGY = load("/Sprites/Enemies/RedEnergy.gif", 20, 20);
private Content() {
throw new IllegalStateException("Utility Class");
}
public static BufferedImage[][] load(String s, int w, int h) {
BufferedImage[][] ret;
try {
BufferedImage spritesheet = ImageIO.read(Content.class.getResourceAsStream(s));
int width = spritesheet.getWidth() / w;
int height = spritesheet.getHeight() / h;
ret = new BufferedImage[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
ret[i][j] = spritesheet.getSubimage(j * w, i * h, w, h);
}
}
return ret;
} catch (Exception e) {
LoggingHelper.LOGGER.log(Level.SEVERE, e.getMessage());
System.exit(0);
}
return new BufferedImage[0][0];
}
public static BufferedImage[][] getEnergyParticle() {
return ENERGY_PARTICLE;
}
public static BufferedImage[][] getExplosions() {
return EXPLOSIONS;
}
public static BufferedImage[][] getZogu() {
return ZOGU;
}
public static BufferedImage[][] getUfo() {
return UFO;
}
public static BufferedImage[][] getXhelbat() {
return XHELBAT;
}
public static BufferedImage[][] getRedEnergy() {
return RED_ENERGY;
}
}
| UTF-8 | Java | 2,243 | java | Content.java | Java | [
{
"context": "e;\nimport java.util.logging.Level;\n\n/**\n * @author ArtOfSoul\n */\n\n// this class loads resources on boot.\n// sp",
"end": 157,
"score": 0.6162592172622681,
"start": 148,
"tag": "NAME",
"value": "ArtOfSoul"
}
]
| null | []
| package al.tonikolaba.handlers;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
/**
* @author ArtOfSoul
*/
// this class loads resources on boot.
// spritesheets are taken from here.
public class Content {
private static final BufferedImage[][] ENERGY_PARTICLE = load("/Sprites/Player/EnergyParticle.gif", 5, 5);
private static final BufferedImage[][] EXPLOSIONS = load("/Sprites/Enemies/ExplosionRed.gif", 30, 30);
private static final BufferedImage[][] ZOGU = load("/Sprites/Enemies/Zogu.gif", 39, 20);
private static final BufferedImage[][] UFO = load("/Sprites/Enemies/Ufo.gif", 30, 30);
private static final BufferedImage[][] XHELBAT = load("/Sprites/Enemies/XhelBat.gif", 25, 25);
private static final BufferedImage[][] RED_ENERGY = load("/Sprites/Enemies/RedEnergy.gif", 20, 20);
private Content() {
throw new IllegalStateException("Utility Class");
}
public static BufferedImage[][] load(String s, int w, int h) {
BufferedImage[][] ret;
try {
BufferedImage spritesheet = ImageIO.read(Content.class.getResourceAsStream(s));
int width = spritesheet.getWidth() / w;
int height = spritesheet.getHeight() / h;
ret = new BufferedImage[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
ret[i][j] = spritesheet.getSubimage(j * w, i * h, w, h);
}
}
return ret;
} catch (Exception e) {
LoggingHelper.LOGGER.log(Level.SEVERE, e.getMessage());
System.exit(0);
}
return new BufferedImage[0][0];
}
public static BufferedImage[][] getEnergyParticle() {
return ENERGY_PARTICLE;
}
public static BufferedImage[][] getExplosions() {
return EXPLOSIONS;
}
public static BufferedImage[][] getZogu() {
return ZOGU;
}
public static BufferedImage[][] getUfo() {
return UFO;
}
public static BufferedImage[][] getXhelbat() {
return XHELBAT;
}
public static BufferedImage[][] getRedEnergy() {
return RED_ENERGY;
}
}
| 2,243 | 0.609006 | 0.596968 | 72 | 30.152779 | 30.345079 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.680556 | false | false | 2 |
ec8a174a4093bb15d3d1d6beff5202a124a09795 | 32,899,449,515,461 | 4db048132ade6f26a079f47900a4f655faf6ef04 | /JiraPlugins/atlassian-jira-5.1.1-source/streams-api/src/main/java/com/atlassian/streams/api/renderer/StreamsEntryRendererFactory.java | 36cff2d4dfdbb5c2555da3575ab307bff8e20fd0 | []
| no_license | JCVI-VIRIFX/SampleTracking | https://github.com/JCVI-VIRIFX/SampleTracking | 045f3a690161cd6735dda6cf53964a89910c2d32 | 8f68cf385a083dcef055605dc040a224576a16fe | refs/heads/master | 2018-01-07T23:30:42.211000 | 2015-12-11T04:23:38 | 2015-12-11T04:23:38 | 47,804,829 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.atlassian.streams.api.renderer;
import java.net.URI;
import com.atlassian.streams.api.Html;
import com.atlassian.streams.api.StreamsEntry;
import com.atlassian.streams.api.StreamsEntry.ActivityObject;
import com.atlassian.streams.api.StreamsEntry.Renderer;
import com.atlassian.streams.api.UserProfile;
import com.atlassian.streams.api.common.Option;
import com.google.common.base.Function;
/**
* Factory to create {@link StreamsEntry.Renderer}s for some common types of activity entries.
*/
public interface StreamsEntryRendererFactory
{
/**
* Creates a {@code StreamsEntry.Renderer} for a comment entry. Uses {@code comment} as the content of the entry.
*
* @param comment comment to use as the content of the entry
* @return renderer for the comment
*/
Renderer newCommentRenderer(String comment);
Renderer newCommentRenderer(Html comment);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, String message);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, Html message);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, Html apply, Option<URI> styleLink);
Function<StreamsEntry, Html> newCommentTitleRenderer();
Function<StreamsEntry, Html> newTitleRenderer(String key);
Function<StreamsEntry, Html> newTitleRenderer(String key,
Function<Iterable<UserProfile>, Html> authorsRenderer,
Option<Function<Iterable<ActivityObject>, Option<Html>>> activityObjectRenderer,
Option<Function<ActivityObject, Option<Html>>> targetRenderer);
Function<Iterable<UserProfile>, Html> newAuthorsRenderer();
Function<Iterable<UserProfile>, Html> newUserProfileRenderer();
Function<Iterable<ActivityObject>, Option<Html>> newActivityObjectsRenderer();
Function<Iterable<ActivityObject>, Option<Html>> newActivityObjectsRenderer(Function<ActivityObject, Option<Html>> objectRenderer);
Function<ActivityObject, Option<Html>> newActivityObjectRendererWithSummary();
Function<ActivityObject, Option<Html>> newActivityObjectRendererWithoutSummary();
<T> Function<Iterable<T>, Option<Html>> newCompoundStatementRenderer(Function<T, Option<Html>> render);
}
| UTF-8 | Java | 2,258 | java | StreamsEntryRendererFactory.java | Java | []
| null | []
| package com.atlassian.streams.api.renderer;
import java.net.URI;
import com.atlassian.streams.api.Html;
import com.atlassian.streams.api.StreamsEntry;
import com.atlassian.streams.api.StreamsEntry.ActivityObject;
import com.atlassian.streams.api.StreamsEntry.Renderer;
import com.atlassian.streams.api.UserProfile;
import com.atlassian.streams.api.common.Option;
import com.google.common.base.Function;
/**
* Factory to create {@link StreamsEntry.Renderer}s for some common types of activity entries.
*/
public interface StreamsEntryRendererFactory
{
/**
* Creates a {@code StreamsEntry.Renderer} for a comment entry. Uses {@code comment} as the content of the entry.
*
* @param comment comment to use as the content of the entry
* @return renderer for the comment
*/
Renderer newCommentRenderer(String comment);
Renderer newCommentRenderer(Html comment);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, String message);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, Html message);
Renderer newCommentRenderer(Function<StreamsEntry, Html> titleRenderer, Html apply, Option<URI> styleLink);
Function<StreamsEntry, Html> newCommentTitleRenderer();
Function<StreamsEntry, Html> newTitleRenderer(String key);
Function<StreamsEntry, Html> newTitleRenderer(String key,
Function<Iterable<UserProfile>, Html> authorsRenderer,
Option<Function<Iterable<ActivityObject>, Option<Html>>> activityObjectRenderer,
Option<Function<ActivityObject, Option<Html>>> targetRenderer);
Function<Iterable<UserProfile>, Html> newAuthorsRenderer();
Function<Iterable<UserProfile>, Html> newUserProfileRenderer();
Function<Iterable<ActivityObject>, Option<Html>> newActivityObjectsRenderer();
Function<Iterable<ActivityObject>, Option<Html>> newActivityObjectsRenderer(Function<ActivityObject, Option<Html>> objectRenderer);
Function<ActivityObject, Option<Html>> newActivityObjectRendererWithSummary();
Function<ActivityObject, Option<Html>> newActivityObjectRendererWithoutSummary();
<T> Function<Iterable<T>, Option<Html>> newCompoundStatementRenderer(Function<T, Option<Html>> render);
}
| 2,258 | 0.771036 | 0.771036 | 54 | 40.814816 | 38.591438 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.907407 | false | false | 2 |
ffcea427069842b3cc957a74198c73830e17864e | 13,812,614,853,646 | 5cd55da8db5b2cd58a231ecb2b797f27ed7294a3 | /src/cn/edu/njnu/viewmodel/OrderDetailViewModel.java | 85bdc27eb7f49f220c02067b740beec284e73796 | []
| no_license | zshellzhang1993-2025/SaleSystem | https://github.com/zshellzhang1993-2025/SaleSystem | 931f26b93afef1d2dd3ecb0e9e8daa7b397a8459 | 630f71abe63dd41c22ae1158ba024cd157d338ed | refs/heads/master | 2021-05-29T02:04:09.801000 | 2015-07-06T16:02:38 | 2015-07-06T16:02:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.njnu.viewmodel;
import java.sql.Timestamp;
/**
* 订单详情模型,用于读数据库
*/
public class OrderDetailViewModel {
// 订单号
private int id;
// 下单时间
private Timestamp createtime;
// 联系电话
private String phone;
// 总价
private double price;
// 购买商品详情
private ShoppingDetail[] shoppingDetail;
public OrderDetailViewModel(int id, Timestamp createtime, String phone,
double price, ShoppingDetail[] shoppingDetail) {
this.id = id;
this.createtime = createtime;
this.phone = phone;
this.price = price;
this.shoppingDetail = shoppingDetail;
}
/* setter and getter for every member */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getCreatetime() {
return createtime;
}
public void setCreatetime(Timestamp createtime) {
this.createtime = createtime;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public ShoppingDetail[] getGoodsDetail() {
return shoppingDetail;
}
public void setGoodsDetail(ShoppingDetail[] shoppingDetail) {
this.shoppingDetail = shoppingDetail;
}
}
| UTF-8 | Java | 1,397 | java | OrderDetailViewModel.java | Java | []
| null | []
| package cn.edu.njnu.viewmodel;
import java.sql.Timestamp;
/**
* 订单详情模型,用于读数据库
*/
public class OrderDetailViewModel {
// 订单号
private int id;
// 下单时间
private Timestamp createtime;
// 联系电话
private String phone;
// 总价
private double price;
// 购买商品详情
private ShoppingDetail[] shoppingDetail;
public OrderDetailViewModel(int id, Timestamp createtime, String phone,
double price, ShoppingDetail[] shoppingDetail) {
this.id = id;
this.createtime = createtime;
this.phone = phone;
this.price = price;
this.shoppingDetail = shoppingDetail;
}
/* setter and getter for every member */
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getCreatetime() {
return createtime;
}
public void setCreatetime(Timestamp createtime) {
this.createtime = createtime;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public ShoppingDetail[] getGoodsDetail() {
return shoppingDetail;
}
public void setGoodsDetail(ShoppingDetail[] shoppingDetail) {
this.shoppingDetail = shoppingDetail;
}
}
| 1,397 | 0.663916 | 0.663916 | 77 | 15.311688 | 17.018141 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.220779 | false | false | 2 |
2a66fcca2d825c27509eaf983899eaa22a5947fd | 4,526,895,569,223 | db06fe185deca2104116e184463e40994d41375b | /src/PersonaApp/PersonaOperations.java | 3ed5c72e316618e5345da6e6032c29df3e6f6741 | []
| no_license | Alejandro120/Corba | https://github.com/Alejandro120/Corba | 9fb977ef3863681bb7f333e7f69ae51db09d31e0 | 171628cb4391ca5bee87dec9822089c1f276f120 | refs/heads/master | 2020-05-18T04:01:27.073000 | 2019-04-30T01:06:59 | 2019-04-30T01:06:59 | 184,162,475 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PersonaApp;
/**
* PersonaApp/PersonaOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Persona.idl
* lunes 22 de abril de 2019 07:40:06 PM COT
*/
public interface PersonaOperations
{
boolean insertarPersona (int identificacion, String nombre, String apellido, String direccion, String telefono, String email);
String consultarPersona (int identificacion);
boolean actualizarPersona (int identificacion, String nombre, String apellido, String direccion, String telefono, String email);
boolean eliminarPersona (int identificacion);
String listarPersonas ();
void shutdown ();
} // interface PersonaOperations
| UTF-8 | Java | 691 | java | PersonaOperations.java | Java | []
| null | []
| package PersonaApp;
/**
* PersonaApp/PersonaOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Persona.idl
* lunes 22 de abril de 2019 07:40:06 PM COT
*/
public interface PersonaOperations
{
boolean insertarPersona (int identificacion, String nombre, String apellido, String direccion, String telefono, String email);
String consultarPersona (int identificacion);
boolean actualizarPersona (int identificacion, String nombre, String apellido, String direccion, String telefono, String email);
boolean eliminarPersona (int identificacion);
String listarPersonas ();
void shutdown ();
} // interface PersonaOperations
| 691 | 0.75398 | 0.733719 | 19 | 34.36842 | 37.515205 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.947368 | false | false | 2 |
796ed24f8ba0f4d281ee2b47ae24bf8a0373e5cb | 14,439,680,108,178 | 60e27f061784e1e4ade229ce33a8c2c9814f1ef8 | /code/src/main/java/nl/rubend/clonebook/rest/ChatService.java | a370c012d1358e6f82cfae60bae15cb357b9e7e0 | []
| no_license | RubenNL/clonebook | https://github.com/RubenNL/clonebook | 4def5b68be20dcd0305317e4689c317870c84247 | be941acdb04fbadd8982c08f91b645ee79a3dc9c | refs/heads/master | 2023-03-07T00:41:47.455000 | 2020-10-30T19:30:44 | 2020-10-30T19:30:44 | 257,590,951 | 0 | 2 | null | false | 2021-01-04T17:47:18 | 2020-04-21T12:37:50 | 2020-11-01T09:19:30 | 2020-11-09T18:42:37 | 2,623 | 0 | 1 | 2 | Java | false | false | package nl.rubend.clonebook.rest;
import nl.rubend.clonebook.domain.Chat;
import nl.rubend.clonebook.domain.Page;
import nl.rubend.clonebook.domain.Post;
import nl.rubend.clonebook.domain.User;
import nl.rubend.clonebook.exceptions.ClonebookException;
import nl.rubend.clonebook.security.SecurityBean;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.AbstractMap;
import java.util.Date;
@Path("/chat")
@RolesAllowed("user")
@Produces(MediaType.APPLICATION_JSON)
public class ChatService {
@GET
public Response getChats(@BeanParam SecurityBean securityBean) {
return Response.ok(Chat.getChats(securityBean.getSender())).build();
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response newChat(@BeanParam SecurityBean securityBean,@FormParam("user") String otherUser) {
Chat chat = new Chat(securityBean.getSender(), User.getUserById(otherUser));
return Response.ok(new AbstractMap.SimpleEntry<String, String>("id", chat.getId())).build();
}
@GET
@Path("/{chatId}")
public Response getChat(@BeanParam Bean bean) {
return Response.ok(bean.onlyLid().getChat()).build();
}
@GET
@Path("/{chatId}/{before}")
public Response getChatAfter(@BeanParam Bean bean,@PathParam("before") String before) {
return Response.ok(bean.onlyLid().getChat().getMessagesBefore(new Date(Long.parseLong(before)))).build();
}
@POST
@Path("/{chatId}")
public Response sendMessage(@BeanParam Bean bean, @BeanParam SecurityBean securityBean,@FormParam("message") String message) {
bean.onlyLid().getChat().sendMessage(securityBean.getSender(),message);
return Response.ok().build();
}
static class Bean {
@PathParam("chatId") String chatId;
@BeanParam SecurityBean securityBean;
Chat getChat() {
return Chat.getChat(chatId);
}
boolean hasAccess() {
return getChat().getUsers().contains(securityBean.getSender());
}
Bean onlyLid() {
if(!hasAccess()) throw new ClonebookException(Response.Status.FORBIDDEN,"geen toegang");
return this;
}
}
}
| UTF-8 | Java | 2,097 | java | ChatService.java | Java | []
| null | []
| package nl.rubend.clonebook.rest;
import nl.rubend.clonebook.domain.Chat;
import nl.rubend.clonebook.domain.Page;
import nl.rubend.clonebook.domain.Post;
import nl.rubend.clonebook.domain.User;
import nl.rubend.clonebook.exceptions.ClonebookException;
import nl.rubend.clonebook.security.SecurityBean;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.AbstractMap;
import java.util.Date;
@Path("/chat")
@RolesAllowed("user")
@Produces(MediaType.APPLICATION_JSON)
public class ChatService {
@GET
public Response getChats(@BeanParam SecurityBean securityBean) {
return Response.ok(Chat.getChats(securityBean.getSender())).build();
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response newChat(@BeanParam SecurityBean securityBean,@FormParam("user") String otherUser) {
Chat chat = new Chat(securityBean.getSender(), User.getUserById(otherUser));
return Response.ok(new AbstractMap.SimpleEntry<String, String>("id", chat.getId())).build();
}
@GET
@Path("/{chatId}")
public Response getChat(@BeanParam Bean bean) {
return Response.ok(bean.onlyLid().getChat()).build();
}
@GET
@Path("/{chatId}/{before}")
public Response getChatAfter(@BeanParam Bean bean,@PathParam("before") String before) {
return Response.ok(bean.onlyLid().getChat().getMessagesBefore(new Date(Long.parseLong(before)))).build();
}
@POST
@Path("/{chatId}")
public Response sendMessage(@BeanParam Bean bean, @BeanParam SecurityBean securityBean,@FormParam("message") String message) {
bean.onlyLid().getChat().sendMessage(securityBean.getSender(),message);
return Response.ok().build();
}
static class Bean {
@PathParam("chatId") String chatId;
@BeanParam SecurityBean securityBean;
Chat getChat() {
return Chat.getChat(chatId);
}
boolean hasAccess() {
return getChat().getUsers().contains(securityBean.getSender());
}
Bean onlyLid() {
if(!hasAccess()) throw new ClonebookException(Response.Status.FORBIDDEN,"geen toegang");
return this;
}
}
}
| 2,097 | 0.75298 | 0.75298 | 61 | 33.377048 | 30.584023 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.606557 | false | false | 2 |
87bec30adfa5b5fc59bdf9dd7946fe629d96eb4d | 14,439,680,108,439 | 8e27f20129d61a114f366f2cef2654bb21fa2695 | /SimpleCRM/code/CRM/src/main/java/com/vin/crm/utils/MyTag.java | 8fee3023f3e8ea003c6eb6b532393268047d3b30 | []
| no_license | VintageProgram/CRM | https://github.com/VintageProgram/CRM | 3545f4e66753cefa804218fedcfd775289e7a895 | c14648fe966be7f9b3ca5c383bbc581a5c35befb | refs/heads/master | 2020-03-26T14:48:28.717000 | 2018-08-16T15:23:15 | 2018-08-16T15:23:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vin.crm.utils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/*自定义标签测试*/
public class MyTag extends TagSupport {
/**
* 针对某一标签的属性,名称需要一致,如何在页面设置了某个属性,则必须给该属性创建一个setter方法
*/
private String url="";
private String bean="";
private String number="";
static final long serialVersionUID = 2372405317744358833L;
@Override
public int doStartTag() throws JspException {
JspWriter out = super.pageContext.getOut();
try {
out.print("<span>这是自定义标签输出的内容"+url+"</span>");
out.print("<h1>这是自定义标签输出的大标题</h1>");
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
System.out.println("url: "+url);
}
public String getBean() {
return bean;
}
public void setBean(String bean) {
this.bean = bean;
System.out.println(bean);
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
System.out.println("number: "+number);
}
}
| GB18030 | Java | 1,379 | java | MyTag.java | Java | []
| null | []
| package com.vin.crm.utils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/*自定义标签测试*/
public class MyTag extends TagSupport {
/**
* 针对某一标签的属性,名称需要一致,如何在页面设置了某个属性,则必须给该属性创建一个setter方法
*/
private String url="";
private String bean="";
private String number="";
static final long serialVersionUID = 2372405317744358833L;
@Override
public int doStartTag() throws JspException {
JspWriter out = super.pageContext.getOut();
try {
out.print("<span>这是自定义标签输出的内容"+url+"</span>");
out.print("<h1>这是自定义标签输出的大标题</h1>");
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
System.out.println("url: "+url);
}
public String getBean() {
return bean;
}
public void setBean(String bean) {
this.bean = bean;
System.out.println(bean);
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
System.out.println("number: "+number);
}
}
| 1,379 | 0.701383 | 0.684296 | 64 | 18.203125 | 17.019455 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.390625 | false | false | 2 |
490b85348023a29fac3576ea792ec30c8075781f | 32,031,866,138,340 | 53d34013c0bd31bcf236c64f9f5f83ee70cab6d9 | /Leaderboard.java | 9598b5be8c0e761e62bce3f6a1fa12cbc98d7cc7 | []
| no_license | Kartik1411/Hacker_Rank_Problem_Solving | https://github.com/Kartik1411/Hacker_Rank_Problem_Solving | 83adfd96b1711a01417f926b232edaeb721b7954 | 4d8729d9974ca6b3801e5f19cac9a570fb3dd513 | refs/heads/master | 2022-07-04T16:37:54.097000 | 2020-05-20T17:20:52 | 2020-05-20T17:20:52 | 265,635,328 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ProblemSolving;
import java.util.*;
public class Leaderboard
{
static int[] climbingLeaderboard(int[] scores, int[] alice)
{
List<Integer> list = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < scores.length; i++)
{
set.add(scores[i]);
}
int[] ar = new int[set.size()];
int k = 0;
for (int i: set)
{
ar[k++] = i;
}
Arrays.sort(ar);
for (int value : alice)//50 65 77 90 102
{
int rank = 1;
for (int j = ar.length - 1; j >= 0; j--)//100 90 80 75 60
{
if (value < ar[0])
{
list.add(ar.length+1);
}
else if(value < ar[j])
{
rank++;
}
else {
list.add(rank);
}
}
}
int[] last = new int[list.size()];
for (int i = 0; i < list.size(); i++)
{
last[i] = list.get(i);
}
return last;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] scores = new int[n];
for (int i = 0; i < scores.length; i++)
{
scores[i] = sc.nextInt() ;
}
int m = sc.nextInt();
int[] alice = new int[m];
for (int i = 0; i < alice.length; i++)
{
alice[i] = sc.nextInt();
}
int[] last = climbingLeaderboard(scores,alice);
for (int i = 0; i < last.length; i++)
{
System.out.println(last[i]);
}
}
}
| UTF-8 | Java | 1,776 | java | Leaderboard.java | Java | []
| null | []
| package ProblemSolving;
import java.util.*;
public class Leaderboard
{
static int[] climbingLeaderboard(int[] scores, int[] alice)
{
List<Integer> list = new ArrayList<>();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < scores.length; i++)
{
set.add(scores[i]);
}
int[] ar = new int[set.size()];
int k = 0;
for (int i: set)
{
ar[k++] = i;
}
Arrays.sort(ar);
for (int value : alice)//50 65 77 90 102
{
int rank = 1;
for (int j = ar.length - 1; j >= 0; j--)//100 90 80 75 60
{
if (value < ar[0])
{
list.add(ar.length+1);
}
else if(value < ar[j])
{
rank++;
}
else {
list.add(rank);
}
}
}
int[] last = new int[list.size()];
for (int i = 0; i < list.size(); i++)
{
last[i] = list.get(i);
}
return last;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] scores = new int[n];
for (int i = 0; i < scores.length; i++)
{
scores[i] = sc.nextInt() ;
}
int m = sc.nextInt();
int[] alice = new int[m];
for (int i = 0; i < alice.length; i++)
{
alice[i] = sc.nextInt();
}
int[] last = climbingLeaderboard(scores,alice);
for (int i = 0; i < last.length; i++)
{
System.out.println(last[i]);
}
}
}
| 1,776 | 0.38964 | 0.371059 | 89 | 18.955055 | 17.972458 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438202 | false | false | 2 |
e642730dfa60fabe98aebb435cbfc7782ca2a7bb | 19,997,367,795,187 | f6a9e18edd22aa7aad3f98a1c124975b3c126a03 | /src/main/java/net/digitaltsunami/tmeter/action/ActionChainShutdownType.java | e82fbfa4dfaff2eddd1ff127c363fb617966798e | []
| no_license | danhagberg/TMeter | https://github.com/danhagberg/TMeter | 97410bd9ef495c610baaff2a1647ac3ec5ede26b | dfde28124548d602411e70b8bfe0d6e4aad580cd | refs/heads/master | 2021-01-21T21:48:36.366000 | 2014-09-30T02:40:06 | 2014-09-30T02:40:06 | 1,627,061 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.digitaltsunami.tmeter.action;
public enum ActionChainShutdownType {
TERMINATE_AFTER_COMPLETION,
TERMINATE_MANUALLY,
TERMINATE_IMMEDIATELY
}
| UTF-8 | Java | 166 | java | ActionChainShutdownType.java | Java | []
| null | []
| package net.digitaltsunami.tmeter.action;
public enum ActionChainShutdownType {
TERMINATE_AFTER_COMPLETION,
TERMINATE_MANUALLY,
TERMINATE_IMMEDIATELY
}
| 166 | 0.783133 | 0.783133 | 8 | 19.75 | 15.990232 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 2 |
4df5baf59d013c8650f9c199bd969afd583e0dcf | 35,347,580,862,458 | b124b87aef92f281baf8ef84d6208bb204f84583 | /main/java/com/example/sudip/sqlitedb/UpdateRecord.java | ae25ff321838c94609dbf12eb2c9f5c996b0ab78 | []
| no_license | sudeepdahal/Android-SQLite-db | https://github.com/sudeepdahal/Android-SQLite-db | 7335e89731d203a0e8f2aa57c3b2f1ee5c36af00 | 532fdb17fef55bdf8c2a6615d5ba676f6b3beae6 | refs/heads/master | 2020-04-10T03:55:46.809000 | 2016-09-13T15:08:04 | 2016-09-13T15:08:04 | 68,119,584 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.sudip.sqlitedb;
import android.content.Intent;
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.Toast;
public class UpdateRecord extends AppCompatActivity {
Button btn;
EditText ed1,ed2,ed3,ed4,ed5;
String n1,n2,n3,n4,n5;
Database db;
Student st;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_record);
ed1 = (EditText) findViewById(R.id.ed1);
ed2 = (EditText) findViewById(R.id.ed2);
ed3 = (EditText) findViewById(R.id.ed3);
ed4 = (EditText) findViewById(R.id.ed4);
ed5 = (EditText) findViewById(R.id.ed5);
btn = (Button) findViewById(R.id.btn2);
final Intent i = getIntent();
final int did = i.getIntExtra("myid",0);
String dname = i.getStringExtra("name");
String daddress = i.getStringExtra("address");
String dfaculty = i.getStringExtra("faculty");
String dphone = i.getStringExtra("phone");
String demail = i.getStringExtra("email");
ed1.setText(dname);
ed2.setText(daddress);
ed3.setText(dfaculty);
ed4.setText(dphone);
ed5.setText(demail);
db=new Database(UpdateRecord.this);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Student st=new Student();
st.setId(did);
st.setName(ed1.getText().toString());
st.setAddress(ed2.getText().toString());
st.setFaculty(ed3.getText().toString());
st.setPhone(ed4.getText().toString());
st.setEmail(ed5.getText().toString());
db.updateRecord(st);
Toast.makeText(UpdateRecord.this, "Update Sucessful!", Toast.LENGTH_SHORT).show();
setResult(1);
finish();
}
});
}
}
| UTF-8 | Java | 2,144 | java | UpdateRecord.java | Java | []
| null | []
| package com.example.sudip.sqlitedb;
import android.content.Intent;
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.Toast;
public class UpdateRecord extends AppCompatActivity {
Button btn;
EditText ed1,ed2,ed3,ed4,ed5;
String n1,n2,n3,n4,n5;
Database db;
Student st;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_record);
ed1 = (EditText) findViewById(R.id.ed1);
ed2 = (EditText) findViewById(R.id.ed2);
ed3 = (EditText) findViewById(R.id.ed3);
ed4 = (EditText) findViewById(R.id.ed4);
ed5 = (EditText) findViewById(R.id.ed5);
btn = (Button) findViewById(R.id.btn2);
final Intent i = getIntent();
final int did = i.getIntExtra("myid",0);
String dname = i.getStringExtra("name");
String daddress = i.getStringExtra("address");
String dfaculty = i.getStringExtra("faculty");
String dphone = i.getStringExtra("phone");
String demail = i.getStringExtra("email");
ed1.setText(dname);
ed2.setText(daddress);
ed3.setText(dfaculty);
ed4.setText(dphone);
ed5.setText(demail);
db=new Database(UpdateRecord.this);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Student st=new Student();
st.setId(did);
st.setName(ed1.getText().toString());
st.setAddress(ed2.getText().toString());
st.setFaculty(ed3.getText().toString());
st.setPhone(ed4.getText().toString());
st.setEmail(ed5.getText().toString());
db.updateRecord(st);
Toast.makeText(UpdateRecord.this, "Update Sucessful!", Toast.LENGTH_SHORT).show();
setResult(1);
finish();
}
});
}
}
| 2,144 | 0.604478 | 0.588619 | 65 | 31.984615 | 20.799032 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.876923 | false | false | 2 |
e097a604785f9f9f61c91360f02089465e951b7e | 13,554,916,829,107 | 5fd919f0ce5449a160546d5e1ca7b871e7f6c0ec | /mediniOCLInterpreter/source/OCLCommon/srcgensyntax/org/oslo/ocl20/syntax/ast/expressions/impl/OclMessageArgASImpl.java | 8d461b89ece4467e338f1cc2e406e4a59ecd1a23 | []
| no_license | mabilov/medini | https://github.com/mabilov/medini | 0a5ff0652b9176011b4d788a76a1cee8fc8da310 | 99ede9dcbc990c77f04a0169f0ee5b8735849247 | refs/heads/master | 2018-05-02T23:54:57.133000 | 2015-05-20T07:48:37 | 2015-05-20T07:48:37 | 35,933,295 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.oslo.ocl20.syntax.ast.expressions.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.oslo.ocl20.syntax.ast.Visitor;
import org.oslo.ocl20.syntax.ast.expressions.ExpressionsPackage;
import org.oslo.ocl20.syntax.ast.expressions.OclExpressionAS;
import org.oslo.ocl20.syntax.ast.expressions.OclMessageArgAS;
import org.oslo.ocl20.syntax.ast.impl.VisitableImpl;
import org.oslo.ocl20.syntax.ast.types.TypeAS;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ocl Message Arg AS</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.oslo.ocl20.syntax.ast.expressions.impl.OclMessageArgASImpl#getExpression <em>Expression</em>}</li>
* <li>{@link org.oslo.ocl20.syntax.ast.expressions.impl.OclMessageArgASImpl#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class OclMessageArgASImpl extends VisitableImpl implements OclMessageArgAS {
/**
* The cached value of the '{@link #getExpression() <em>Expression</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getExpression()
* @generated
* @ordered
*/
protected OclExpressionAS expression;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected TypeAS type;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OclMessageArgASImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return ExpressionsPackage.Literals.OCL_MESSAGE_ARG_AS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeAS getType() {
if (type != null && type.eIsProxy()) {
InternalEObject oldType = (InternalEObject)type;
type = (TypeAS)eResolveProxy(oldType);
if (type != oldType) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE, oldType, type));
}
}
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeAS basicGetType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(TypeAS newType) {
TypeAS oldType = type;
type = newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OclExpressionAS getExpression() {
if (expression != null && expression.eIsProxy()) {
InternalEObject oldExpression = (InternalEObject)expression;
expression = (OclExpressionAS)eResolveProxy(oldExpression);
if (expression != oldExpression) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION, oldExpression, expression));
}
}
return expression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OclExpressionAS basicGetExpression() {
return expression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setExpression(OclExpressionAS newExpression) {
OclExpressionAS oldExpression = expression;
expression = newExpression;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION, oldExpression, expression));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object accept(Visitor visitor, Object data) {
return ((org.oslo.ocl20.semantics.analyser.OclSemanticAnalyserVisitorImpl)visitor).visit(this,data);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
if (resolve) return getExpression();
return basicGetExpression();
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
if (resolve) return getType();
return basicGetType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
setExpression((OclExpressionAS)newValue);
return;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
setType((TypeAS)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
setExpression((OclExpressionAS)null);
return;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
setType((TypeAS)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
return expression != null;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
return type != null;
}
return super.eIsSet(featureID);
}
} //OclMessageArgASImpl
| UTF-8 | Java | 5,848 | java | OclMessageArgASImpl.java | Java | []
| null | []
| /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.oslo.ocl20.syntax.ast.expressions.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.oslo.ocl20.syntax.ast.Visitor;
import org.oslo.ocl20.syntax.ast.expressions.ExpressionsPackage;
import org.oslo.ocl20.syntax.ast.expressions.OclExpressionAS;
import org.oslo.ocl20.syntax.ast.expressions.OclMessageArgAS;
import org.oslo.ocl20.syntax.ast.impl.VisitableImpl;
import org.oslo.ocl20.syntax.ast.types.TypeAS;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ocl Message Arg AS</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.oslo.ocl20.syntax.ast.expressions.impl.OclMessageArgASImpl#getExpression <em>Expression</em>}</li>
* <li>{@link org.oslo.ocl20.syntax.ast.expressions.impl.OclMessageArgASImpl#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class OclMessageArgASImpl extends VisitableImpl implements OclMessageArgAS {
/**
* The cached value of the '{@link #getExpression() <em>Expression</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getExpression()
* @generated
* @ordered
*/
protected OclExpressionAS expression;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected TypeAS type;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OclMessageArgASImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return ExpressionsPackage.Literals.OCL_MESSAGE_ARG_AS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeAS getType() {
if (type != null && type.eIsProxy()) {
InternalEObject oldType = (InternalEObject)type;
type = (TypeAS)eResolveProxy(oldType);
if (type != oldType) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE, oldType, type));
}
}
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TypeAS basicGetType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(TypeAS newType) {
TypeAS oldType = type;
type = newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OclExpressionAS getExpression() {
if (expression != null && expression.eIsProxy()) {
InternalEObject oldExpression = (InternalEObject)expression;
expression = (OclExpressionAS)eResolveProxy(oldExpression);
if (expression != oldExpression) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION, oldExpression, expression));
}
}
return expression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OclExpressionAS basicGetExpression() {
return expression;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setExpression(OclExpressionAS newExpression) {
OclExpressionAS oldExpression = expression;
expression = newExpression;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION, oldExpression, expression));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object accept(Visitor visitor, Object data) {
return ((org.oslo.ocl20.semantics.analyser.OclSemanticAnalyserVisitorImpl)visitor).visit(this,data);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
if (resolve) return getExpression();
return basicGetExpression();
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
if (resolve) return getType();
return basicGetType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
setExpression((OclExpressionAS)newValue);
return;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
setType((TypeAS)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
setExpression((OclExpressionAS)null);
return;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
setType((TypeAS)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__EXPRESSION:
return expression != null;
case ExpressionsPackage.OCL_MESSAGE_ARG_AS__TYPE:
return type != null;
}
return super.eIsSet(featureID);
}
} //OclMessageArgASImpl
| 5,848 | 0.663133 | 0.659713 | 231 | 24.316017 | 25.915607 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.601732 | false | false | 2 |
e1dfc8a10aa7218827369e4a34d7d90bc1343fd2 | 17,763,984,793,935 | e93ed07465c5f53ef3e8bffae9789f1320af854a | /step07/Q2941.java | 3ef51b1523d92d5d1cadc2ed0e89dae3812452c5 | [
"Unlicense"
]
| permissive | happys8520/bj | https://github.com/happys8520/bj | 7916380765d2b687f66cfff52c0c289a74aca7a6 | e46e4342a4bafc0ebea0d89d3082a34d1b7e44b4 | refs/heads/master | 2020-03-28T13:32:31.303000 | 2019-11-19T14:01:06 | 2019-11-19T14:01:06 | 148,312,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package boj07;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Q2941 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String input = br.readLine().trim();
// 방법 1.
// int cnt = 0;
// int length = input.length();
//
// for(int i=0; i<length; i++) {
// cnt++;
// switch(input.charAt(i)) { //substring(i, i+1)
// case 'c':
// if(i < length-1 && (input.charAt(i+1)=='=' || input.charAt(i+1)=='-')) { // index 벗어나는것을 방지하기위한 조건
// i++;
// }
// break;
// case 'd':
// if(i < length-2 && input.charAt(i+1)=='z' && input.charAt(i+2)=='=') {
// i+=2;
// }else if(i < length-1 && input.charAt(i+1)=='-') {
// i++;
// }
// break;
// case 'l': case 'n':
// if(i < length-1 && input.charAt(i+1)=='j') {
// i++;
// }
// break;
// case 's': case 'z':
// if(i < length-1 && input.charAt(i+1)=='=') {
// i++;
// }
// break;
// }
// }
//
//방법2
String alphabet[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
for(int i = 0; i < alphabet.length; i++) {
if(input.contains(alphabet[i])) {
input = input.replaceAll(alphabet[i], "a"); // alphbet배열과 겹치는 문자a로 변환
}
}
bw.write(Integer.toString(input.length()));
bw.flush();
bw.close();
br.close();
}
}
| UTF-8 | Java | 2,177 | java | Q2941.java | Java | []
| null | []
| package boj07;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Q2941 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String input = br.readLine().trim();
// 방법 1.
// int cnt = 0;
// int length = input.length();
//
// for(int i=0; i<length; i++) {
// cnt++;
// switch(input.charAt(i)) { //substring(i, i+1)
// case 'c':
// if(i < length-1 && (input.charAt(i+1)=='=' || input.charAt(i+1)=='-')) { // index 벗어나는것을 방지하기위한 조건
// i++;
// }
// break;
// case 'd':
// if(i < length-2 && input.charAt(i+1)=='z' && input.charAt(i+2)=='=') {
// i+=2;
// }else if(i < length-1 && input.charAt(i+1)=='-') {
// i++;
// }
// break;
// case 'l': case 'n':
// if(i < length-1 && input.charAt(i+1)=='j') {
// i++;
// }
// break;
// case 's': case 'z':
// if(i < length-1 && input.charAt(i+1)=='=') {
// i++;
// }
// break;
// }
// }
//
//방법2
String alphabet[] = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="};
for(int i = 0; i < alphabet.length; i++) {
if(input.contains(alphabet[i])) {
input = input.replaceAll(alphabet[i], "a"); // alphbet배열과 겹치는 문자a로 변환
}
}
bw.write(Integer.toString(input.length()));
bw.flush();
bw.close();
br.close();
}
}
| 2,177 | 0.39547 | 0.383672 | 65 | 31.538462 | 24.909113 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.753846 | false | false | 2 |
208590424409e0b1c231bb2d0451f697e511bfd4 | 25,202,868,151,514 | 87e2667a438461b5a36d1bb35fb00dc7b9cd5f84 | /src/main/java/com/example/demo/Babu.java | 39e79534ad0400c6bfbc84904639f22fd1d8f432 | []
| no_license | sahmedgithub/sbootCusBeanVal | https://github.com/sahmedgithub/sbootCusBeanVal | 9b0d8f4fdd220d78dd60912dec64209e78e6ac75 | 8e7f759e82e3f3eaf5cfd2876893c47661b8916f | refs/heads/master | 2020-04-25T07:22:50.659000 | 2019-02-26T01:29:52 | 2019-02-26T01:29:52 | 172,611,984 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Babu {
@NotNull
@JsonProperty("fName")
private String fName;
@NotNull
@JsonProperty("lName")
private String lName;
@ContactNumberConstraint(message = "ff. valid values are ", enumClass = B.class)
private String contact;
}
enum B {
A,B,C
}
| UTF-8 | Java | 582 | java | Babu.java | Java | []
| null | []
| package com.example.demo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Babu {
@NotNull
@JsonProperty("fName")
private String fName;
@NotNull
@JsonProperty("lName")
private String lName;
@ContactNumberConstraint(message = "ff. valid values are ", enumClass = B.class)
private String contact;
}
enum B {
A,B,C
}
| 582 | 0.747423 | 0.747423 | 31 | 17.774193 | 18.331553 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 2 |
9dc7bf3b9c5ec85d5fac0c5de480dea787a5e18d | 6,236,292,572,698 | 4b1ecad89f608f873dd15f68e7f4c2931ca735a7 | /Programmers/2020 카카오 인턴십/수식 최대화.java | 35330209277c0f2f0c355dce4d11b1261bbf7a7c | []
| no_license | jionchu/Problem-Solving | https://github.com/jionchu/Problem-Solving | 1a8b2ab607b7c645bbf814e90743a5020a4191f6 | 028f077ee4e8d52420e923ac393f79edc8dbdd8f | refs/heads/master | 2023-08-11T07:12:41.164000 | 2021-09-24T10:48:23 | 2021-09-24T10:48:23 | 233,232,210 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Programmers
* 2020 카카오 인턴십 - 수식 최대화
* created on 2021.05.10
* created by jionchu */
import java.util.Stack;
class Solution {
long max = 0;
char[] express;
public long solution(String expression) {
express = expression.toCharArray();
//가능한 모든 우선순위 경우의 수
String[] priorities = {"+-*", "+*-", "-+*", "-*+", "*+-", "*-+"};
//각 우선순위마다 연산 결과 확인
for (String priority: priorities) {
long result = getResult(priority);
if (result > max) max = result; //최대값 구하기
}
return max;
}
//입력 우선순위에 따라 연산 결과 구하기
public long getResult(String priority) {
Stack<Long> numbers = new Stack<>(); //숫자들 저장
Stack<Character> operators = new Stack<>(); //연산자들 저장
StringBuilder sb = new StringBuilder();
for (char c : express) {
switch (c) {
case '+': case '-': case '*': //연산자인 경우
numbers.push(Long.parseLong(sb.toString()));
sb = new StringBuilder(); //다음 숫자 인식을 위해 초기화
//이전 연산자보다 우선순위가 낮거나 같은 경우
while (operators.size() > 0 && priority.indexOf(c) >= priority.indexOf(operators.peek())) {
//계산한 결과값을 숫자 스택에 추가
numbers.push(calculate(operators.pop(),numbers.pop(),numbers.pop()));
}
//이전 연산자보다 우선순위가 높은 경우 계속 진행
operators.push(c);
break;
default: sb.append(c); break; //연산자가 아닌 경우 숫자로 붙이기
}
}
numbers.push(Long.parseLong(sb.toString())); //마지막 숫자 추가
while (operators.size() > 0) { //모든 연산자에 대한 연산 완료하기
numbers.push(calculate(operators.pop(), numbers.pop(), numbers.pop()));
}
return Math.abs(numbers.pop()); //절대값 반환
}
//계산
public long calculate(char operator, long num2, long num1) {
switch(operator) {
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
}
return 0;
}
} | UTF-8 | Java | 2,556 | java | 수식 최대화.java | Java | [
{
"context": "턴십 - 수식 최대화\n * created on 2021.05.10\n * created by jionchu */\n\nimport java.util.Stack;\nclass Solution {\n ",
"end": 86,
"score": 0.9989539384841919,
"start": 79,
"tag": "USERNAME",
"value": "jionchu"
}
]
| null | []
| /* Programmers
* 2020 카카오 인턴십 - 수식 최대화
* created on 2021.05.10
* created by jionchu */
import java.util.Stack;
class Solution {
long max = 0;
char[] express;
public long solution(String expression) {
express = expression.toCharArray();
//가능한 모든 우선순위 경우의 수
String[] priorities = {"+-*", "+*-", "-+*", "-*+", "*+-", "*-+"};
//각 우선순위마다 연산 결과 확인
for (String priority: priorities) {
long result = getResult(priority);
if (result > max) max = result; //최대값 구하기
}
return max;
}
//입력 우선순위에 따라 연산 결과 구하기
public long getResult(String priority) {
Stack<Long> numbers = new Stack<>(); //숫자들 저장
Stack<Character> operators = new Stack<>(); //연산자들 저장
StringBuilder sb = new StringBuilder();
for (char c : express) {
switch (c) {
case '+': case '-': case '*': //연산자인 경우
numbers.push(Long.parseLong(sb.toString()));
sb = new StringBuilder(); //다음 숫자 인식을 위해 초기화
//이전 연산자보다 우선순위가 낮거나 같은 경우
while (operators.size() > 0 && priority.indexOf(c) >= priority.indexOf(operators.peek())) {
//계산한 결과값을 숫자 스택에 추가
numbers.push(calculate(operators.pop(),numbers.pop(),numbers.pop()));
}
//이전 연산자보다 우선순위가 높은 경우 계속 진행
operators.push(c);
break;
default: sb.append(c); break; //연산자가 아닌 경우 숫자로 붙이기
}
}
numbers.push(Long.parseLong(sb.toString())); //마지막 숫자 추가
while (operators.size() > 0) { //모든 연산자에 대한 연산 완료하기
numbers.push(calculate(operators.pop(), numbers.pop(), numbers.pop()));
}
return Math.abs(numbers.pop()); //절대값 반환
}
//계산
public long calculate(char operator, long num2, long num1) {
switch(operator) {
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
}
return 0;
}
} | 2,556 | 0.480822 | 0.469863 | 67 | 31.701492 | 24.458319 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537313 | false | false | 2 |
0930fa37dc73b928f9ba5d895bd0b09bdfab7b96 | 14,972,255,996,831 | 97c37377bdfd0a2e99777c88a2501ca740bbbc43 | /app/src/main/java/com/example/whiletrue/ui/home/BlackActivity.java | ae72241071b19855eab2d15f0e8c48167d535adf | []
| no_license | Sonya-Proskurina/WhileTrue | https://github.com/Sonya-Proskurina/WhileTrue | 38b9db30dcc314fda8d243073ad11efed2200b26 | 6d78bd05ed17bb095e9e697a2c1766c226b54a4b | refs/heads/master | 2023-05-06T03:18:33.962000 | 2021-05-30T11:38:15 | 2021-05-30T11:38:15 | 371,690,621 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.whiletrue.ui.home;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.example.whiletrue.R;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class BlackActivity extends AppCompatActivity {
PieChart pieChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_black);
getSupportActionBar().hide();
pieChart = findViewById(R.id.chart);
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5,10,5,5);
pieChart.setDragDecelerationFrictionCoef(0.95f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(R.color.dark);
pieChart.setCenterTextColor(Color.WHITE);
pieChart.setEntryLabelColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.getLegend().setTextColor(Color.WHITE);
pieChart.getLegend().setTextSize(14);
ArrayList<PieEntry> yValues = new ArrayList<>();
yValues.add(new PieEntry(30f, "Металл"));
yValues.add(new PieEntry(20f, "Батарейки"));
yValues.add(new PieEntry(40f, "Пластик"));
yValues.add(new PieEntry(40f, "Бумага"));
yValues.add(new PieEntry(30f, "Стекло"));
PieDataSet dataSet = new PieDataSet(yValues, "");
dataSet.setSliceSpace(2f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.JOYFUL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextColor(Color.WHITE);
data.setValueTextSize(10f);
pieChart.setData(data);
}
public void back(View view) {
finish();
}
} | UTF-8 | Java | 2,129 | java | BlackActivity.java | Java | [
{
"context": "import com.example.whiletrue.R;\nimport com.github.mikephil.charting.charts.PieChart;\nimport com.github.mikep",
"end": 232,
"score": 0.7304020524024963,
"start": 224,
"tag": "USERNAME",
"value": "mikephil"
},
{
"context": "ephil.charting.charts.PieChart;\nimport com.github.mikephil.charting.data.PieData;\nimport com.github.mikephil",
"end": 285,
"score": 0.6240111589431763,
"start": 277,
"tag": "USERNAME",
"value": "mikephil"
},
{
"context": "phil.charting.data.PieData;\nimport com.github.mikephil.charting.data.PieDataSet;\nimport com.github.mikep",
"end": 335,
"score": 0.545133650302887,
"start": 331,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "l.charting.data.PieDataSet;\nimport com.github.mikephil.charting.data.PieEntry;\nimport com.github.mikephi",
"end": 388,
"score": 0.5219495892524719,
"start": 384,
"tag": "USERNAME",
"value": "phil"
}
]
| null | []
| package com.example.whiletrue.ui.home;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.example.whiletrue.R;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class BlackActivity extends AppCompatActivity {
PieChart pieChart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_black);
getSupportActionBar().hide();
pieChart = findViewById(R.id.chart);
pieChart.setUsePercentValues(true);
pieChart.getDescription().setEnabled(false);
pieChart.setExtraOffsets(5,10,5,5);
pieChart.setDragDecelerationFrictionCoef(0.95f);
pieChart.setDrawHoleEnabled(true);
pieChart.setHoleColor(R.color.dark);
pieChart.setCenterTextColor(Color.WHITE);
pieChart.setEntryLabelColor(Color.WHITE);
pieChart.setTransparentCircleRadius(61f);
pieChart.getLegend().setTextColor(Color.WHITE);
pieChart.getLegend().setTextSize(14);
ArrayList<PieEntry> yValues = new ArrayList<>();
yValues.add(new PieEntry(30f, "Металл"));
yValues.add(new PieEntry(20f, "Батарейки"));
yValues.add(new PieEntry(40f, "Пластик"));
yValues.add(new PieEntry(40f, "Бумага"));
yValues.add(new PieEntry(30f, "Стекло"));
PieDataSet dataSet = new PieDataSet(yValues, "");
dataSet.setSliceSpace(2f);
dataSet.setSelectionShift(5f);
dataSet.setColors(ColorTemplate.JOYFUL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextColor(Color.WHITE);
data.setValueTextSize(10f);
pieChart.setData(data);
}
public void back(View view) {
finish();
}
} | 2,129 | 0.702148 | 0.689737 | 65 | 31.246155 | 21.169666 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 2 |
9b3531222378d8ffafbbca9431c8bcfde47bd2ab | 17,532,056,508,090 | b921933f52419cc4f7c6ab51d7bbd174998e1d71 | /infrastructure/microservice/microservice-tenant-server/src/generated/java/com/jikezhiji/tenant/aggregate/TenantServiceMetadata.java | 8045f19b387418236183463a333e635afa7c21a2 | [
"Apache-2.0"
]
| permissive | SignleMR/saas-platform | https://github.com/SignleMR/saas-platform | 0d0829174a806607263de8be38275a11ae5385c4 | 6259b6a400e28d351757807cd28a6e0689cb70de | refs/heads/master | 2018-04-30T08:37:35.197000 | 2017-06-14T06:05:27 | 2017-06-14T06:05:27 | 92,262,198 | 0 | 3 | null | true | 2017-06-14T06:05:28 | 2017-05-24T07:18:23 | 2017-05-24T07:18:25 | 2017-06-14T06:05:28 | 163 | 0 | 0 | 0 | Java | null | null | package com.jikezhiji.tenant.aggregate;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.PathInits;
/**
* TenantServiceMetadata is a Querydsl query type for TenantService
*/
@Generated("com.querydsl.codegen.EntitySerializer")
public class TenantServiceMetadata extends EntityPathBase<TenantService> {
private static final long serialVersionUID = -615625102L;
public static final TenantServiceMetadata tenantService = new TenantServiceMetadata("tenantService");
public final com.jikezhiji.domain.command.AutoIncrementEsarMetadata _super = new com.jikezhiji.domain.command.AutoIncrementEsarMetadata(this);
//inherited
public final BooleanPath deleted = _super.deleted;
public final DateTimePath<java.time.LocalDateTime> endTime = createDateTime("endTime", java.time.LocalDateTime.class);
//inherited
public final NumberPath<Long> id = _super.id;
public final SetPath<com.jikezhiji.tenant.aggregate.value.TenantDetailProperties, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata> metadataSet = this.<com.jikezhiji.tenant.aggregate.value.TenantDetailProperties, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata>createSet("metadataSet", com.jikezhiji.tenant.aggregate.value.TenantDetailProperties.class, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata.class, PathInits.DIRECT2);
public final StringPath remark = createString("remark");
public final StringPath serviceId = createString("serviceId");
public final DateTimePath<java.time.LocalDateTime> startTime = createDateTime("startTime", java.time.LocalDateTime.class);
public final NumberPath<Long> tenantId = createNumber("tenantId", Long.class);
//inherited
public final NumberPath<Integer> version = _super.version;
public TenantServiceMetadata(String variable) {
super(TenantService.class, forVariable(variable));
}
public TenantServiceMetadata(Path<? extends TenantService> path) {
super(path.getType(), path.getMetadata());
}
public TenantServiceMetadata(PathMetadata metadata) {
super(TenantService.class, metadata);
}
}
| UTF-8 | Java | 2,367 | java | TenantServiceMetadata.java | Java | []
| null | []
| package com.jikezhiji.tenant.aggregate;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.PathInits;
/**
* TenantServiceMetadata is a Querydsl query type for TenantService
*/
@Generated("com.querydsl.codegen.EntitySerializer")
public class TenantServiceMetadata extends EntityPathBase<TenantService> {
private static final long serialVersionUID = -615625102L;
public static final TenantServiceMetadata tenantService = new TenantServiceMetadata("tenantService");
public final com.jikezhiji.domain.command.AutoIncrementEsarMetadata _super = new com.jikezhiji.domain.command.AutoIncrementEsarMetadata(this);
//inherited
public final BooleanPath deleted = _super.deleted;
public final DateTimePath<java.time.LocalDateTime> endTime = createDateTime("endTime", java.time.LocalDateTime.class);
//inherited
public final NumberPath<Long> id = _super.id;
public final SetPath<com.jikezhiji.tenant.aggregate.value.TenantDetailProperties, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata> metadataSet = this.<com.jikezhiji.tenant.aggregate.value.TenantDetailProperties, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata>createSet("metadataSet", com.jikezhiji.tenant.aggregate.value.TenantDetailProperties.class, com.jikezhiji.tenant.aggregate.value.TenantDetailPropertiesMetadata.class, PathInits.DIRECT2);
public final StringPath remark = createString("remark");
public final StringPath serviceId = createString("serviceId");
public final DateTimePath<java.time.LocalDateTime> startTime = createDateTime("startTime", java.time.LocalDateTime.class);
public final NumberPath<Long> tenantId = createNumber("tenantId", Long.class);
//inherited
public final NumberPath<Integer> version = _super.version;
public TenantServiceMetadata(String variable) {
super(TenantService.class, forVariable(variable));
}
public TenantServiceMetadata(Path<? extends TenantService> path) {
super(path.getType(), path.getMetadata());
}
public TenantServiceMetadata(PathMetadata metadata) {
super(TenantService.class, metadata);
}
}
| 2,367 | 0.784115 | 0.77989 | 58 | 39.793102 | 69.950417 | 490 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568965 | false | false | 2 |
ad5c7de68b69c0e6a2e9af25f3008d046858c392 | 31,250,182,077,334 | 737e3d460e7b6a4c7b330c3f120655e4a268a85e | /src/test/java/com/selenium/test/testng/tests/EmptyFieldsTest.java | babba70a117a570b04683e4aca19a90c7a26964f | []
| no_license | IrkStalker/MyProject | https://github.com/IrkStalker/MyProject | a8eac45c3c530e4edb67e1aad9eba88dea02a2c9 | 3b08fd4128788345c6ac75d831c2f091b59f2ced | refs/heads/master | 2020-02-21T11:08:38.004000 | 2017-02-05T13:07:37 | 2017-02-05T13:07:37 | 80,991,749 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.selenium.test.testng.tests;
import com.selenium.test.pages.AfterRBPage;
import com.selenium.test.pages.RBPage;
import com.selenium.test.webtestsbase.WebDriverFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.junit.Assert.assertTrue;
//Тест на проверку регистрации, если какое-то из полей не заполнено (логин, email, пароль)
//Возвращает ошибку, если регистрация прошла успешно с незаполненным полем
public class EmptyFieldsTest {
@BeforeTest
public void beforeTest() {
WebDriverFactory.startBrowser(true);
}
@Test
public void testRegistration() {
//какое-либо из полей не должно быть заполнено
String login = "474hrthrh";
String email = "4t83t@dgnfdgn.com";
String passw = "";
RBPage regPage = new RBPage();
regPage.insertStringLogin(login);
regPage.insertStringEmail(email);
regPage.insertStringPassword(passw);
AfterRBPage resultsPage = regPage.doRegistration();
//тест пройден, если регистрация не происходит
assertTrue("Ошибка: пользователь зарегистрирован, хотя не все обязательные поля заполнены", !resultsPage.regSuccess());
}
@AfterTest
public void afterTest() {
WebDriverFactory.finishBrowser();
}
}
| UTF-8 | Java | 1,634 | java | EmptyFieldsTest.java | Java | [
{
"context": " не должно быть заполнено\n String login = \"474hrthrh\";\n String email = \"4t83t@dgnfdgn.com\";\n ",
"end": 777,
"score": 0.9990241527557373,
"start": 768,
"tag": "USERNAME",
"value": "474hrthrh"
},
{
"context": "ring login = \"474hrthrh\";\n String email = \"4t83t@dgnfdgn.com\";\n String passw = \"\";\n RBPage regPa",
"end": 821,
"score": 0.999891996383667,
"start": 804,
"tag": "EMAIL",
"value": "4t83t@dgnfdgn.com"
}
]
| null | []
| package com.selenium.test.testng.tests;
import com.selenium.test.pages.AfterRBPage;
import com.selenium.test.pages.RBPage;
import com.selenium.test.webtestsbase.WebDriverFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.junit.Assert.assertTrue;
//Тест на проверку регистрации, если какое-то из полей не заполнено (логин, email, пароль)
//Возвращает ошибку, если регистрация прошла успешно с незаполненным полем
public class EmptyFieldsTest {
@BeforeTest
public void beforeTest() {
WebDriverFactory.startBrowser(true);
}
@Test
public void testRegistration() {
//какое-либо из полей не должно быть заполнено
String login = "474hrthrh";
String email = "<EMAIL>";
String passw = "";
RBPage regPage = new RBPage();
regPage.insertStringLogin(login);
regPage.insertStringEmail(email);
regPage.insertStringPassword(passw);
AfterRBPage resultsPage = regPage.doRegistration();
//тест пройден, если регистрация не происходит
assertTrue("Ошибка: пользователь зарегистрирован, хотя не все обязательные поля заполнены", !resultsPage.regSuccess());
}
@AfterTest
public void afterTest() {
WebDriverFactory.finishBrowser();
}
}
| 1,624 | 0.719208 | 0.714809 | 41 | 32.268291 | 26.622953 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.634146 | false | false | 2 |
8a44729f958f5d3eba41870538c98aca2e3e4c34 | 15,212,774,231,123 | c8328bd8c179c94043d7144cf7dcb30e0d1b285c | /HanAna_Assignment2/src/main/java/ro/utcn/sd/dao/factory/DaoFactory.java | 387d929e45b187f0240f1192471d38b213fecf90 | []
| no_license | anamhan13/HanAna_Assignment1 | https://github.com/anamhan13/HanAna_Assignment1 | ca6e08a9d27d01a460ae0d27cd38dae154246ec7 | 891061a3d7ce8dc11f85c5ba30e9aed95f44d2d3 | refs/heads/master | 2020-03-07T23:57:01.395000 | 2018-05-28T21:24:17 | 2018-05-28T21:24:17 | 127,794,374 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.utcn.sd.dao.factory;
import ro.utcn.sd.dao.GameDao;
import ro.utcn.sd.dao.MatchDao;
import ro.utcn.sd.dao.PlayerDao;
import ro.utcn.sd.dao.TournamentDao;
import ro.utcn.sd.dao.factory.impl.HibernateDaoFactory;
import ro.utcn.sd.dao.factory.impl.JdbcDaoFactory;
public abstract class DaoFactory {
public enum Type {
HIBERNATE,
JDBC;
}
protected DaoFactory(){
}
public static DaoFactory getInstance(Type factoryType) {
switch (factoryType) {
case HIBERNATE:
return new HibernateDaoFactory();
case JDBC:
return new JdbcDaoFactory();
default:
throw new IllegalArgumentException("Invalid factory");
}
}
public abstract GameDao getGameDao();
public abstract MatchDao getMatchDao();
public abstract PlayerDao getPlayerDao();
public abstract TournamentDao getTournamentDao();
}
| UTF-8 | Java | 873 | java | DaoFactory.java | Java | []
| null | []
| package ro.utcn.sd.dao.factory;
import ro.utcn.sd.dao.GameDao;
import ro.utcn.sd.dao.MatchDao;
import ro.utcn.sd.dao.PlayerDao;
import ro.utcn.sd.dao.TournamentDao;
import ro.utcn.sd.dao.factory.impl.HibernateDaoFactory;
import ro.utcn.sd.dao.factory.impl.JdbcDaoFactory;
public abstract class DaoFactory {
public enum Type {
HIBERNATE,
JDBC;
}
protected DaoFactory(){
}
public static DaoFactory getInstance(Type factoryType) {
switch (factoryType) {
case HIBERNATE:
return new HibernateDaoFactory();
case JDBC:
return new JdbcDaoFactory();
default:
throw new IllegalArgumentException("Invalid factory");
}
}
public abstract GameDao getGameDao();
public abstract MatchDao getMatchDao();
public abstract PlayerDao getPlayerDao();
public abstract TournamentDao getTournamentDao();
}
| 873 | 0.717068 | 0.717068 | 40 | 19.825001 | 19.209227 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.425 | false | false | 2 |
15629c4794ae097723718824865968a359a4fba1 | 18,537,078,916,111 | c3248f8b54c41c65e10cbe2fd1559741e98e8f7c | /src/test/java/org/hivesoft/confluence/rest/representations/CsvExportRepresentationTest.java | 5c91b58bfb92030bbce2ebceb4f152873093a687 | [
"BSD-2-Clause"
]
| permissive | jdputsch/confluence-survey-plugin | https://github.com/jdputsch/confluence-survey-plugin | 2c6ba84c2eae1ed7c6cc638dd91ba3c528102235 | f672667b88cfd1675e48283cec72535ace8bb4f7 | refs/heads/master | 2020-12-31T01:22:55.670000 | 2014-11-26T23:35:48 | 2014-11-26T23:35:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.hivesoft.confluence.rest.representations;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CsvExportRepresentationTest {
CSVExportRepresentation classUnderTest;
@Test
public void test_gettersSetters_success() {
classUnderTest = new CSVExportRepresentation("someTitle", "someUri");
assertThat("someTitle", is(equalTo(classUnderTest.getTitle())));
assertThat("someUri", is(equalTo(classUnderTest.getUri())));
assertTrue(classUnderTest.equals(new CSVExportRepresentation("someTitle", "someUri")));
assertFalse(classUnderTest.equals(null));
assertFalse(classUnderTest.equals("someString"));
}
}
| UTF-8 | Java | 860 | java | CsvExportRepresentationTest.java | Java | []
| null | []
| package org.hivesoft.confluence.rest.representations;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CsvExportRepresentationTest {
CSVExportRepresentation classUnderTest;
@Test
public void test_gettersSetters_success() {
classUnderTest = new CSVExportRepresentation("someTitle", "someUri");
assertThat("someTitle", is(equalTo(classUnderTest.getTitle())));
assertThat("someUri", is(equalTo(classUnderTest.getUri())));
assertTrue(classUnderTest.equals(new CSVExportRepresentation("someTitle", "someUri")));
assertFalse(classUnderTest.equals(null));
assertFalse(classUnderTest.equals("someString"));
}
}
| 860 | 0.787209 | 0.787209 | 24 | 34.833332 | 26.875742 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 2 |
641cb3d7c5ecf3c561065fb7946e56f93a8b4343 | 27,135,603,434,926 | dfff8db679708ab1d329c5fe015530c4a7ce3ef1 | /Source Code/src/Content/Text/LessonThree.java | f6a760573b82fe5d82c6e5185b63e813fe414c6d | []
| no_license | AntonRand/pokercoacher | https://github.com/AntonRand/pokercoacher | e4fc3d0862ed3818134c5ac2676847bad1311402 | 6128b6a506b627232476bb5cf7f1a3d4b3bd9bda | refs/heads/master | 2021-01-21T04:28:05.106000 | 2016-08-15T22:11:19 | 2016-08-15T22:11:19 | 44,798,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Content.Text;
import Lesson.Lesson;
import Lesson.LessonView;
import Lesson.LessonStep;
import Primitives.Definition;
import java.util.ArrayList;
/**
* Bluffing Lesson
* @author Anton
*/
public class LessonThree {
public static Lesson getContent(LessonView v) {
ArrayList<LessonStep> allStages = new ArrayList<LessonStep>();
//Message 1
LessonStep stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Lesson Three<br>Lesson Overview</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This lesson will introduce you to the concept of bluffing, something that every player needs to carry out to improve their chances of winning tournaments.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You will learn what the risks and best conditions for bluffing are, so you can maximise the chances of your bluffs being successful.</p> "
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">After taking the lesson you will understand why players choose to bluff, what the types of bluffing are and you will have learnt how to make sensible decisions on when to bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 2
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>What is Bluffing?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Bluffing is a strategy which when applied correctly can lead to significant chip gains. If you do not bluff you're unlikely to win tournaments because you rarely have a strong <u>hand</u>, so you have to make your own luck.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Bluffing involves betting a large amount of chips to deceive other players into thinking you have a strong hand, when in reality you have a weak hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The aim of bluffing is to make all of the other players fold so that you win the <u>pot</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">It can backfire on you if another player calls your bluff, as your weak cards are highly unlikely to win.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.hand(205, 207));
stage.addDefinition(Definitions.pot(478, 479));
allStages.add(stage);
//Message 3
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Pure Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There are two different types of bluff, the first is known as the pure bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A pure bluff is when you have a poor hand which has little or no chance of improving in future stages such as the <u>turn</u> or <u>river</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">An example of a pure bluff is if the player decides to <u>raise</u> in the following situation:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Hole Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 2<font color=red style='font-size:140%'>♦</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Community Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">A<font color=red style='font-size:140%'>♥</font> Q<font color=red style='font-size:140%'>♦</font> 9<font color=black style='font-size:140%'>♣</font></p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.turn(220, 222));
stage.addDefinition(Definitions.river(228, 232));
stage.addDefinition(Definitions.raise(290, 293));
allStages.add(stage);
//Message 4
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Pure Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 2<font color=red style='font-size:140%'>♦</font> | "
+ "A<font color=red style='font-size:140%'>♥</font> Q<font color=red style='font-size:140%'>♦</font> 9<font color=black style='font-size:140%'>♣</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Why is this a pure bluff?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The player only has a <u>high card</u>, there is no chance of them getting a <u>flush</u> or <u>straight</u> and all of the community cards are higher than the players hole cards.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">It is very likely one of the other players has a stronger hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is why it is an example of a pure bluff, it's highly unlikely that the player's hand will get any stronger on the turn or river.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.highcard(93, 101));
stage.addDefinition(Definitions.flush(141, 145));
stage.addDefinition(Definitions.straight(150, 157));
allStages.add(stage);
//Message 5
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Semi Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The second type of bluff is known as the semi bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A semi bluff is when you have a weak hand that stands a reasonable chance of improving in future stages.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">An example of a semi bluff is if the player decides to raise in the following situation:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Hole Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 4<font color=red style='font-size:140%'>♦</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Community Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">6<font color=red style='font-size:140%'>♥</font> 8<font color=red style='font-size:140%'>♦</font> Q<font color=black style='font-size:140%'>♣</font></p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 6
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Semi Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 4<font color=red style='font-size:140%'>♦</font> | "
+ "6<font color=red style='font-size:140%'>♥</font> 8<font color=red style='font-size:140%'>♦</font> Q<font color=black style='font-size:140%'>♣</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">What is this a semi bluff?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Although the player doesn't have anything yet there is a chance of a 5 coming up on the turn or river.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If a 5 comes up the player will have a <u>straight</u>, which is a strong hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is why it is an example of a semi bluff, there is a chance that the player's hand could get stronger on the turn or river, because they are only one card away from making the strong hand.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.straight(213, 220));
allStages.add(stage);
//Message 7
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Analyse the Situation</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">To determine whether or not you are in a suitable situation to bluff you need to consider several possible conditions.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Before explaining the conditions it is important to firstly emphasise that you should constantly be analysing the game.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You should think about how players are likely to react to your raises, if you notice for instance that a player has been calling other peoples raises frequently with average hands you should be wary of bluffing them, because they may call your bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 8
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Position</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The first and most important condition you should consider is <u>position</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you are one of the first to act (in an <u>early position</u>) you should not consider bluffing, because you do not know what actions the other players will take. The player to act after you may have a strong hand and be about to raise, so bluffing is too risky.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you are the last person to act (in a <u>late position</u>) you should consider bluffing depending on other conditions.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.position(92, 99));
stage.addDefinition(Definitions.earlyposition(145, 157));
stage.addDefinition(Definitions.lateposition(401, 412));
allStages.add(stage);
//Message 9
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Few Opponents</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The second condition you should consider is the amount of opponents left in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Even if you are in a <u>late position</u> you should only consider bluffing if there are only 1 or 2 other players involved in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is because with a high number of participating players it is more likely a player will have a stronger hand than you and call/raise your bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">With more players involved there is even a chance that one of them could try to bluff you.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.lateposition(143, 154));
allStages.add(stage);
//Message 10
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Uncommitted Players</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The third condition you should consider is the type of players involved in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Players who are reluctant to commit chips and check until they hit a strong hand are known as passive players.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Passive players often fold hands if you bet aggressively against them, taking away their chance to hit a strong hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you have identified the other players in the hand as being passive, bluffing would be a good strategy because their reluctance to commit chips is likely to win you the pot.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 11
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Pot Size</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The fourth condition you should consider is the size of the <u>pot</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Players who have committed a moderate amount of chips into a pot will often be reluctant to fold. They will usually call any bet in the hope of winning because they are too stubborn to fold and lose the chips they have already bet.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If the pot is large, players will be less willing to fold and let you win the pot, so you shouldn't bluff in these circumstances, because their medicore hand will still beat your weak hand.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.pot(91, 92));
allStages.add(stage);
//Message 12
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">How Much To Bluff By?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There is no universal method or formula to work out how much to bluff by.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A general rule would be to bet more than half of the pot but no more than the pot. More than half so that the bet is aggressive enough to put players off, but less than the pot because you don't want to be seen as being too aggressive or players might get suspicious.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The more you bet the more likely you are to put players off, but the more damaging it will be if your bluff gets called.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There are no guarantees when bluffing, but if you take all the different conditions set out in this lesson into account, you should find yourself making less errors when deciding to bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 13
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 1/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Now that you have learnt the main conditions for bluffing, think about whether you could bluff in the following scenario.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">After going in the hand with strong hole cards, you have been raised on the flop. What should you do?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(16, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "Michaels raise shows confidence, do you think he would be", "put off by a raise after already raising himself?"));
allStages.add(stage);
//Message 14
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 2/5"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You went into the hand because you were the big blind, not because you had strong cards. 3 other players chose to call and the action starts on you after the flop.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(17, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "Your position makes it unwise to bluff, but you shouldn't", "fold if you have the option to check."));
allStages.add(stage);
//Message 15
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 3/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You called with high valued connected cards but the flop hasn't been good to you. However, you have identified Emily and Michael as passive players and they both decide to check, the action is on you.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(18, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "You have the benefit of late position, and there are only two", "players in the hand. Bluffing is very effective against these two", "'passive' players.."));
allStages.add(stage);
//Message 16
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 4/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You rather foolishly went into the hand with weak cards and called a bet on the flop even though you had nothing. The action is on you with $50 to call, should you bluff, call or fold?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(19, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "There are too many people in the hand to bluff and the odds", "are that somebody has you beat. It's not worth being in", "the hand."));
allStages.add(stage);
//Message 17
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 5/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You made another bad judgement and went into the hand with weak cards. You called a bet on the flop as you were one away from a straight. The turn card wasn't good to you but both players check, the action is on you.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(20, v.getUserDetails(), 0);
stage.setAction("StartEnd");
stage.addHint(new Definition(1, 34, "Hint", "You are only one card away from a straight, the pot is small", "and there are only 2 other players involved so a bluff", "would be a good option here."));
allStages.add(stage);
Lesson completeLesson = new Lesson(allStages);
return completeLesson;
}
} | UTF-8 | Java | 22,381 | java | LessonThree.java | Java | [
{
"context": "util.ArrayList;\n\n/**\n * Bluffing Lesson\n * @author Anton\n */\npublic class LessonThree {\n\n public static",
"end": 295,
"score": 0.999664306640625,
"start": 290,
"tag": "NAME",
"value": "Anton"
},
{
"context": " stage.addHint(new Definition(1, 34, \"Hint\", \"Michaels raise shows confidence, do you think he would ",
"end": 17489,
"score": 0.621873140335083,
"start": 17484,
"tag": "NAME",
"value": "Micha"
},
{
"context": "n't been good to you. However, you have identified Emily and Michael as passive players and they both deci",
"end": 19124,
"score": 0.9997541904449463,
"start": 19119,
"tag": "NAME",
"value": "Emily"
},
{
"context": "ood to you. However, you have identified Emily and Michael as passive players and they both decide to check,",
"end": 19136,
"score": 0.9987919330596924,
"start": 19129,
"tag": "NAME",
"value": "Michael"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Content.Text;
import Lesson.Lesson;
import Lesson.LessonView;
import Lesson.LessonStep;
import Primitives.Definition;
import java.util.ArrayList;
/**
* Bluffing Lesson
* @author Anton
*/
public class LessonThree {
public static Lesson getContent(LessonView v) {
ArrayList<LessonStep> allStages = new ArrayList<LessonStep>();
//Message 1
LessonStep stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Lesson Three<br>Lesson Overview</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This lesson will introduce you to the concept of bluffing, something that every player needs to carry out to improve their chances of winning tournaments.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You will learn what the risks and best conditions for bluffing are, so you can maximise the chances of your bluffs being successful.</p> "
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">After taking the lesson you will understand why players choose to bluff, what the types of bluffing are and you will have learnt how to make sensible decisions on when to bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 2
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>What is Bluffing?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Bluffing is a strategy which when applied correctly can lead to significant chip gains. If you do not bluff you're unlikely to win tournaments because you rarely have a strong <u>hand</u>, so you have to make your own luck.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Bluffing involves betting a large amount of chips to deceive other players into thinking you have a strong hand, when in reality you have a weak hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The aim of bluffing is to make all of the other players fold so that you win the <u>pot</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">It can backfire on you if another player calls your bluff, as your weak cards are highly unlikely to win.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.hand(205, 207));
stage.addDefinition(Definitions.pot(478, 479));
allStages.add(stage);
//Message 3
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Pure Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There are two different types of bluff, the first is known as the pure bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A pure bluff is when you have a poor hand which has little or no chance of improving in future stages such as the <u>turn</u> or <u>river</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">An example of a pure bluff is if the player decides to <u>raise</u> in the following situation:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Hole Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 2<font color=red style='font-size:140%'>♦</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Community Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">A<font color=red style='font-size:140%'>♥</font> Q<font color=red style='font-size:140%'>♦</font> 9<font color=black style='font-size:140%'>♣</font></p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.turn(220, 222));
stage.addDefinition(Definitions.river(228, 232));
stage.addDefinition(Definitions.raise(290, 293));
allStages.add(stage);
//Message 4
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Pure Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 2<font color=red style='font-size:140%'>♦</font> | "
+ "A<font color=red style='font-size:140%'>♥</font> Q<font color=red style='font-size:140%'>♦</font> 9<font color=black style='font-size:140%'>♣</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Why is this a pure bluff?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The player only has a <u>high card</u>, there is no chance of them getting a <u>flush</u> or <u>straight</u> and all of the community cards are higher than the players hole cards.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">It is very likely one of the other players has a stronger hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is why it is an example of a pure bluff, it's highly unlikely that the player's hand will get any stronger on the turn or river.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.highcard(93, 101));
stage.addDefinition(Definitions.flush(141, 145));
stage.addDefinition(Definitions.straight(150, 157));
allStages.add(stage);
//Message 5
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Semi Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The second type of bluff is known as the semi bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A semi bluff is when you have a weak hand that stands a reasonable chance of improving in future stages.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">An example of a semi bluff is if the player decides to raise in the following situation:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Hole Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 4<font color=red style='font-size:140%'>♦</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Community Cards:</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">6<font color=red style='font-size:140%'>♥</font> 8<font color=red style='font-size:140%'>♦</font> Q<font color=black style='font-size:140%'>♣</font></p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 6
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Types of Bluff<br>Semi Bluff</p>"
+ "<p style=\"font-family:arial;color:white;font-size:11px;text-align:center;font-size:120%;\">7<font color=red style='font-size:140%'>♥</font> 4<font color=red style='font-size:140%'>♦</font> | "
+ "6<font color=red style='font-size:140%'>♥</font> 8<font color=red style='font-size:140%'>♦</font> Q<font color=black style='font-size:140%'>♣</font></p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">What is this a semi bluff?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Although the player doesn't have anything yet there is a chance of a 5 coming up on the turn or river.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If a 5 comes up the player will have a <u>straight</u>, which is a strong hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is why it is an example of a semi bluff, there is a chance that the player's hand could get stronger on the turn or river, because they are only one card away from making the strong hand.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.straight(213, 220));
allStages.add(stage);
//Message 7
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Analyse the Situation</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">To determine whether or not you are in a suitable situation to bluff you need to consider several possible conditions.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Before explaining the conditions it is important to firstly emphasise that you should constantly be analysing the game.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You should think about how players are likely to react to your raises, if you notice for instance that a player has been calling other peoples raises frequently with average hands you should be wary of bluffing them, because they may call your bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 8
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Position</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The first and most important condition you should consider is <u>position</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you are one of the first to act (in an <u>early position</u>) you should not consider bluffing, because you do not know what actions the other players will take. The player to act after you may have a strong hand and be about to raise, so bluffing is too risky.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you are the last person to act (in a <u>late position</u>) you should consider bluffing depending on other conditions.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.position(92, 99));
stage.addDefinition(Definitions.earlyposition(145, 157));
stage.addDefinition(Definitions.lateposition(401, 412));
allStages.add(stage);
//Message 9
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Few Opponents</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The second condition you should consider is the amount of opponents left in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Even if you are in a <u>late position</u> you should only consider bluffing if there are only 1 or 2 other players involved in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">This is because with a high number of participating players it is more likely a player will have a stronger hand than you and call/raise your bluff.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">With more players involved there is even a chance that one of them could try to bluff you.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.lateposition(143, 154));
allStages.add(stage);
//Message 10
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Uncommitted Players</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The third condition you should consider is the type of players involved in the hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Players who are reluctant to commit chips and check until they hit a strong hand are known as passive players.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Passive players often fold hands if you bet aggressively against them, taking away their chance to hit a strong hand.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If you have identified the other players in the hand as being passive, bluffing would be a good strategy because their reluctance to commit chips is likely to win you the pot.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 11
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing Conditions<br>Pot Size</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The fourth condition you should consider is the size of the <u>pot</u>.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Players who have committed a moderate amount of chips into a pot will often be reluctant to fold. They will usually call any bet in the hope of winning because they are too stubborn to fold and lose the chips they have already bet.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">If the pot is large, players will be less willing to fold and let you win the pot, so you shouldn't bluff in these circumstances, because their medicore hand will still beat your weak hand.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
stage.addDefinition(Definitions.pot(91, 92));
allStages.add(stage);
//Message 12
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">How Much To Bluff By?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There is no universal method or formula to work out how much to bluff by.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">A general rule would be to bet more than half of the pot but no more than the pot. More than half so that the bet is aggressive enough to put players off, but less than the pot because you don't want to be seen as being too aggressive or players might get suspicious.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">The more you bet the more likely you are to put players off, but the more damaging it will be if your bluff gets called.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">There are no guarantees when bluffing, but if you take all the different conditions set out in this lesson into account, you should find yourself making less errors when deciding to bluff.</p>"
+ "</html>");
stage.addGame(1, v.getUserDetails(), 0);
allStages.add(stage);
//Message 13
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 1/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">Now that you have learnt the main conditions for bluffing, think about whether you could bluff in the following scenario.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">After going in the hand with strong hole cards, you have been raised on the flop. What should you do?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(16, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "Michaels raise shows confidence, do you think he would be", "put off by a raise after already raising himself?"));
allStages.add(stage);
//Message 14
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 2/5"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You went into the hand because you were the big blind, not because you had strong cards. 3 other players chose to call and the action starts on you after the flop.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(17, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "Your position makes it unwise to bluff, but you shouldn't", "fold if you have the option to check."));
allStages.add(stage);
//Message 15
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 3/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You called with high valued connected cards but the flop hasn't been good to you. However, you have identified Emily and Michael as passive players and they both decide to check, the action is on you.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(18, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "You have the benefit of late position, and there are only two", "players in the hand. Bluffing is very effective against these two", "'passive' players.."));
allStages.add(stage);
//Message 16
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 4/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You rather foolishly went into the hand with weak cards and called a bet on the flop even though you had nothing. The action is on you with $50 to call, should you bluff, call or fold?</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(19, v.getUserDetails(), 0);
stage.setAction("Start");
stage.addHint(new Definition(1, 34, "Hint", "There are too many people in the hand to bluff and the odds", "are that somebody has you beat. It's not worth being in", "the hand."));
allStages.add(stage);
//Message 17
stage = new LessonStep(v, "<html>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;text-align:center;font-weight:bold;\">Bluffing<br>Test Yourself 5/5</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\">You made another bad judgement and went into the hand with weak cards. You called a bet on the flop as you were one away from a straight. The turn card wasn't good to you but both players check, the action is on you.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Remember to bluff you need to bet more than half the size of the pot but less than the whole pot.</p>"
+ "<p style=\"font-family:arial;color:white;font-size:10px;\"><b>Click 'Start' to begin the hand and make your decision...</b></p>"
+ "</html>");
stage.addGame(20, v.getUserDetails(), 0);
stage.setAction("StartEnd");
stage.addHint(new Definition(1, 34, "Hint", "You are only one card away from a straight, the pot is small", "and there are only 2 other players involved so a bluff", "would be a good option here."));
allStages.add(stage);
Lesson completeLesson = new Lesson(allStages);
return completeLesson;
}
} | 22,381 | 0.647688 | 0.628083 | 239 | 92.481171 | 87.327301 | 350 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.1841 | false | false | 2 |
d73ce5c0396a752646c8c0c4864c17fbedd598cd | 3,195,455,729,593 | 8e1d2080d1a00aec1154082a97b0d5a6c81519d6 | /src/main/java/org/numerateweb/math/xml/OMReader.java | 61b3a79545fb9b13bc8d459c06b583d850550fc6 | []
| no_license | numerateweb/org.numerateweb.math | https://github.com/numerateweb/org.numerateweb.math | 5ea38e4e751b38f97092dadf8c8035eed5ba7a44 | 0b5abc1253998f36106ce693b034bf716413c625 | refs/heads/master | 2016-08-04T06:58:49.314000 | 2015-02-16T10:24:15 | 2015-02-16T10:24:15 | 18,175,992 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.numerateweb.math.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import net.enilink.komma.core.URI;
import net.enilink.komma.model.IURIConverter;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.numerateweb.math.MathActivator;
import org.numerateweb.math.model.OMObjectBuilder;
import org.numerateweb.math.om.cd.OMCDParser;
import org.numerateweb.math.util.stax.ParseException;
public class OMReader {
Collection<String> extensions;
public OMReader(Collection<String> extensions) {
this.extensions = extensions;
}
protected IURIConverter getURIConverter() {
return null;
}
protected InputStream inputStreamForFile(URI resourceUri)
throws IOException {
String testPath = resourceUri.toString().toLowerCase();
InputStream in;
IURIConverter uriConverter = getURIConverter();
if (uriConverter == null) {
try {
in = new java.net.URI(resourceUri.toString()).toURL()
.openStream();
} catch (URISyntaxException e) {
throw new IOException("Unable to open file: " + resourceUri);
}
} else {
in = uriConverter.createInputStream(resourceUri);
}
if (testPath.endsWith(".gz")) {
in = new GZIPInputStream(in);
if (testPath.endsWith(".tar.gz")) {
in = new TarArchiveInputStream(in);
}
} else if (testPath.endsWith(".zip")) {
in = new ZipArchiveInputStream(in);
}
return in;
}
public void parse(String fileName, IOMXmlParser parser)
throws XMLStreamException, ParseException {
parser.parse(new OMObjectBuilder());
}
public IStatus readAll(URI resourceUri, IProgressMonitor monitor) {
String fileName = (resourceUri.isFile() ? resourceUri.toFileString()
: resourceUri.toString());
List<String> errors = new ArrayList<String>();
InputStream in = null;
try {
in = inputStreamForFile(resourceUri);
if (in instanceof ArchiveInputStream) {
Set<String> entries = new HashSet<>();
ArchiveEntry entry;
while ((entry = ((ArchiveInputStream) in).getNextEntry()) != null) {
if (!entry.isDirectory()) {
String name = entry.getName().toLowerCase();
int index = name.lastIndexOf('.');
if (index >= 0
&& extensions.contains(name
.substring(index + 1))) {
entries.add(entry.getName());
}
}
}
in.close();
monitor.beginTask("Reading files", entries.size());
in = inputStreamForFile(resourceUri);
while ((entry = ((ArchiveInputStream) in).getNextEntry()) != null) {
if (!entry.isDirectory()
&& entries.contains(entry.getName())) {
monitor.subTask("Reading " + entry.getName());
readSingle(entry.getName(), in, errors);
monitor.worked(1);
if (monitor.isCanceled()) {
break;
}
}
}
} else {
monitor.beginTask("Reading file " + fileName, 1);
readSingle(fileName, in, errors);
}
monitor.done();
// explicitly close input stream
in.close();
} catch (IOException e) {
errors.add("Unable to read file \"" + fileName + "\": "
+ e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
if (!errors.isEmpty()) {
final MultiStatus status = new MultiStatus(MathActivator.PLUGIN_ID,
0, "Failed to read one or more content dictionaries", null);
for (String error : errors) {
status.add(new Status(Status.ERROR, MathActivator.PLUGIN_ID,
error));
}
return status;
}
return Status.OK_STATUS;
}
protected void readSingle(String fileName, InputStream in,
List<String> errors) {
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory
.createXMLStreamReader(new InputStreamReader(in) {
@Override
public void close() throws IOException {
// do not close stream
}
});
IOMXmlParser parser = fileName.toLowerCase().endsWith(".ocd") ? new OMCDParser(
reader) : new OMXmlParser(reader);
parse(fileName, parser);
} catch (XMLStreamException xse) {
errors.add("File \"" + fileName + "\": " + xse.getMessage());
} catch (ParseException pe) {
errors.add("File \"" + fileName + "\": " + pe);
} catch (Exception e) {
errors.add("Processing file \"" + fileName + "\" failed: " + e);
}
}
} | UTF-8 | Java | 5,037 | java | OMReader.java | Java | []
| null | []
| package org.numerateweb.math.xml;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import net.enilink.komma.core.URI;
import net.enilink.komma.model.IURIConverter;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.numerateweb.math.MathActivator;
import org.numerateweb.math.model.OMObjectBuilder;
import org.numerateweb.math.om.cd.OMCDParser;
import org.numerateweb.math.util.stax.ParseException;
public class OMReader {
Collection<String> extensions;
public OMReader(Collection<String> extensions) {
this.extensions = extensions;
}
protected IURIConverter getURIConverter() {
return null;
}
protected InputStream inputStreamForFile(URI resourceUri)
throws IOException {
String testPath = resourceUri.toString().toLowerCase();
InputStream in;
IURIConverter uriConverter = getURIConverter();
if (uriConverter == null) {
try {
in = new java.net.URI(resourceUri.toString()).toURL()
.openStream();
} catch (URISyntaxException e) {
throw new IOException("Unable to open file: " + resourceUri);
}
} else {
in = uriConverter.createInputStream(resourceUri);
}
if (testPath.endsWith(".gz")) {
in = new GZIPInputStream(in);
if (testPath.endsWith(".tar.gz")) {
in = new TarArchiveInputStream(in);
}
} else if (testPath.endsWith(".zip")) {
in = new ZipArchiveInputStream(in);
}
return in;
}
public void parse(String fileName, IOMXmlParser parser)
throws XMLStreamException, ParseException {
parser.parse(new OMObjectBuilder());
}
public IStatus readAll(URI resourceUri, IProgressMonitor monitor) {
String fileName = (resourceUri.isFile() ? resourceUri.toFileString()
: resourceUri.toString());
List<String> errors = new ArrayList<String>();
InputStream in = null;
try {
in = inputStreamForFile(resourceUri);
if (in instanceof ArchiveInputStream) {
Set<String> entries = new HashSet<>();
ArchiveEntry entry;
while ((entry = ((ArchiveInputStream) in).getNextEntry()) != null) {
if (!entry.isDirectory()) {
String name = entry.getName().toLowerCase();
int index = name.lastIndexOf('.');
if (index >= 0
&& extensions.contains(name
.substring(index + 1))) {
entries.add(entry.getName());
}
}
}
in.close();
monitor.beginTask("Reading files", entries.size());
in = inputStreamForFile(resourceUri);
while ((entry = ((ArchiveInputStream) in).getNextEntry()) != null) {
if (!entry.isDirectory()
&& entries.contains(entry.getName())) {
monitor.subTask("Reading " + entry.getName());
readSingle(entry.getName(), in, errors);
monitor.worked(1);
if (monitor.isCanceled()) {
break;
}
}
}
} else {
monitor.beginTask("Reading file " + fileName, 1);
readSingle(fileName, in, errors);
}
monitor.done();
// explicitly close input stream
in.close();
} catch (IOException e) {
errors.add("Unable to read file \"" + fileName + "\": "
+ e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
if (!errors.isEmpty()) {
final MultiStatus status = new MultiStatus(MathActivator.PLUGIN_ID,
0, "Failed to read one or more content dictionaries", null);
for (String error : errors) {
status.add(new Status(Status.ERROR, MathActivator.PLUGIN_ID,
error));
}
return status;
}
return Status.OK_STATUS;
}
protected void readSingle(String fileName, InputStream in,
List<String> errors) {
try {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory
.createXMLStreamReader(new InputStreamReader(in) {
@Override
public void close() throws IOException {
// do not close stream
}
});
IOMXmlParser parser = fileName.toLowerCase().endsWith(".ocd") ? new OMCDParser(
reader) : new OMXmlParser(reader);
parse(fileName, parser);
} catch (XMLStreamException xse) {
errors.add("File \"" + fileName + "\": " + xse.getMessage());
} catch (ParseException pe) {
errors.add("File \"" + fileName + "\": " + pe);
} catch (Exception e) {
errors.add("Processing file \"" + fileName + "\" failed: " + e);
}
}
} | 5,037 | 0.687512 | 0.68652 | 164 | 29.719513 | 20.92861 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.158537 | false | false | 2 |
a15ec41f047be827aeb44374fd632d9c520905ec | 11,613,591,613,607 | 59313019db59049b3a95712f48ebb15bb9f1af79 | /src/advancejava/d3/MultipleInterfaces.java | bf6d8058ef50bfa5e14e82483e7f5c8f77273ce2 | []
| no_license | dichharai/100DaysOfCode | https://github.com/dichharai/100DaysOfCode | aef83ffa759459d2e16b2d91ad7b117c2dfa4f16 | f0ff49b714c052887fee13bbd656ccac99143e74 | refs/heads/master | 2021-09-12T17:00:04.265000 | 2018-04-19T03:41:48 | 2018-04-19T03:41:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package advancejava.d3;
/**
*
* @author dichha
*/
/*
In contrast to C++ and some other languages, Jaca does not support multiple
inheritance: in Java every class has exactly one direct parent (with Object
class being on top of the hierarchy. However, the class may implement multiple
interfaces and as such, stacking interfaces is the only way to achieve (or mimic)
multiple inheritace in Java.
*/
public class MultipleInterfaces implements Runnable, AutoCloseable{
@Override
public void run(){
// some implementation here
}
@Override
public void close() throws Exception{
// some implementation here
}
/*
Implementation of multiple interfaces is in fact quite powerful, but often the
need to reuse an implementation leads to deep class hierarchies as a way to
overcome the absence of multiple inheritance support in Java.
*/
/*
public class A implements Runnable{
@Override
public void run(){
// some implementation here
}
}
public class B extends A implements AutoCloseable{
@Override
public void close() throws Exception{
// some implementation here
}
}
public class C extends B implements Readable{
@Override
public int read(java.nio.CharBuffer cb) throws IOException{
// Some implementation here
}
}
*/
}
| UTF-8 | Java | 1,678 | java | MultipleInterfaces.java | Java | [
{
"context": "*/\r\npackage advancejava.d3;\r\n\r\n/**\r\n *\r\n * @author dichha\r\n */\r\n/*\r\nIn contrast to C++ and some other ",
"end": 238,
"score": 0.8425803780555725,
"start": 237,
"tag": "NAME",
"value": "d"
},
{
"context": "\r\npackage advancejava.d3;\r\n\r\n/**\r\n *\r\n * @author dichha\r\n */\r\n/*\r\nIn contrast to C++ and some other langu",
"end": 243,
"score": 0.7220264673233032,
"start": 238,
"tag": "USERNAME",
"value": "ichha"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package advancejava.d3;
/**
*
* @author dichha
*/
/*
In contrast to C++ and some other languages, Jaca does not support multiple
inheritance: in Java every class has exactly one direct parent (with Object
class being on top of the hierarchy. However, the class may implement multiple
interfaces and as such, stacking interfaces is the only way to achieve (or mimic)
multiple inheritace in Java.
*/
public class MultipleInterfaces implements Runnable, AutoCloseable{
@Override
public void run(){
// some implementation here
}
@Override
public void close() throws Exception{
// some implementation here
}
/*
Implementation of multiple interfaces is in fact quite powerful, but often the
need to reuse an implementation leads to deep class hierarchies as a way to
overcome the absence of multiple inheritance support in Java.
*/
/*
public class A implements Runnable{
@Override
public void run(){
// some implementation here
}
}
public class B extends A implements AutoCloseable{
@Override
public void close() throws Exception{
// some implementation here
}
}
public class C extends B implements Readable{
@Override
public int read(java.nio.CharBuffer cb) throws IOException{
// Some implementation here
}
}
*/
}
| 1,678 | 0.643623 | 0.643027 | 56 | 27.964285 | 26.813486 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.160714 | false | false | 2 |
62b5cf54aa90cf746dd5f13004ef9a2f5e766c81 | 19,731,079,803,673 | 830bf1ff8f209d354ca7ac465022d237fb616018 | /SpringMVCDefault/src/main/java/com/pooh/springdefault/common/SpringDaoSupport.java | 9f5e9e39f5ce569c8282a1dfb79f42a411fbfa68 | []
| no_license | baehoyeon/SpringBasic | https://github.com/baehoyeon/SpringBasic | 4fe273a6cedde04d3a46e75e075fb509effed265 | 46684552291cf5ce85292536f58cc13235237a8f | HEAD | 2016-09-10T19:21:57.671000 | 2016-07-18T14:43:43 | 2016-07-18T14:43:43 | 59,396,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pooh.springdefault.common;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author pooh.explorer
*/
public class SpringDaoSupport extends SqlSessionDaoSupport {
protected final String NAMESPACE = this.getClass().getSimpleName() + ".";
@Autowired
@Qualifier("sqlSessionFactory")
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionTemplate(new SqlSessionTemplate(sqlSessionFactory,
sqlSessionFactory.getConfiguration().getDefaultExecutorType()));
}
protected String getNamespace() {
return NAMESPACE;
}
} | UTF-8 | Java | 813 | java | SpringDaoSupport.java | Java | [
{
"context": "eans.factory.annotation.Qualifier;\n\n/**\n * @author pooh.explorer\n */\npublic class SpringDaoSupport extends SqlSess",
"end": 349,
"score": 0.9946027994155884,
"start": 336,
"tag": "USERNAME",
"value": "pooh.explorer"
}
]
| null | []
| package com.pooh.springdefault.common;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author pooh.explorer
*/
public class SpringDaoSupport extends SqlSessionDaoSupport {
protected final String NAMESPACE = this.getClass().getSimpleName() + ".";
@Autowired
@Qualifier("sqlSessionFactory")
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionTemplate(new SqlSessionTemplate(sqlSessionFactory,
sqlSessionFactory.getConfiguration().getDefaultExecutorType()));
}
protected String getNamespace() {
return NAMESPACE;
}
} | 813 | 0.815498 | 0.815498 | 25 | 31.559999 | 27.620398 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 2 |
ec4a60fbe74406d16092bb306b5862923cd037db | 240,518,234,366 | d60c61b04b8717eb79f5cb55ba06be8b57e53f5e | /src/main/java/com/lx/animation/config/MyFactoryBean.java | e36adb3b41a209d846260525f15d525cf8e43dbe | []
| no_license | tttoad/web | https://github.com/tttoad/web | 930f0c9bc9bcbc6bdd0e24dc71ac3eaa6595f271 | 227c9a398a4a62de31e2a2366e1e99a810092988 | refs/heads/master | 2021-10-22T14:53:19.106000 | 2019-03-11T14:49:44 | 2019-03-11T14:49:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lx.animation.config;
import com.lx.animation.util.JedisCache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.List;
public class MyFactoryBean implements FactoryBean<JedisCache>,MyInterface {
@Override
public JedisCache getObject() throws Exception {
return new JedisCache();
}
@Override
public Class<?> getObjectType() {
return JedisCache.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public void setQccc(List<String> list) {
}
}
| UTF-8 | Java | 741 | java | MyFactoryBean.java | Java | []
| null | []
| package com.lx.animation.config;
import com.lx.animation.util.JedisCache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.List;
public class MyFactoryBean implements FactoryBean<JedisCache>,MyInterface {
@Override
public JedisCache getObject() throws Exception {
return new JedisCache();
}
@Override
public Class<?> getObjectType() {
return JedisCache.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public void setQccc(List<String> list) {
}
}
| 741 | 0.728745 | 0.728745 | 33 | 21.454546 | 21.661432 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 2 |
d5d91a9bd4e4f372a21d7639d9858654804016a4 | 26,783,416,123,106 | bcb9afdb8d4b8916dec5aa4c0167a8a945ff8705 | /src/com/lenovo/cobweb/http/MainSocketServer.java | 999336829ccd99c648c338472ba3fcf06d06f747 | []
| no_license | kiddliu/nanao-android | https://github.com/kiddliu/nanao-android | 7494dbdfd8bfdc497ed98e0845a400986556257d | 7f1441e84c9d70339956f1070e34d45044c94285 | refs/heads/master | 2016-08-06T20:07:21.357000 | 2014-09-23T06:40:20 | 2014-09-23T06:40:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lenovo.cobweb.http;
import android.content.Context;
import android.util.Log;
import com.lenovo.cobweb.MainService;
import com.lenovo.cobweb.WebSocketInterface;
import com.lenovo.cobweb.core.Engine;
import com.lenovo.cobweb.network.SocketActivity;
import com.lenovo.cobweb.protocol.impl.CobwebCmdRequest;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
public class MainSocketServer extends WebSocketServer implements WebSocketInterface {
private Context mContext;
static WebSocket mConnection = null;
public MainSocketServer(final Context context, final int port) throws UnknownHostException {
super(new InetSocketAddress(port));
this.mContext = context;
}
public MainSocketServer(final InetSocketAddress address) {
super(address);
}
@Override
public void onOpen(final WebSocket conn, final ClientHandshake handshake) {
String sIpAddress = conn.getRemoteSocketAddress().getAddress().getHostAddress();
Engine.getEngine().RegisterNotifyInterface(this);
System.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress());
if ((mConnection == null) || (mConnection == conn))
{
SocketActivity.SendMsg2Client("IpAddress", sIpAddress, MainService.MSG_CLIENT_CONNECTED);
}
}
@Override
public void onClose(final WebSocket conn, final int code, final String reason,
final boolean remote) {
System.out.println(conn + " closed");
Engine.getEngine().RegisterNotifyInterface(null);
if (mConnection == conn)
{
SocketActivity.SendMsg2Client(null, null, MainService.MSG_CLIENT_DISCONNECT);
mConnection = null;
CheckConnection();
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static void PrintTimer(String sInfo)
{
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSZ");
Date curDate = new Date(System.currentTimeMillis());
String str = sInfo + " " + formatter.format(curDate);
Log.v("Timer", str);
}
public static String byteArrayToHexString(byte[] array) {
StringBuffer hexString = new StringBuffer();
for (byte b : array) {
int intVal = b & 0xff;
if (intVal < 0x10)
hexString.append("0");
hexString.append(Integer.toHexString(intVal));
}
return hexString.toString();
}
@Override
public void onMessage(final WebSocket conn, final String message) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, Boolean.FALSE);
byte[] sByte = hexStringToByteArray(message);
String sAesKey = Engine.getAesKey();
String enJason = new String(Crypto.decrypt(sByte, sAesKey));
enJason = enJason.trim();
CobwebCmdRequest cmdRequest = mapper.readValue(enJason, CobwebCmdRequest.class);
String sQCode = cmdRequest.getToken();
if ((null == sQCode) || (sQCode.isEmpty()))
{
conn.close();
return;
}
if ((conn != mConnection) && (Engine.getEngine().msQCode.equals(sQCode)))
{
if (mConnection != null)
{
mConnection.close();
}
mConnection = conn;
CheckConnection();
}
String sValues = Engine.analysisCmd(cmdRequest.getId(), cmdRequest.getData(),cmdRequest.getToken());
byte[] bytesSnd = Crypto.encrypt(sValues, sAesKey);
String sResponse = byteArrayToHexString(bytesSnd);
conn.send(sResponse);
}
catch (IOException e) {
throw new RuntimeException(e);
}
catch (Exception e) {
e.printStackTrace();
conn.close();
}
System.out.println(conn + ": " + message);
}
@Override
public void onError(final WebSocket conn, final Exception ex) {
ex.printStackTrace();
if (conn != null) {
System.out.println("Error: " + conn);
}
}
public void sendToAll(final String text)
{
final Collection<WebSocket> con = connections();
for (final WebSocket c : con)
{
c.send(text);
}
}
@Override
public void NotifyToAll(String text)
{
Collection<WebSocket> con = connections();
for (WebSocket c : con)
{
try
{
String sAesKey = Engine.getAesKey();
byte[] bytesSnd = new byte[0];
bytesSnd = Crypto.encrypt(text, sAesKey);
String sResponse = byteArrayToHexString(bytesSnd);
c.send(sResponse);
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
}
}
public void CheckConnection()
{
if (null != mConnection)
{
Engine.getEngine().acquireWakeLock();
}
else
{
Engine.getEngine().releaseWakLock();
}
}
}
| UTF-8 | Java | 5,881 | java | MainSocketServer.java | Java | []
| null | []
| package com.lenovo.cobweb.http;
import android.content.Context;
import android.util.Log;
import com.lenovo.cobweb.MainService;
import com.lenovo.cobweb.WebSocketInterface;
import com.lenovo.cobweb.core.Engine;
import com.lenovo.cobweb.network.SocketActivity;
import com.lenovo.cobweb.protocol.impl.CobwebCmdRequest;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
public class MainSocketServer extends WebSocketServer implements WebSocketInterface {
private Context mContext;
static WebSocket mConnection = null;
public MainSocketServer(final Context context, final int port) throws UnknownHostException {
super(new InetSocketAddress(port));
this.mContext = context;
}
public MainSocketServer(final InetSocketAddress address) {
super(address);
}
@Override
public void onOpen(final WebSocket conn, final ClientHandshake handshake) {
String sIpAddress = conn.getRemoteSocketAddress().getAddress().getHostAddress();
Engine.getEngine().RegisterNotifyInterface(this);
System.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress());
if ((mConnection == null) || (mConnection == conn))
{
SocketActivity.SendMsg2Client("IpAddress", sIpAddress, MainService.MSG_CLIENT_CONNECTED);
}
}
@Override
public void onClose(final WebSocket conn, final int code, final String reason,
final boolean remote) {
System.out.println(conn + " closed");
Engine.getEngine().RegisterNotifyInterface(null);
if (mConnection == conn)
{
SocketActivity.SendMsg2Client(null, null, MainService.MSG_CLIENT_DISCONNECT);
mConnection = null;
CheckConnection();
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static void PrintTimer(String sInfo)
{
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSZ");
Date curDate = new Date(System.currentTimeMillis());
String str = sInfo + " " + formatter.format(curDate);
Log.v("Timer", str);
}
public static String byteArrayToHexString(byte[] array) {
StringBuffer hexString = new StringBuffer();
for (byte b : array) {
int intVal = b & 0xff;
if (intVal < 0x10)
hexString.append("0");
hexString.append(Integer.toHexString(intVal));
}
return hexString.toString();
}
@Override
public void onMessage(final WebSocket conn, final String message) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, Boolean.FALSE);
byte[] sByte = hexStringToByteArray(message);
String sAesKey = Engine.getAesKey();
String enJason = new String(Crypto.decrypt(sByte, sAesKey));
enJason = enJason.trim();
CobwebCmdRequest cmdRequest = mapper.readValue(enJason, CobwebCmdRequest.class);
String sQCode = cmdRequest.getToken();
if ((null == sQCode) || (sQCode.isEmpty()))
{
conn.close();
return;
}
if ((conn != mConnection) && (Engine.getEngine().msQCode.equals(sQCode)))
{
if (mConnection != null)
{
mConnection.close();
}
mConnection = conn;
CheckConnection();
}
String sValues = Engine.analysisCmd(cmdRequest.getId(), cmdRequest.getData(),cmdRequest.getToken());
byte[] bytesSnd = Crypto.encrypt(sValues, sAesKey);
String sResponse = byteArrayToHexString(bytesSnd);
conn.send(sResponse);
}
catch (IOException e) {
throw new RuntimeException(e);
}
catch (Exception e) {
e.printStackTrace();
conn.close();
}
System.out.println(conn + ": " + message);
}
@Override
public void onError(final WebSocket conn, final Exception ex) {
ex.printStackTrace();
if (conn != null) {
System.out.println("Error: " + conn);
}
}
public void sendToAll(final String text)
{
final Collection<WebSocket> con = connections();
for (final WebSocket c : con)
{
c.send(text);
}
}
@Override
public void NotifyToAll(String text)
{
Collection<WebSocket> con = connections();
for (WebSocket c : con)
{
try
{
String sAesKey = Engine.getAesKey();
byte[] bytesSnd = new byte[0];
bytesSnd = Crypto.encrypt(text, sAesKey);
String sResponse = byteArrayToHexString(bytesSnd);
c.send(sResponse);
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
}
}
public void CheckConnection()
{
if (null != mConnection)
{
Engine.getEngine().acquireWakeLock();
}
else
{
Engine.getEngine().releaseWakLock();
}
}
}
| 5,881 | 0.60891 | 0.605849 | 205 | 27.687805 | 26.330917 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731707 | false | false | 2 |
d367b74f2ce70423464d5074a1dd635c798c0f95 | 24,859,270,728,319 | 2ccd749117941f812d6f09a3dc40820f80e8b79d | /String_Practice/src/com/codewithraju/string/LowerCaseCount.java | c46f052f8b2ef5c21230b900894779e6267765a8 | []
| no_license | enraj26/Basic-Java-CodingPractice | https://github.com/enraj26/Basic-Java-CodingPractice | d1ad431ff606d6d0d08fdc855b48998734977e32 | 71fa70e3c44863f4e6d1e6cf891bd7ede141cb59 | refs/heads/master | 2023-05-02T22:43:13.996000 | 2021-05-20T15:11:44 | 2021-05-20T15:11:44 | 369,247,778 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codewithraju.string;
public class LowerCaseCount {
public static void main(String[] args) {
String str = "Hello I am From Ongole";
int count = getLowerCount(str);
System.out.println(count);
}
static int getLowerCount(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
int ascii = charAt;
if (ascii >= 97 & ascii <= 122) {
count++;
}
}
return count;
}
}
| UTF-8 | Java | 451 | java | LowerCaseCount.java | Java | []
| null | []
| package com.codewithraju.string;
public class LowerCaseCount {
public static void main(String[] args) {
String str = "Hello I am From Ongole";
int count = getLowerCount(str);
System.out.println(count);
}
static int getLowerCount(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
int ascii = charAt;
if (ascii >= 97 & ascii <= 122) {
count++;
}
}
return count;
}
}
| 451 | 0.62306 | 0.607539 | 23 | 18.608696 | 15.796915 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.956522 | false | false | 2 |
c26cdb5567f039106b0651654e392cf23a4440d1 | 5,763,846,176,268 | cc7936260b439d259d1dc5f07b5269b9501496f0 | /src/main/java/com/jf/mydemo/mytest/Utils/date/WeekDateKit.java | d12ee5df580af482e800c1493fc35cddf019213a | []
| no_license | Monkey-D-Jie/MyTest | https://github.com/Monkey-D-Jie/MyTest | d392057eae39e8febe5917c542200d895f67b4bb | 588d122cbea8f8dbfa893b78a9845c7aaf5f5fee | refs/heads/master | 2020-03-19T07:22:19.263000 | 2019-06-19T01:54:51 | 2019-06-19T01:54:51 | 136,108,158 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jf.mydemo.mytest.Utils.date;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WeekDateKit {
private static final int WEEK = 7;
private static final long MILLISECONDS_PER_DAY = 24L * 3600 * 1000;
/**
* 由学期开始时间,周次,星期几获取到星期数对应的日期
* Created by wjie on 2017/9/15 0015.
*/
public static String getWeekDate(Date sbeginDate, int weekday, int weeks, String dateFormat) {
String date = "";
if (sbeginDate != null && weekday != 0 && weeks != 0) {
Map<String, Object> weekMap = new HashMap<String, Object>();
Calendar cal = Calendar.getInstance();
cal.setTime(sbeginDate);
/*判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了*/
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
/*设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一*/
cal.setFirstDayOfWeek(Calendar.MONDAY);
/*获得当前日期是一个星期的第几天*/
int day = cal.get(Calendar.DAY_OF_WEEK);
/*根据日历的规则,给当前日期减去星期几与一个星期第一天的差值*/
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
/*获取到传入日期所在周的周一*/
long time = cal.getTime().getTime()+(weeks-1)*WEEK*MILLISECONDS_PER_DAY;
Date mondayDate = new Date(time);
for (int i = 1; i <= WEEK; i++) {
String weekDay = DateFormatKit.convert(dateFormat,DateCalculateKit.addDate(mondayDate,i-1));
weekMap.put("week"+i, weekDay);
}
date = String.valueOf(weekMap.get("week" + weekday));
}
return date;
}
}
| UTF-8 | Java | 2,022 | java | WeekDateKit.java | Java | [
{
"context": " * 由学期开始时间,周次,星期几获取到星期数对应的日期\n * Created by wjie on 2017/9/15 0015.\n */\n public static Stri",
"end": 345,
"score": 0.9996221661567688,
"start": 341,
"tag": "USERNAME",
"value": "wjie"
}
]
| null | []
| package com.jf.mydemo.mytest.Utils.date;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WeekDateKit {
private static final int WEEK = 7;
private static final long MILLISECONDS_PER_DAY = 24L * 3600 * 1000;
/**
* 由学期开始时间,周次,星期几获取到星期数对应的日期
* Created by wjie on 2017/9/15 0015.
*/
public static String getWeekDate(Date sbeginDate, int weekday, int weeks, String dateFormat) {
String date = "";
if (sbeginDate != null && weekday != 0 && weeks != 0) {
Map<String, Object> weekMap = new HashMap<String, Object>();
Calendar cal = Calendar.getInstance();
cal.setTime(sbeginDate);
/*判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了*/
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
/*设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一*/
cal.setFirstDayOfWeek(Calendar.MONDAY);
/*获得当前日期是一个星期的第几天*/
int day = cal.get(Calendar.DAY_OF_WEEK);
/*根据日历的规则,给当前日期减去星期几与一个星期第一天的差值*/
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
/*获取到传入日期所在周的周一*/
long time = cal.getTime().getTime()+(weeks-1)*WEEK*MILLISECONDS_PER_DAY;
Date mondayDate = new Date(time);
for (int i = 1; i <= WEEK; i++) {
String weekDay = DateFormatKit.convert(dateFormat,DateCalculateKit.addDate(mondayDate,i-1));
weekMap.put("week"+i, weekDay);
}
date = String.valueOf(weekMap.get("week" + weekday));
}
return date;
}
}
| 2,022 | 0.585664 | 0.568765 | 46 | 36.304348 | 26.360271 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.73913 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.