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
cce7d7cd74860efc513f8ee78b56dd0d99a2fddb
3,238,405,378,383
328e5512d2cc764a6a182596e6a4745d48375ae7
/ddxj-worker-bll/src/main/java/net/zn/ddxj/entity/CreditRepayment.java
e6852ac6d5d4ff0f10a0de541726cdcf83fffe4e
[]
no_license
yangbingkun315/cms
https://github.com/yangbingkun315/cms
e67b1b0958d9b390198290a22d2b9bfd30880ea5
80c494db4c76e1540bee7861f312374a6492abd4
refs/heads/master
2022-12-12T13:28:49.419000
2019-07-04T13:34:43
2019-07-04T13:34:43
163,160,603
0
1
null
false
2022-12-06T00:30:54
2018-12-26T09:14:38
2019-07-04T13:35:41
2022-12-06T00:30:54
17,419
0
1
10
TSQL
false
false
package net.zn.ddxj.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 授信资金变动记录 * * @author wcyong * * @date 2018-05-14 */ public class CreditRepayment implements Serializable{ /** * */ private static final long serialVersionUID = 3655131672262569776L; /** * 主键ID */ private Integer id; /** * 授信记录ID */ private Integer recruitCreditId; /** * 交易金额 */ private BigDecimal businessMoney; /** * 用途 */ private String application; /** * 类型(1-发放,2-还款) */ private Integer type; /** * 交易状态 (1审核中,2审核成功,3审核失败) */ private Integer businessStatus; /** * 收款人姓名 */ private String payeeName; /** * 收款人ID */ private Integer userId; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; /** * 是否有效 */ private Integer flag; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getRecruitCreditId() { return recruitCreditId; } public void setRecruitCreditId(Integer recruitCreditId) { this.recruitCreditId = recruitCreditId; } public BigDecimal getBusinessMoney() { return businessMoney; } public void setBusinessMoney(BigDecimal businessMoney) { this.businessMoney = businessMoney; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application == null ? null : application.trim(); } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getBusinessStatus() { return businessStatus; } public void setBusinessStatus(Integer businessStatus) { this.businessStatus = businessStatus; } public String getPayeeName() { return payeeName; } public void setPayeeName(String payeeName) { this.payeeName = payeeName == null ? null : payeeName.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getFlag() { return flag; } public void setFlag(Integer flag) { this.flag = flag; } }
UTF-8
Java
3,109
java
CreditRepayment.java
Java
[ { "context": "va.util.Date;\r\n\r\n/**\r\n * 授信资金变动记录\r\n * \r\n * @author wcyong\r\n * \r\n * @date 2018-05-14\r\n */\r\npublic class Cred", "end": 157, "score": 0.9996710419654846, "start": 151, "tag": "USERNAME", "value": "wcyong" } ]
null
[]
package net.zn.ddxj.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 授信资金变动记录 * * @author wcyong * * @date 2018-05-14 */ public class CreditRepayment implements Serializable{ /** * */ private static final long serialVersionUID = 3655131672262569776L; /** * 主键ID */ private Integer id; /** * 授信记录ID */ private Integer recruitCreditId; /** * 交易金额 */ private BigDecimal businessMoney; /** * 用途 */ private String application; /** * 类型(1-发放,2-还款) */ private Integer type; /** * 交易状态 (1审核中,2审核成功,3审核失败) */ private Integer businessStatus; /** * 收款人姓名 */ private String payeeName; /** * 收款人ID */ private Integer userId; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; /** * 是否有效 */ private Integer flag; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getRecruitCreditId() { return recruitCreditId; } public void setRecruitCreditId(Integer recruitCreditId) { this.recruitCreditId = recruitCreditId; } public BigDecimal getBusinessMoney() { return businessMoney; } public void setBusinessMoney(BigDecimal businessMoney) { this.businessMoney = businessMoney; } public String getApplication() { return application; } public void setApplication(String application) { this.application = application == null ? null : application.trim(); } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getBusinessStatus() { return businessStatus; } public void setBusinessStatus(Integer businessStatus) { this.businessStatus = businessStatus; } public String getPayeeName() { return payeeName; } public void setPayeeName(String payeeName) { this.payeeName = payeeName == null ? null : payeeName.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getFlag() { return flag; } public void setFlag(Integer flag) { this.flag = flag; } }
3,109
0.558537
0.547803
164
16.189024
17.324581
75
false
false
0
0
0
0
0
0
0.323171
false
false
8
aa415371cabffccaf9c8e6ee981174d2024d280b
3,891,240,399,749
17aa9d1a86095bfdb90344979fd04dba3ca0b753
/src/main/java/io/github/cottonmc/resources/tag/BiomeTags.java
019e107c55b60545314d944a7e608bd471a99343
[ "MIT" ]
permissive
SDUBZ/CottonResources
https://github.com/SDUBZ/CottonResources
ca686475c109d54d3692a7d7436211a208757bba
6d71d6762f87fb8ba76e9e44c0d3911764add832
refs/heads/master
2020-12-09T03:40:24.485000
2020-01-11T09:44:48
2020-01-11T09:44:48
233,180,482
0
0
MIT
true
2020-01-11T05:22:05
2020-01-11T05:18:55
2020-01-11T05:18:57
2020-01-11T05:22:05
774
0
0
0
null
false
false
package io.github.cottonmc.resources.tag; import java.util.Optional; import net.minecraft.tag.TagContainer; import net.minecraft.world.biome.Biome; /** * Now you can tag Biomes! */ public class BiomeTags { public static TagContainer<Biome> CONTAINER = new TagContainer<>((identifier)->{ return Optional.empty(); }, "", false, ""); public static TagContainer<Biome> getContainer() { return CONTAINER; } static void setContainer(TagContainer<Biome> container) { CONTAINER = container; } }
UTF-8
Java
500
java
BiomeTags.java
Java
[ { "context": "package io.github.cottonmc.resources.tag;\n\nimport java.util.Optional;\n\nimpor", "end": 26, "score": 0.9990549087524414, "start": 18, "tag": "USERNAME", "value": "cottonmc" } ]
null
[]
package io.github.cottonmc.resources.tag; import java.util.Optional; import net.minecraft.tag.TagContainer; import net.minecraft.world.biome.Biome; /** * Now you can tag Biomes! */ public class BiomeTags { public static TagContainer<Biome> CONTAINER = new TagContainer<>((identifier)->{ return Optional.empty(); }, "", false, ""); public static TagContainer<Biome> getContainer() { return CONTAINER; } static void setContainer(TagContainer<Biome> container) { CONTAINER = container; } }
500
0.74
0.74
18
26.777779
27.095625
83
false
false
0
0
0
0
0
0
1
false
false
8
6922a9692fb55088abde234fec44201bf9cb7200
2,714,419,398,448
26f9bee24d8f86be5075fcfe4aa715bb5790b1b4
/shopxx/src/net/shopxx/entity/PaymentConfig.java
a6f5568aee2eda1fe8ad06ecca46b21a515e7247
[]
no_license
dalinhuang/concourse
https://github.com/dalinhuang/concourse
d9826f9cd113b0ae7862cdaa298051ebbf1e66c8
2fdde7a0b72ec60fc8d1908020282fc50736a29b
refs/heads/master
2018-01-08T22:07:53.508000
2013-05-18T14:23:13
2013-05-18T14:23:13
50,279,072
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.shopxx.entity; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; import net.shopxx.util.SettingUtil; /** * 实体类 - 支付配置 * ============================================================================ * 版权所有 2008-2010 长沙鼎诚软件有限公司,并保留所有权利。 * ---------------------------------------------------------------------------- * 提示:在未取得SHOP++商业授权之前,您不能将本软件应用于商业用途,否则SHOP++将保留追究的权力。 * ---------------------------------------------------------------------------- * 官方网站:http://www.shopxx.net * ---------------------------------------------------------------------------- * KEY: SHOPXXDA3F0780A7AFA10368BF915483346760 * ============================================================================ */ @Entity public class PaymentConfig extends BaseEntity { private static final long serialVersionUID = -7950849648189504426L; // 支付配置类型(预存款、线下支付、在线支付) public enum PaymentConfigType { deposit, offline, online }; // 支付手续费类型(按比例收费、固定费用) public enum PaymentFeeType { scale, fixed } private PaymentConfigType paymentConfigType;// 支付配置类型 private String paymentProductId;// 支付产品标识 private String name;// 支付方式名称 private String bargainorId;// 商家ID private String bargainorKey;// 商户私钥 private PaymentFeeType paymentFeeType;// 支付手续费类型 private BigDecimal paymentFee;// 支付费用 private String description;// 介绍 private Integer orderList;// 排序 private Set<Order> orderSet = new HashSet<Order>();// 订单 private Set<Payment> paymentSet = new HashSet<Payment>();// 支付 private Set<Refund> refundSet = new HashSet<Refund>();// 退款 @Enumerated @Column(nullable = false, updatable = false) public PaymentConfigType getPaymentConfigType() { return paymentConfigType; } public void setPaymentConfigType(PaymentConfigType paymentConfigType) { this.paymentConfigType = paymentConfigType; } @Column(updatable = false) public String getPaymentProductId() { return paymentProductId; } public void setPaymentProductId(String paymentProductId) { this.paymentProductId = paymentProductId; } @Column(nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBargainorId() { return bargainorId; } public void setBargainorId(String bargainorId) { this.bargainorId = bargainorId; } public String getBargainorKey() { return bargainorKey; } public void setBargainorKey(String bargainorKey) { this.bargainorKey = bargainorKey; } @Enumerated @Column(nullable = false) public PaymentFeeType getPaymentFeeType() { return paymentFeeType; } public void setPaymentFeeType(PaymentFeeType paymentFeeType) { this.paymentFeeType = paymentFeeType; } @Column(nullable = false, precision = 15, scale = 5) public BigDecimal getPaymentFee() { return paymentFee; } public void setPaymentFee(BigDecimal paymentFee) { this.paymentFee = SettingUtil.setPriceScale(paymentFee); } @Column(length = 3000) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getOrderList() { return orderList; } public void setOrderList(Integer orderList) { this.orderList = orderList; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Order> getOrderSet() { return orderSet; } public void setOrderSet(Set<Order> orderSet) { this.orderSet = orderSet; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Payment> getPaymentSet() { return paymentSet; } public void setPaymentSet(Set<Payment> paymentSet) { this.paymentSet = paymentSet; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Refund> getRefundSet() { return refundSet; } public void setRefundSet(Set<Refund> refundSet) { this.refundSet = refundSet; } // 保存处理 @Override @Transient public void onSave() { if (paymentFee == null || paymentFee.compareTo(new BigDecimal(0)) < 0) { paymentFee = new BigDecimal(0); } if (orderList == null || orderList < 0) { orderList = 0; } if (StringUtils.isEmpty(description)) { description = null; } } // 更新处理 @Override @Transient public void onUpdate() { if (paymentFee == null || paymentFee.compareTo(new BigDecimal(0)) < 0) { paymentFee = new BigDecimal(0); } if (orderList == null || orderList < 0) { orderList = 0; } if (StringUtils.isEmpty(description)) { description = null; } } /** * 根据总金额计算支付费用 * * @return 支付费用 */ @Transient public BigDecimal getPaymentFee(BigDecimal totalAmount) { BigDecimal paymentFee = new BigDecimal(0); if (paymentFeeType == PaymentFeeType.scale){ paymentFee = totalAmount.multiply(this.paymentFee.divide(new BigDecimal(100))); } else { paymentFee = this.paymentFee; } return SettingUtil.setPriceScale(paymentFee); } }
UTF-8
Java
5,729
java
PaymentConfig.java
Java
[ { "context": "-----------------------------------------\r\n * KEY: SHOPXXDA3F0780A7AFA10368BF915483346760\r\n * =============================================", "end": 934, "score": 0.9996966123580933, "start": 896, "tag": "KEY", "value": "SHOPXXDA3F0780A7AFA10368BF915483346760" } ]
null
[]
package net.shopxx.entity; import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Transient; import org.apache.commons.lang.StringUtils; import net.shopxx.util.SettingUtil; /** * 实体类 - 支付配置 * ============================================================================ * 版权所有 2008-2010 长沙鼎诚软件有限公司,并保留所有权利。 * ---------------------------------------------------------------------------- * 提示:在未取得SHOP++商业授权之前,您不能将本软件应用于商业用途,否则SHOP++将保留追究的权力。 * ---------------------------------------------------------------------------- * 官方网站:http://www.shopxx.net * ---------------------------------------------------------------------------- * KEY: <KEY> * ============================================================================ */ @Entity public class PaymentConfig extends BaseEntity { private static final long serialVersionUID = -7950849648189504426L; // 支付配置类型(预存款、线下支付、在线支付) public enum PaymentConfigType { deposit, offline, online }; // 支付手续费类型(按比例收费、固定费用) public enum PaymentFeeType { scale, fixed } private PaymentConfigType paymentConfigType;// 支付配置类型 private String paymentProductId;// 支付产品标识 private String name;// 支付方式名称 private String bargainorId;// 商家ID private String bargainorKey;// 商户私钥 private PaymentFeeType paymentFeeType;// 支付手续费类型 private BigDecimal paymentFee;// 支付费用 private String description;// 介绍 private Integer orderList;// 排序 private Set<Order> orderSet = new HashSet<Order>();// 订单 private Set<Payment> paymentSet = new HashSet<Payment>();// 支付 private Set<Refund> refundSet = new HashSet<Refund>();// 退款 @Enumerated @Column(nullable = false, updatable = false) public PaymentConfigType getPaymentConfigType() { return paymentConfigType; } public void setPaymentConfigType(PaymentConfigType paymentConfigType) { this.paymentConfigType = paymentConfigType; } @Column(updatable = false) public String getPaymentProductId() { return paymentProductId; } public void setPaymentProductId(String paymentProductId) { this.paymentProductId = paymentProductId; } @Column(nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBargainorId() { return bargainorId; } public void setBargainorId(String bargainorId) { this.bargainorId = bargainorId; } public String getBargainorKey() { return bargainorKey; } public void setBargainorKey(String bargainorKey) { this.bargainorKey = bargainorKey; } @Enumerated @Column(nullable = false) public PaymentFeeType getPaymentFeeType() { return paymentFeeType; } public void setPaymentFeeType(PaymentFeeType paymentFeeType) { this.paymentFeeType = paymentFeeType; } @Column(nullable = false, precision = 15, scale = 5) public BigDecimal getPaymentFee() { return paymentFee; } public void setPaymentFee(BigDecimal paymentFee) { this.paymentFee = SettingUtil.setPriceScale(paymentFee); } @Column(length = 3000) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getOrderList() { return orderList; } public void setOrderList(Integer orderList) { this.orderList = orderList; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Order> getOrderSet() { return orderSet; } public void setOrderSet(Set<Order> orderSet) { this.orderSet = orderSet; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Payment> getPaymentSet() { return paymentSet; } public void setPaymentSet(Set<Payment> paymentSet) { this.paymentSet = paymentSet; } @OneToMany(mappedBy = "paymentConfig", fetch = FetchType.LAZY) public Set<Refund> getRefundSet() { return refundSet; } public void setRefundSet(Set<Refund> refundSet) { this.refundSet = refundSet; } // 保存处理 @Override @Transient public void onSave() { if (paymentFee == null || paymentFee.compareTo(new BigDecimal(0)) < 0) { paymentFee = new BigDecimal(0); } if (orderList == null || orderList < 0) { orderList = 0; } if (StringUtils.isEmpty(description)) { description = null; } } // 更新处理 @Override @Transient public void onUpdate() { if (paymentFee == null || paymentFee.compareTo(new BigDecimal(0)) < 0) { paymentFee = new BigDecimal(0); } if (orderList == null || orderList < 0) { orderList = 0; } if (StringUtils.isEmpty(description)) { description = null; } } /** * 根据总金额计算支付费用 * * @return 支付费用 */ @Transient public BigDecimal getPaymentFee(BigDecimal totalAmount) { BigDecimal paymentFee = new BigDecimal(0); if (paymentFeeType == PaymentFeeType.scale){ paymentFee = totalAmount.multiply(this.paymentFee.divide(new BigDecimal(100))); } else { paymentFee = this.paymentFee; } return SettingUtil.setPriceScale(paymentFee); } }
5,696
0.649283
0.636059
213
23.215963
22.165834
82
false
false
0
0
0
0
76
0.028311
1.413146
false
false
8
fa47366b3c637bc4d498ed592ecc2405cce5986d
8,108,898,255,892
0045dcb21d9fdb0a993c3d34f315c1915138ada7
/FB/PopulatingNxtRightNodeII_117.java
fa94ffc4c93a492e64164a1376327eec353417da
[]
no_license
daydreamerlee/LC
https://github.com/daydreamerlee/LC
a7555590a47412314a19849a47129730cbe0f44e
bdfdd9c896feee288fd191cf77c16728f8c245e4
refs/heads/master
2018-12-22T16:46:31.003000
2018-10-01T16:07:28
2018-10-01T16:07:28
116,524,423
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package FB; /** * Created by Administrator on 1/28/2018. */ public class PopulatingNxtRightNodeII_117 { /*0408 update*/ public void connect(TreeLinkNode root) { if (root == null) return; TreeLinkNode prev = root; // index on the parent level TreeLinkNode dummy = new TreeLinkNode(); // dummy head of current level, dummy.next will serve as next prev TreeLinkNode curr = dummy; // cursor on the current level while (prev != null || dummy.next != null) { while (prev != null && prev.left == null && prev.right == null) prev = prev.next; if (prev == null) { prev = dummy.next; dummy = new TreeLinkNode(); curr = dummy; continue; } if (prev.left != null) { curr.next = prev.left; curr = curr.next; } if (prev.right != null) { curr.next = prev.right; curr = curr.next; } prev = prev.next; // shall be null if reaching the current tail, but if dummy.next if not null, should go next level } } /*01/28*/ private void connect_old(TreeLinkNode root) { TreeLinkNode curr = root; TreeLinkNode nextHead; while (curr != null) { /*下一层的头不一定是 curr.left 得找到下一层的头*/ nextHead = curr; while (nextHead != null) { if (nextHead.left != null || nextHead.right != null) { break; } nextHead = nextHead.next; } while (curr != null) { /*下一个被接上的节点有可能不是 next的子树,而是很远以后的某个东西 * nextTobE就是找到这个东西*/ TreeLinkNode nextToBe = curr.next; while (nextToBe != null) { if (nextToBe.left != null || nextToBe.right != null) { break; } nextToBe = nextToBe.next; } if (curr.left != null && curr.right != null) { curr.left.next = curr.right; if (nextToBe != null) { curr.right.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } else if (curr.left != null) { if (nextToBe != null) { curr.left.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } else if (curr.right != null) { if (nextToBe != null) { curr.right.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } curr = curr.next; } if (nextHead == null) { return; } else { curr = nextHead.left != null ? nextHead.left : nextHead.right; } } } public static void main(String[] args) { TreeLinkNode root = new TreeLinkNode(); TreeLinkNode n2 = new TreeLinkNode(); root.left = n2; PopulatingNxtRightNodeII_117 inst = new PopulatingNxtRightNodeII_117(); inst.connect(root); } }
UTF-8
Java
3,387
java
PopulatingNxtRightNodeII_117.java
Java
[ { "context": "package FB;\n\n\n/**\n * Created by Administrator on 1/28/2018.\n */\npublic class PopulatingNxtRight", "end": 45, "score": 0.985760509967804, "start": 32, "tag": "NAME", "value": "Administrator" } ]
null
[]
package FB; /** * Created by Administrator on 1/28/2018. */ public class PopulatingNxtRightNodeII_117 { /*0408 update*/ public void connect(TreeLinkNode root) { if (root == null) return; TreeLinkNode prev = root; // index on the parent level TreeLinkNode dummy = new TreeLinkNode(); // dummy head of current level, dummy.next will serve as next prev TreeLinkNode curr = dummy; // cursor on the current level while (prev != null || dummy.next != null) { while (prev != null && prev.left == null && prev.right == null) prev = prev.next; if (prev == null) { prev = dummy.next; dummy = new TreeLinkNode(); curr = dummy; continue; } if (prev.left != null) { curr.next = prev.left; curr = curr.next; } if (prev.right != null) { curr.next = prev.right; curr = curr.next; } prev = prev.next; // shall be null if reaching the current tail, but if dummy.next if not null, should go next level } } /*01/28*/ private void connect_old(TreeLinkNode root) { TreeLinkNode curr = root; TreeLinkNode nextHead; while (curr != null) { /*下一层的头不一定是 curr.left 得找到下一层的头*/ nextHead = curr; while (nextHead != null) { if (nextHead.left != null || nextHead.right != null) { break; } nextHead = nextHead.next; } while (curr != null) { /*下一个被接上的节点有可能不是 next的子树,而是很远以后的某个东西 * nextTobE就是找到这个东西*/ TreeLinkNode nextToBe = curr.next; while (nextToBe != null) { if (nextToBe.left != null || nextToBe.right != null) { break; } nextToBe = nextToBe.next; } if (curr.left != null && curr.right != null) { curr.left.next = curr.right; if (nextToBe != null) { curr.right.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } else if (curr.left != null) { if (nextToBe != null) { curr.left.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } else if (curr.right != null) { if (nextToBe != null) { curr.right.next = (nextToBe.left != null) ? nextToBe.left : nextToBe.right; } } curr = curr.next; } if (nextHead == null) { return; } else { curr = nextHead.left != null ? nextHead.left : nextHead.right; } } } public static void main(String[] args) { TreeLinkNode root = new TreeLinkNode(); TreeLinkNode n2 = new TreeLinkNode(); root.left = n2; PopulatingNxtRightNodeII_117 inst = new PopulatingNxtRightNodeII_117(); inst.connect(root); } }
3,387
0.467521
0.459591
93
34.258064
26.87562
128
false
false
0
0
0
0
0
0
0.473118
false
false
8
006dccaabffc17744469af39d4a71a6bd030b2f2
8,100,308,386,796
a505f0d0d9158bbca113db59ed5955801ea0726d
/domain/src/main/java/statikk/domain/entity/enums/Lane.java
460ef80829d30c8b3aace37ac58f31d880b6267d
[]
no_license
AJJohnsonUtah/statikk
https://github.com/AJJohnsonUtah/statikk
00af7e0b99f65c6c4a5448b8b53d94ecb55ff907
883ec12b274a06430c65425c00d0135573fe08cf
refs/heads/feature/STAT-33
2020-03-15T17:24:09.005000
2018-05-05T15:35:47
2018-05-05T15:35:47
132,259,254
0
0
null
false
2018-05-05T15:37:11
2018-05-05T15:16:17
2018-05-05T15:35:48
2018-05-05T15:37:11
0
0
0
0
Java
false
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 statikk.domain.entity.enums; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.HashMap; /** * * @author AJ */ public enum Lane { MIDDLE(1), BOTTOM(2), TOP(3), JUNGLE(4), SUPPORT(5), ROAM(6); private Integer laneId; Lane(Integer id) { this.laneId = id; } public Integer getLaneId() { return laneId; } private final static HashMap<Integer, Lane> laneMap; static { laneMap = new HashMap<>(); for (Lane lane : values()) { laneMap.put(lane.laneId, lane); } } public static Lane getLane(Integer id) { return laneMap.get(id); } @JsonCreator public static Lane getLane(String id) { char firstChar = id.charAt(0); if (firstChar >= '0' && firstChar <= '9') { return getLane(Integer.parseInt(id)); } return Lane.valueOf(id); } }
UTF-8
Java
1,103
java
Lane.java
Java
[ { "context": "ator;\nimport java.util.HashMap;\n\n/**\n *\n * @author AJ\n */\npublic enum Lane {\n MIDDLE(1), BOTTOM(2), ", "end": 323, "score": 0.9689269065856934, "start": 321, "tag": "NAME", "value": "AJ" } ]
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 statikk.domain.entity.enums; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.HashMap; /** * * @author AJ */ public enum Lane { MIDDLE(1), BOTTOM(2), TOP(3), JUNGLE(4), SUPPORT(5), ROAM(6); private Integer laneId; Lane(Integer id) { this.laneId = id; } public Integer getLaneId() { return laneId; } private final static HashMap<Integer, Lane> laneMap; static { laneMap = new HashMap<>(); for (Lane lane : values()) { laneMap.put(lane.laneId, lane); } } public static Lane getLane(Integer id) { return laneMap.get(id); } @JsonCreator public static Lane getLane(String id) { char firstChar = id.charAt(0); if (firstChar >= '0' && firstChar <= '9') { return getLane(Integer.parseInt(id)); } return Lane.valueOf(id); } }
1,103
0.603808
0.595648
49
21.510204
20.90027
79
false
false
0
0
0
0
0
0
0.489796
false
false
8
16118851b93c5f6a3eb52e44706eb5599c942db4
19,370,302,527,837
353cef09c0f72d07f28eae90299254c12362f012
/Arduino Widgets/src/sensors/utilities/DataUtility.java
8d5de2e5ae85b238e4a6c45f023fa7e3bb3eb019
[]
no_license
wwkayak/arduino-stuff
https://github.com/wwkayak/arduino-stuff
0418fc10e27cca9ed9f433d67ec320b5a530cb1f
4481ddc9543e801b0cd850c7b408fe62b0c24cb4
refs/heads/master
2016-09-06T06:01:53.757000
2013-10-30T02:35:58
2013-10-30T02:35:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/**Similar to Arduino’s map function, this value remapping allows a simple adaption of nonlinear input or output devices. If you have a device like a sensor with a behavior that follows the red line for example draw some joined lines through the red curve and make note of the five node points which are occurring here. {{ 0,10 } , { 10,50 } , { 20,150 } , { 40,200 } ,{ 50,200 }}; Put these values in the “nodepoints” array where the reMap() function calculates the linear equations (y=mx+b) and according to that the resulting output value. If you need more nodes simply enlarge the “nodepoints” Array. The node values can be positive or negative . *Martin Nawrath / KHM 2010 http://interface.khm.de/index.php/lab/experiments/nonlinear-mapping/ */ package sensors.utilities; /** I don't like this version, use a lookup table / formula * * * */ public class DataUtility { public int nonlinearMap(float pts[][], int input) { int output=0; return output; } }
WINDOWS-1250
Java
1,042
java
DataUtility.java
Java
[ { "context": "The node values can be positive or negative .\r\n\r\n*Martin Nawrath / KHM 2010 http://interface.khm.de/index.php/lab/", "end": 698, "score": 0.9998908042907715, "start": 684, "tag": "NAME", "value": "Martin Nawrath" } ]
null
[]
/**Similar to Arduino’s map function, this value remapping allows a simple adaption of nonlinear input or output devices. If you have a device like a sensor with a behavior that follows the red line for example draw some joined lines through the red curve and make note of the five node points which are occurring here. {{ 0,10 } , { 10,50 } , { 20,150 } , { 40,200 } ,{ 50,200 }}; Put these values in the “nodepoints” array where the reMap() function calculates the linear equations (y=mx+b) and according to that the resulting output value. If you need more nodes simply enlarge the “nodepoints” Array. The node values can be positive or negative . *<NAME> / KHM 2010 http://interface.khm.de/index.php/lab/experiments/nonlinear-mapping/ */ package sensors.utilities; /** I don't like this version, use a lookup table / formula * * * */ public class DataUtility { public int nonlinearMap(float pts[][], int input) { int output=0; return output; } }
1,034
0.69186
0.665698
26
37.615383
54.916775
198
false
false
0
0
0
0
0
0
0.961538
false
false
8
7675f55ee3bc74c0c4bd9b0654367b56f683f534
13,649,406,130,026
3767c5ac074c7c9cdda67e86b6542ef251cdef74
/ToolShopClient/src/controller/ClientController.java
627559e3df346b0c7c9306d0c0422326aa1431d6
[]
no_license
KChow095/ToolShopManager
https://github.com/KChow095/ToolShopManager
b34e12b45ca98cc8e48312fad681960c4a402841
19995c30b52b861a1bbf393e324135927a409110
refs/heads/main
2023-02-12T04:23:00.320000
2021-01-13T05:04:43
2021-01-13T05:04:43
329,195,578
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.rmi.UnknownHostException; /** * This class connects from the client to the server and sends/receives information from the server * @author Karlen Chow * @version 1.0 * @since November 29, 2020 * */ public class ClientController { private Socket socket; private BufferedReader socketIn; private PrintWriter socketOut; public ClientController(String serverName, int portNumber) { try { socket = new Socket(serverName, portNumber); System.out.println("Connection established"); socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream())); socketOut = new PrintWriter(socket.getOutputStream(),true); ModelController m = new ModelController(socketIn, socketOut); }catch(UnknownHostException e) {e.printStackTrace();} catch(IOException e) {e.printStackTrace();} } public void communicate() { while(true) {} } public static void main(String[] args) { try { ClientController c = new ClientController("localhost",9898); c.communicate(); }catch(Exception e) { System.err.println(e); } } }
UTF-8
Java
1,234
java
ClientController.java
Java
[ { "context": "ds/receives information from the server\n * @author Karlen Chow\n * @version 1.0\n * @since November 29, 2020\n *\n *", "end": 330, "score": 0.9997932314872742, "start": 319, "tag": "NAME", "value": "Karlen Chow" } ]
null
[]
package controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.rmi.UnknownHostException; /** * This class connects from the client to the server and sends/receives information from the server * @author <NAME> * @version 1.0 * @since November 29, 2020 * */ public class ClientController { private Socket socket; private BufferedReader socketIn; private PrintWriter socketOut; public ClientController(String serverName, int portNumber) { try { socket = new Socket(serverName, portNumber); System.out.println("Connection established"); socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream())); socketOut = new PrintWriter(socket.getOutputStream(),true); ModelController m = new ModelController(socketIn, socketOut); }catch(UnknownHostException e) {e.printStackTrace();} catch(IOException e) {e.printStackTrace();} } public void communicate() { while(true) {} } public static void main(String[] args) { try { ClientController c = new ClientController("localhost",9898); c.communicate(); }catch(Exception e) { System.err.println(e); } } }
1,229
0.743922
0.734198
44
27.045454
23.566111
99
false
false
0
0
0
0
0
0
1.727273
false
false
8
cae15834b32bfccc71d590f0712d8fce4b3b30eb
8,572,754,783,522
59bf3c023dde49332b85601f2634fb88820f2d39
/src/re/agiledesign/mp2/exception/VariableNotClosable.java
df5dc00979bf295f83ce9a98232dba34303dd653
[ "MIT" ]
permissive
gcnew/MP2
https://github.com/gcnew/MP2
d02881fe71fb3a9fabec06eaa268071c847cd081
21633be0ad9260f3457ac92cd2a97ebe05110408
refs/heads/master
2021-01-19T09:41:51.428000
2015-09-07T20:32:54
2015-09-07T20:32:54
20,842,686
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package re.agiledesign.mp2.exception; import re.agiledesign.mp2.parser.VarInfo; import re.agiledesign.mp2.util.StringUtil; public class VariableNotClosable extends ParsingException { public VariableNotClosable(final VarInfo aVariable) { super(StringUtil.format("Variable '{}' declared as {} cannot be captured", aVariable.getVarName(), aVariable.getVisibility())); } }
UTF-8
Java
395
java
VariableNotClosable.java
Java
[]
null
[]
package re.agiledesign.mp2.exception; import re.agiledesign.mp2.parser.VarInfo; import re.agiledesign.mp2.util.StringUtil; public class VariableNotClosable extends ParsingException { public VariableNotClosable(final VarInfo aVariable) { super(StringUtil.format("Variable '{}' declared as {} cannot be captured", aVariable.getVarName(), aVariable.getVisibility())); } }
395
0.75443
0.746835
12
30.916666
24.622004
76
false
false
0
0
0
0
0
0
1.5
false
false
8
aefe44d15b1fefe91298099d73dc887a411a0f35
36,945,308,703,755
0ef8ce3db76289db5f9478f8771ee3ee6d024387
/src/designPattern/bigtalkdesignpattern/template/AbstractClass.java
aa5d5160aaa38615a0c71a6a7d04467225b85959
[]
no_license
WarriorYu/Algorithm-Best-Practice
https://github.com/WarriorYu/Algorithm-Best-Practice
aac5fb454e879aa2fdd87351b5b6f4fcb3c5c862
185fa64ad8eadc8e2c5ad5ef06db4d3d90960e85
refs/heads/master
2021-08-31T11:49:29.787000
2021-08-17T02:27:17
2021-08-17T02:27:17
183,173,452
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package designPattern.bigtalkdesignpattern.template; /** * Author : soldieryu.dev@gmail.com * Create : 2021/1/5 * Describe : AbstractClass是抽象类,即抽象模板,定义并实现了一个模板方法。这个模板方法一般是一个具体方法,他给出了一个顶级的逻辑的骨架, * 而逻辑的组成步骤在相应的抽象操作中,推迟到子类实现。 */ public abstract class AbstractClass { public abstract void primitiveOperation1(); public abstract void primitiveOperation2(); public void templateMethod() { primitiveOperation1(); primitiveOperation2(); System.out.println("模板方法结束\n"); } }
UTF-8
Java
691
java
AbstractClass.java
Java
[ { "context": ".bigtalkdesignpattern.template;\n\n/**\n * Author : soldieryu.dev@gmail.com\n * Create : 2021/1/5\n * Describe : AbstractClas", "end": 95, "score": 0.9999091029167175, "start": 72, "tag": "EMAIL", "value": "soldieryu.dev@gmail.com" } ]
null
[]
package designPattern.bigtalkdesignpattern.template; /** * Author : <EMAIL> * Create : 2021/1/5 * Describe : AbstractClass是抽象类,即抽象模板,定义并实现了一个模板方法。这个模板方法一般是一个具体方法,他给出了一个顶级的逻辑的骨架, * 而逻辑的组成步骤在相应的抽象操作中,推迟到子类实现。 */ public abstract class AbstractClass { public abstract void primitiveOperation1(); public abstract void primitiveOperation2(); public void templateMethod() { primitiveOperation1(); primitiveOperation2(); System.out.println("模板方法结束\n"); } }
675
0.719536
0.700193
19
26.210526
22.215639
82
false
false
0
0
0
0
0
0
0.315789
false
false
8
d782500afd16329feec2aa037ec78b6ac7dadfdc
36,773,510,008,799
31fd0863947d2268292e915b04e79fe32a8cdd8f
/CrickCircle/src/cricket/entities/Tournament.java
bdc0bcb7ebc73251259e1abcd760c677f688e2ea
[]
no_license
cd-dpk/CrickCircleProject
https://github.com/cd-dpk/CrickCircleProject
76bea4486940de72af8ed4fb84bd5a13df823def
637cd229ae0ca09e0d9e553962d9512beaef7720
refs/heads/master
2022-05-10T13:11:35.582000
2022-04-06T06:44:59
2022-04-06T06:44:59
29,964,146
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cricket.entities; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import cricket.constant.Stage; public class Tournament implements Serializable{ private double extraBonus=0; private double timeBonus=0; private double runRateBonus=0; private double prizeMonus=0; private double totatPoint=0; private Settings settings; private Nation userNation; private List<Edge>groupAEdges=new ArrayList<Edge>(); private List<Edge>groupBEdges=new ArrayList<Edge>(); private List<Team> groupA=new ArrayList<Team>(); private List<Team> groupB=new ArrayList<Team>(); private Stage stage; private int indexOfEdge=0; private Nation semiFinal[][]; private Nation finale[]; private Nation championNation; private int playOffIndex=0; public void setTournament(Nation userNation, List<Nation>tournamentNations){ setStage(Stage.GROUP); Edge edge; this.userNation=userNation; Nation nation=new Nation(); nation.setIdOfNation("null"); nation.setCodeNameOfNation("TBD"); nation.setNameOfNation("TBD"); nation.setFlagOfNation("null"); nation.setImageOfNation("null"); nation.setRankOfNation("null"); Team team; for(int i=0;i<(tournamentNations.size()/2-1);i++){ for(int j=i+1;j<tournamentNations.size()/2;j++){ edge=new Edge(tournamentNations.get(i),tournamentNations.get(j),false,nation); groupAEdges.add(edge); } team=new Team(); team.setIdOfNation(tournamentNations.get(i).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(i).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(i).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(i).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(i).getImageOfNation()); team.setRankOfNation(tournamentNations.get(i).getRankOfNation()); groupA.add(team); } Collections.shuffle(groupAEdges); team=new Team(); team.setIdOfNation(tournamentNations.get(tournamentNations.size()/2-1).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(tournamentNations.size()/2-1).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(tournamentNations.size()/2-1).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(tournamentNations.size()/2-1).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(tournamentNations.size()/2-1).getImageOfNation()); team.setRankOfNation(tournamentNations.get(tournamentNations.size()/2-1).getRankOfNation()); groupA.add(team); for(int i=tournamentNations.size()/2;i<(tournamentNations.size()-1);i++){ for(int j=i+1;j<tournamentNations.size();j++){ edge=new Edge(tournamentNations.get(i),tournamentNations.get(j),false,nation); groupBEdges.add(edge); } team=new Team(); team.setIdOfNation(tournamentNations.get(i).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(i).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(i).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(i).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(i).getImageOfNation()); team.setRankOfNation(tournamentNations.get(i).getRankOfNation()); groupB.add(team); } team=new Team(); team.setIdOfNation(tournamentNations.get(tournamentNations.size()-1).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(tournamentNations.size()-1).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(tournamentNations.size()-1).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(tournamentNations.size()-1).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(tournamentNations.size()-1).getImageOfNation()); team.setRankOfNation(tournamentNations.get(tournamentNations.size()-1).getRankOfNation()); groupB.add(team); Collections.shuffle(groupBEdges); semiFinal=new Nation[2][2]; for (int i = 0; i < semiFinal.length; i++) { for (int j = 0; j < semiFinal[i].length; j++) { semiFinal[i][j]=nation; } } finale=new Nation[2]; for (int i = 0; i < finale.length; i++) { finale[i]=nation; } championNation=nation; } public double getExtraBonus() { return extraBonus; } public void setExtraBonus(double extraBonus) { this.extraBonus = extraBonus; } public double getTimeBonus() { return timeBonus; } public void setTimeBonus(double timeBonus) { this.timeBonus = timeBonus; } public double getRunRateBonus() { return runRateBonus; } public void setRunRateBonus(double runRateBonus) { this.runRateBonus = runRateBonus; } public double getPrizeMonus() { return prizeMonus; } public void setPrizeMonus(double prizeMonus) { this.prizeMonus = prizeMonus; } public double getTotatPoint() { return totatPoint; } public void setTotatPoint(double totatPoint) { this.totatPoint = totatPoint; } public List<Edge> getGroupAEdges() { return groupAEdges; } public void setGroupAEdges(List<Edge> groupAEdges) { this.groupAEdges = groupAEdges; } public List<Edge> getGroupBEdges() { return groupBEdges; } public void setGroupBEdges(List<Edge> groupBEdges) { this.groupBEdges = groupBEdges; } public List<Team> getGroupA() { return groupA; } public void setGroupA(List<Team> groupA) { this.groupA = groupA; } public List<Team> getGroupB() { return groupB; } public void setGroupB(List<Team> groupB) { this.groupB = groupB; } public Stage getStage() { return stage; } public void setStage(Stage stage) { this.stage = stage; } public Nation getUserNation() { return userNation; } public void setUserNation(Nation userNation) { this.userNation = userNation; } public Settings getSettings() { return settings; } public void setSettings(Settings settings) { this.settings = settings; } public int getIndexOfEdge() { return indexOfEdge; } public void setIndexOfEdge(int indexOfEdge) { this.indexOfEdge = indexOfEdge; } public Nation[][] getSemiFinal() { return semiFinal; } public void setSemiFinal(Nation semiFinal[][]) { this.semiFinal = semiFinal; } public Nation[] getFinal() { return finale; } public void setFinal(Nation[] finale) { this.finale = finale; } public Nation getChampionNation() { return championNation; } public void setChampionNation(Nation championNation) { this.championNation = championNation; } public int getPlayOffIndex() { return playOffIndex; } public void setPlayOffIndex(int playOffIndex) { this.playOffIndex = playOffIndex; } }
UTF-8
Java
6,743
java
Tournament.java
Java
[]
null
[]
package cricket.entities; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import cricket.constant.Stage; public class Tournament implements Serializable{ private double extraBonus=0; private double timeBonus=0; private double runRateBonus=0; private double prizeMonus=0; private double totatPoint=0; private Settings settings; private Nation userNation; private List<Edge>groupAEdges=new ArrayList<Edge>(); private List<Edge>groupBEdges=new ArrayList<Edge>(); private List<Team> groupA=new ArrayList<Team>(); private List<Team> groupB=new ArrayList<Team>(); private Stage stage; private int indexOfEdge=0; private Nation semiFinal[][]; private Nation finale[]; private Nation championNation; private int playOffIndex=0; public void setTournament(Nation userNation, List<Nation>tournamentNations){ setStage(Stage.GROUP); Edge edge; this.userNation=userNation; Nation nation=new Nation(); nation.setIdOfNation("null"); nation.setCodeNameOfNation("TBD"); nation.setNameOfNation("TBD"); nation.setFlagOfNation("null"); nation.setImageOfNation("null"); nation.setRankOfNation("null"); Team team; for(int i=0;i<(tournamentNations.size()/2-1);i++){ for(int j=i+1;j<tournamentNations.size()/2;j++){ edge=new Edge(tournamentNations.get(i),tournamentNations.get(j),false,nation); groupAEdges.add(edge); } team=new Team(); team.setIdOfNation(tournamentNations.get(i).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(i).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(i).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(i).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(i).getImageOfNation()); team.setRankOfNation(tournamentNations.get(i).getRankOfNation()); groupA.add(team); } Collections.shuffle(groupAEdges); team=new Team(); team.setIdOfNation(tournamentNations.get(tournamentNations.size()/2-1).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(tournamentNations.size()/2-1).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(tournamentNations.size()/2-1).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(tournamentNations.size()/2-1).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(tournamentNations.size()/2-1).getImageOfNation()); team.setRankOfNation(tournamentNations.get(tournamentNations.size()/2-1).getRankOfNation()); groupA.add(team); for(int i=tournamentNations.size()/2;i<(tournamentNations.size()-1);i++){ for(int j=i+1;j<tournamentNations.size();j++){ edge=new Edge(tournamentNations.get(i),tournamentNations.get(j),false,nation); groupBEdges.add(edge); } team=new Team(); team.setIdOfNation(tournamentNations.get(i).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(i).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(i).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(i).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(i).getImageOfNation()); team.setRankOfNation(tournamentNations.get(i).getRankOfNation()); groupB.add(team); } team=new Team(); team.setIdOfNation(tournamentNations.get(tournamentNations.size()-1).getIdOfNation()); team.setCodeNameOfNation(tournamentNations.get(tournamentNations.size()-1).getCodeNameOfNation()); team.setNameOfNation(tournamentNations.get(tournamentNations.size()-1).getNameOfNation()); team.setFlagOfNation(tournamentNations.get(tournamentNations.size()-1).getFlagOfNation()); team.setImageOfNation(tournamentNations.get(tournamentNations.size()-1).getImageOfNation()); team.setRankOfNation(tournamentNations.get(tournamentNations.size()-1).getRankOfNation()); groupB.add(team); Collections.shuffle(groupBEdges); semiFinal=new Nation[2][2]; for (int i = 0; i < semiFinal.length; i++) { for (int j = 0; j < semiFinal[i].length; j++) { semiFinal[i][j]=nation; } } finale=new Nation[2]; for (int i = 0; i < finale.length; i++) { finale[i]=nation; } championNation=nation; } public double getExtraBonus() { return extraBonus; } public void setExtraBonus(double extraBonus) { this.extraBonus = extraBonus; } public double getTimeBonus() { return timeBonus; } public void setTimeBonus(double timeBonus) { this.timeBonus = timeBonus; } public double getRunRateBonus() { return runRateBonus; } public void setRunRateBonus(double runRateBonus) { this.runRateBonus = runRateBonus; } public double getPrizeMonus() { return prizeMonus; } public void setPrizeMonus(double prizeMonus) { this.prizeMonus = prizeMonus; } public double getTotatPoint() { return totatPoint; } public void setTotatPoint(double totatPoint) { this.totatPoint = totatPoint; } public List<Edge> getGroupAEdges() { return groupAEdges; } public void setGroupAEdges(List<Edge> groupAEdges) { this.groupAEdges = groupAEdges; } public List<Edge> getGroupBEdges() { return groupBEdges; } public void setGroupBEdges(List<Edge> groupBEdges) { this.groupBEdges = groupBEdges; } public List<Team> getGroupA() { return groupA; } public void setGroupA(List<Team> groupA) { this.groupA = groupA; } public List<Team> getGroupB() { return groupB; } public void setGroupB(List<Team> groupB) { this.groupB = groupB; } public Stage getStage() { return stage; } public void setStage(Stage stage) { this.stage = stage; } public Nation getUserNation() { return userNation; } public void setUserNation(Nation userNation) { this.userNation = userNation; } public Settings getSettings() { return settings; } public void setSettings(Settings settings) { this.settings = settings; } public int getIndexOfEdge() { return indexOfEdge; } public void setIndexOfEdge(int indexOfEdge) { this.indexOfEdge = indexOfEdge; } public Nation[][] getSemiFinal() { return semiFinal; } public void setSemiFinal(Nation semiFinal[][]) { this.semiFinal = semiFinal; } public Nation[] getFinal() { return finale; } public void setFinal(Nation[] finale) { this.finale = finale; } public Nation getChampionNation() { return championNation; } public void setChampionNation(Nation championNation) { this.championNation = championNation; } public int getPlayOffIndex() { return playOffIndex; } public void setPlayOffIndex(int playOffIndex) { this.playOffIndex = playOffIndex; } }
6,743
0.722824
0.71704
206
30.733009
25.3479
102
false
false
0
0
0
0
0
0
2.257282
false
false
8
1f9830fd66fa142a4aca29916d8fdfc473388e18
33,956,011,488,354
90b7ee8673c75e6eb00b1e37c2e83689a0a2cb40
/src/Lesson52/Addition.java
80024d8dbf4e2f0b029d93e01ab5aef2c1aa20ca
[]
no_license
KlyuchukA/HelloApp
https://github.com/KlyuchukA/HelloApp
36962aabb8f63c7f0995c5b5f4c3c7d52e19cd67
ae1491beacd62f57590945124c2b844043875578
refs/heads/master
2022-12-29T04:07:39.726000
2020-10-08T13:54:49
2020-10-08T13:54:49
291,918,813
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Lesson52; public class Addition extends Calculator { public double Result(double x, double y) { return x + y; } public Logger calculate() { return new FileLogger(); } }
UTF-8
Java
213
java
Addition.java
Java
[]
null
[]
package Lesson52; public class Addition extends Calculator { public double Result(double x, double y) { return x + y; } public Logger calculate() { return new FileLogger(); } }
213
0.615023
0.605634
11
18.181818
16.540958
46
false
false
0
0
0
0
0
0
0.363636
false
false
8
7d33e68b7da4a054aaeceb586b0553dafdf40ed3
34,694,745,860,457
8d90d9246881b3dc27b941185518148b837d9fa2
/Practice-2020/July/Java/MergeOverlappingIntervals.java
c98bfd8d347eb39a607040badf51f8d5a8d86a59
[]
no_license
su225/algorithmic-programming
https://github.com/su225/algorithmic-programming
5c53e18240e700c839b61b3f3cb81548711bc418
67afb648b3495a97a77dbab6cbae97ade23dbeee
refs/heads/master
2021-09-28T23:20:41.658000
2021-09-28T09:27:23
2021-09-28T09:27:23
141,442,341
0
0
null
false
2021-09-30T18:51:38
2018-07-18T13:58:41
2021-09-30T18:41:34
2021-09-30T18:51:37
2,303
0
0
0
Java
false
false
class Pair{ public int first; public int second; public Pair(int x, int y){ this.first = x; this.second = y; } } class MergeIntervals{ static ArrayList<Pair> mergeIntervals(ArrayList<Pair> v) { if (v.size() <= 1) { return v; } int start = v.get(0).first; int end = v.get(0).second; ArrayList<Pair> mergedIntervals = new ArrayList<>(); for (int i = 1; i < v.size(); i++) { if (isDisjoint(v.get(i), start, end)) { mergedIntervals.add(new Pair(start, end)); start = v.get(i).first; end = v.get(i).second; } start = Math.min(v.get(i).first, start); end = Math.max(v.get(i).second, end); } mergedIntervals.add(new Pair(start, end)); return mergedIntervals; } private static boolean isDisjoint(Pair interval, int start, int end) { return start > interval.second || end < interval.first; } }
UTF-8
Java
864
java
MergeOverlappingIntervals.java
Java
[]
null
[]
class Pair{ public int first; public int second; public Pair(int x, int y){ this.first = x; this.second = y; } } class MergeIntervals{ static ArrayList<Pair> mergeIntervals(ArrayList<Pair> v) { if (v.size() <= 1) { return v; } int start = v.get(0).first; int end = v.get(0).second; ArrayList<Pair> mergedIntervals = new ArrayList<>(); for (int i = 1; i < v.size(); i++) { if (isDisjoint(v.get(i), start, end)) { mergedIntervals.add(new Pair(start, end)); start = v.get(i).first; end = v.get(i).second; } start = Math.min(v.get(i).first, start); end = Math.max(v.get(i).second, end); } mergedIntervals.add(new Pair(start, end)); return mergedIntervals; } private static boolean isDisjoint(Pair interval, int start, int end) { return start > interval.second || end < interval.first; } }
864
0.621528
0.616898
35
23.714285
19.561729
70
false
false
0
0
0
0
0
0
0.828571
false
false
8
9fa13e3823467f9a927ac464cc597e6a1f990ba4
39,247,411,151,088
04a047fd4b75c79c49c08b33c3d904943028da74
/src/main/java/p15/composite/HrDepartment.java
cd089219c1747f191587d4d697ae2ac135f13ed4
[]
no_license
XLShi0913/design-model
https://github.com/XLShi0913/design-model
e5a95717e36afe5ff00ecdbe6fc7028c6279994a
37cf5d0a2f8136778362d5c354fd6323a15e2e94
refs/heads/main
2023-06-20T06:23:03.053000
2021-07-18T17:34:02
2021-07-18T17:34:02
384,989,340
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package p15.composite; public class HrDepartment extends Company { public HrDepartment(String name) { super(name); } @Override public void add(Company c) { } @Override public void remove(Company c) { } @Override public void display(int depth) { System.out.println(StringUtil.buildString('-', depth) + name); } @Override public void lineOfDuty() { System.out.println(String.format("%s 员工招聘培训管理", name)); } }
UTF-8
Java
501
java
HrDepartment.java
Java
[]
null
[]
package p15.composite; public class HrDepartment extends Company { public HrDepartment(String name) { super(name); } @Override public void add(Company c) { } @Override public void remove(Company c) { } @Override public void display(int depth) { System.out.println(StringUtil.buildString('-', depth) + name); } @Override public void lineOfDuty() { System.out.println(String.format("%s 员工招聘培训管理", name)); } }
501
0.62268
0.618557
24
19.208334
20.066513
70
false
false
0
0
0
0
0
0
0.25
false
false
8
bbac661fafa0d4b47a808e9504ac4d561ac88880
32,779,190,406,503
79367abc7d47bc96284fb7e8ffa08e57683dd87d
/src/main/java/com/qph/AppConfiguration.java
59a3eb2132f19a21debf5abb42efb7fe5de9a023
[]
no_license
phquoc25/mailSender
https://github.com/phquoc25/mailSender
c055d6a3f4f30b492334b6a57c893e00faadb6c2
f0022c830c8fa87b2081761326c074126bff2bad
refs/heads/master
2021-06-06T01:12:57.444000
2019-04-06T09:15:38
2019-04-07T08:08:03
95,417,905
0
0
null
false
2019-04-07T08:08:05
2017-06-26T07:00:26
2019-03-26T23:46:06
2019-04-07T08:08:04
6,367
0
0
0
Java
false
false
package com.qph; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Arrays; import java.util.Properties; import javax.mail.MessagingException; /** * Created by quoc on 24/06/2017. */ @Configuration @ImportResource("classpath:properties-config.xml") @ComponentScan(value = {"com.qph"}) public class AppConfiguration { @Autowired private QphMailSenderProperties qphMailSenderProperties; @Bean public JavaMailSenderImpl gmailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost("smtp.gmail.com"); javaMailSender.setPort(587); javaMailSender.setUsername(qphMailSenderProperties.getGmailUserName()); javaMailSender.setPassword(qphMailSenderProperties.getGmailPassword()); Properties javaMailProperties = getJavaMailProperties(); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } @Bean public JavaMailSenderImpl otherMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(qphMailSenderProperties.getHost()); javaMailSender.setPort(Integer.valueOf(qphMailSenderProperties.getPort())); javaMailSender.setUsername(qphMailSenderProperties.getUserName()); javaMailSender.setPassword(qphMailSenderProperties.getPassword()); Properties javaMailProperties = getJavaMailProperties(); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } private Properties getJavaMailProperties() { Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", "true"); javaMailProperties.put("mail.smtp.starttls.enable", "true"); return javaMailProperties; } public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class); QphMailSender qphMailSender = applicationContext.getBean(QphMailSenderImpl.class); try { if (args.length == 0) { qphMailSender.sendMail(); } else { qphMailSender.sendMail(args[0]); } System.out.println("Email sending successfully!"); } catch (MessagingException e) { System.out.println("Error when preparing message"); System.out.println(Arrays.toString(e.getStackTrace())); } } }
UTF-8
Java
2,975
java
AppConfiguration.java
Java
[ { "context": " javax.mail.MessagingException;\n\n/**\n * Created by quoc on 24/06/2017.\n */\n@Configuration\n@ImportResource", "end": 632, "score": 0.9992468953132629, "start": 628, "tag": "USERNAME", "value": "quoc" } ]
null
[]
package com.qph; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Arrays; import java.util.Properties; import javax.mail.MessagingException; /** * Created by quoc on 24/06/2017. */ @Configuration @ImportResource("classpath:properties-config.xml") @ComponentScan(value = {"com.qph"}) public class AppConfiguration { @Autowired private QphMailSenderProperties qphMailSenderProperties; @Bean public JavaMailSenderImpl gmailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost("smtp.gmail.com"); javaMailSender.setPort(587); javaMailSender.setUsername(qphMailSenderProperties.getGmailUserName()); javaMailSender.setPassword(qphMailSenderProperties.getGmailPassword()); Properties javaMailProperties = getJavaMailProperties(); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } @Bean public JavaMailSenderImpl otherMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(qphMailSenderProperties.getHost()); javaMailSender.setPort(Integer.valueOf(qphMailSenderProperties.getPort())); javaMailSender.setUsername(qphMailSenderProperties.getUserName()); javaMailSender.setPassword(qphMailSenderProperties.getPassword()); Properties javaMailProperties = getJavaMailProperties(); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; } private Properties getJavaMailProperties() { Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", "true"); javaMailProperties.put("mail.smtp.starttls.enable", "true"); return javaMailProperties; } public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class); QphMailSender qphMailSender = applicationContext.getBean(QphMailSenderImpl.class); try { if (args.length == 0) { qphMailSender.sendMail(); } else { qphMailSender.sendMail(args[0]); } System.out.println("Email sending successfully!"); } catch (MessagingException e) { System.out.println("Error when preparing message"); System.out.println(Arrays.toString(e.getStackTrace())); } } }
2,975
0.73042
0.72605
80
36.1875
28.694117
111
false
false
0
0
0
0
0
0
0.525
false
false
8
310cb3a1c79da1432da9809457fa67b2a4ac1481
19,421,842,165,603
e9b930b0f8ade86bf4e142d61436bee5996dcd38
/05_Skynet/src/BaseRobot.java
fa6432a2c21679cfd3e57a85573795b71a2125f8
[]
no_license
dani-sc/itb5-systemarchitectures
https://github.com/dani-sc/itb5-systemarchitectures
297b6858df705ee56876c7c64d853be7fa55fd19
70b464c1422400c2aae0e3c34388356c0c02a4a9
refs/heads/master
2021-05-30T22:55:27.418000
2016-01-08T13:05:14
2016-01-08T13:05:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayDeque; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Queue; import com.cyberbotics.webots.controller.DifferentialWheels; import com.cyberbotics.webots.controller.DistanceSensor; import com.cyberbotics.webots.controller.LightSensor; /** * Offers easy access to raw and smoothed out (-> median) sensor values. * General settings can be modified via the constants, e.g. {@link #MAX_SPEED} * * For proportional controllers, we're following Braitenberg's formular * a = k * s + c * a ... actors (vector) * k ... "weight of sensors" (matrix) * s ... sensors (vector) * c ... constants (vector) */ public abstract class BaseRobot extends DifferentialWheels { private static final int STEP_TIME = 8; protected static final int MIN_SPEED = 0; protected static final int MAX_SPEED = 1000; private static final int SENSOR_READING_INTERVALL = 10; // [ms] private static final int NO_VALUES_FOR_SMOOTHING = 10; private Map<Sensor, DistanceSensor> distanceSensors; private Map<Sensor, LightSensor> lightSensors; private Map<Sensor, Queue<Double>> distanceSensorValues; private Map<Sensor, Queue<Double>> lightSensorValues; /** * Defines what the robot should do each step. */ protected abstract void update(); public BaseRobot() { super(); initDistanceSensors(); initLightSensors(); initDistanceSensorValues(); initLightSensorValues(); } private void initDistanceSensors() { distanceSensors = new HashMap<>(); distanceSensors.put(Sensor.FRONT_R, getDistanceSensor("ps0")); distanceSensors.put(Sensor.FRONT_RIGHT, getDistanceSensor("ps1")); distanceSensors.put(Sensor.RIGHT, getDistanceSensor("ps2")); distanceSensors.put(Sensor.BACK_RIGHT, getDistanceSensor("ps3")); distanceSensors.put(Sensor.BACK_LEFT, getDistanceSensor("ps4")); distanceSensors.put(Sensor.LEFT, getDistanceSensor("ps5")); distanceSensors.put(Sensor.FRONT_LEFT, getDistanceSensor("ps6")); distanceSensors.put(Sensor.FRONT_L, getDistanceSensor("ps7")); distanceSensors.entrySet().forEach(proximitySensor -> proximitySensor.getValue().enable(SENSOR_READING_INTERVALL)); } private void initLightSensors() { lightSensors = new HashMap<>(); lightSensors.put(Sensor.FRONT_R, getLightSensor("ls0")); lightSensors.put(Sensor.FRONT_RIGHT, getLightSensor("ls1")); lightSensors.put(Sensor.RIGHT, getLightSensor("ls2")); lightSensors.put(Sensor.BACK_RIGHT, getLightSensor("ls3")); lightSensors.put(Sensor.BACK_LEFT, getLightSensor("ls4")); lightSensors.put(Sensor.LEFT, getLightSensor("ls5")); lightSensors.put(Sensor.FRONT_LEFT, getLightSensor("ls6")); lightSensors.put(Sensor.FRONT_L, getLightSensor("ls7")); lightSensors.entrySet().forEach(lightSensor -> lightSensor.getValue().enable(SENSOR_READING_INTERVALL)); } private void initDistanceSensorValues() { distanceSensorValues = new HashMap<>(); distanceSensorValues.put(Sensor.FRONT_R, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.BACK_RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.BACK_LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_L, new ArrayDeque<Double>()); } private void initLightSensorValues() { lightSensorValues = new HashMap<>(); lightSensorValues.put(Sensor.FRONT_R, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.BACK_RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.BACK_LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_L, new ArrayDeque<Double>()); } /** * Should be called once in main(). */ public void run() { while (step(STEP_TIME) != -1) { updateSensorValues(); update(); // defined in implementing class } } private void updateSensorValues() { if (distanceSensorValues.values().size() > 0) { int nrOfValues = distanceSensorValues.values().iterator().next().size(); if (nrOfValues >= NO_VALUES_FOR_SMOOTHING) { deleteOldestSensorValue(); } insertNewSensorValue(); } } private void deleteOldestSensorValue() { distanceSensorValues.values().forEach(queue -> queue.poll()); lightSensorValues.values().forEach(queue -> queue.poll()); } private void insertNewSensorValue() { distanceSensorValues.entrySet() .forEach(entry -> entry.getValue().add(distanceSensors.get(entry.getKey()).getValue())); lightSensorValues.entrySet() .forEach(entry -> entry.getValue().add(lightSensors.get(entry.getKey()).getValue())); } public double getDistanceSensorDataRaw(Sensor sensor) { return distanceSensors.get(sensor).getValue(); } public double[] getDistanceSensorDataRaw(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getDistanceSensorDataRaw(sensors[i]); } return values; } public double getLightSensorDataRaw(Sensor sensor) { return lightSensors.get(sensor).getValue(); } public double[] getLightSensorDataRaw(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getLightSensorDataRaw(sensors[i]); } return values; } public double getDistanceSensorDataSmoothed(Sensor sensor) { return getMedianValue(distanceSensorValues.get(sensor)); } public double[] getDistanceSensorDataSmoothed(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getDistanceSensorDataSmoothed(sensors[i]); } return values; } public double getLightSensorDataSmoothed(Sensor sensor) { return getMedianValue(lightSensorValues.get(sensor)); } public double[] getLightSensorDataSmoothed(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getLightSensorDataSmoothed(sensors[i]); } return values; } private double getMedianValue(Queue<Double> queue) { Double[] sorted = queue.toArray(new Double[0]); Arrays.sort(sorted); if (sorted.length == 1) { // if only 1 element -> return this element return sorted[0]; } else if (sorted.length % 2 == 1) { // if number of values is odd -> return avg. value of the two central values return (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2d; } else { // if number of values is even -> return central value return sorted[sorted.length / 2]; } } protected void driveLeftMaxSpeed() { setSpeed(MIN_SPEED, MAX_SPEED); } protected void driveRightMaxSpeed() { setSpeed(MAX_SPEED, MIN_SPEED); } protected void driveForwardMaxSpeed() { setSpeed(MAX_SPEED, MAX_SPEED); } protected void driveStop() { setSpeed(MIN_SPEED, MIN_SPEED); } }
UTF-8
Java
7,267
java
BaseRobot.java
Java
[]
null
[]
import java.util.ArrayDeque; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Queue; import com.cyberbotics.webots.controller.DifferentialWheels; import com.cyberbotics.webots.controller.DistanceSensor; import com.cyberbotics.webots.controller.LightSensor; /** * Offers easy access to raw and smoothed out (-> median) sensor values. * General settings can be modified via the constants, e.g. {@link #MAX_SPEED} * * For proportional controllers, we're following Braitenberg's formular * a = k * s + c * a ... actors (vector) * k ... "weight of sensors" (matrix) * s ... sensors (vector) * c ... constants (vector) */ public abstract class BaseRobot extends DifferentialWheels { private static final int STEP_TIME = 8; protected static final int MIN_SPEED = 0; protected static final int MAX_SPEED = 1000; private static final int SENSOR_READING_INTERVALL = 10; // [ms] private static final int NO_VALUES_FOR_SMOOTHING = 10; private Map<Sensor, DistanceSensor> distanceSensors; private Map<Sensor, LightSensor> lightSensors; private Map<Sensor, Queue<Double>> distanceSensorValues; private Map<Sensor, Queue<Double>> lightSensorValues; /** * Defines what the robot should do each step. */ protected abstract void update(); public BaseRobot() { super(); initDistanceSensors(); initLightSensors(); initDistanceSensorValues(); initLightSensorValues(); } private void initDistanceSensors() { distanceSensors = new HashMap<>(); distanceSensors.put(Sensor.FRONT_R, getDistanceSensor("ps0")); distanceSensors.put(Sensor.FRONT_RIGHT, getDistanceSensor("ps1")); distanceSensors.put(Sensor.RIGHT, getDistanceSensor("ps2")); distanceSensors.put(Sensor.BACK_RIGHT, getDistanceSensor("ps3")); distanceSensors.put(Sensor.BACK_LEFT, getDistanceSensor("ps4")); distanceSensors.put(Sensor.LEFT, getDistanceSensor("ps5")); distanceSensors.put(Sensor.FRONT_LEFT, getDistanceSensor("ps6")); distanceSensors.put(Sensor.FRONT_L, getDistanceSensor("ps7")); distanceSensors.entrySet().forEach(proximitySensor -> proximitySensor.getValue().enable(SENSOR_READING_INTERVALL)); } private void initLightSensors() { lightSensors = new HashMap<>(); lightSensors.put(Sensor.FRONT_R, getLightSensor("ls0")); lightSensors.put(Sensor.FRONT_RIGHT, getLightSensor("ls1")); lightSensors.put(Sensor.RIGHT, getLightSensor("ls2")); lightSensors.put(Sensor.BACK_RIGHT, getLightSensor("ls3")); lightSensors.put(Sensor.BACK_LEFT, getLightSensor("ls4")); lightSensors.put(Sensor.LEFT, getLightSensor("ls5")); lightSensors.put(Sensor.FRONT_LEFT, getLightSensor("ls6")); lightSensors.put(Sensor.FRONT_L, getLightSensor("ls7")); lightSensors.entrySet().forEach(lightSensor -> lightSensor.getValue().enable(SENSOR_READING_INTERVALL)); } private void initDistanceSensorValues() { distanceSensorValues = new HashMap<>(); distanceSensorValues.put(Sensor.FRONT_R, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.BACK_RIGHT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.BACK_LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_LEFT, new ArrayDeque<Double>()); distanceSensorValues.put(Sensor.FRONT_L, new ArrayDeque<Double>()); } private void initLightSensorValues() { lightSensorValues = new HashMap<>(); lightSensorValues.put(Sensor.FRONT_R, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.BACK_RIGHT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.BACK_LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_LEFT, new ArrayDeque<Double>()); lightSensorValues.put(Sensor.FRONT_L, new ArrayDeque<Double>()); } /** * Should be called once in main(). */ public void run() { while (step(STEP_TIME) != -1) { updateSensorValues(); update(); // defined in implementing class } } private void updateSensorValues() { if (distanceSensorValues.values().size() > 0) { int nrOfValues = distanceSensorValues.values().iterator().next().size(); if (nrOfValues >= NO_VALUES_FOR_SMOOTHING) { deleteOldestSensorValue(); } insertNewSensorValue(); } } private void deleteOldestSensorValue() { distanceSensorValues.values().forEach(queue -> queue.poll()); lightSensorValues.values().forEach(queue -> queue.poll()); } private void insertNewSensorValue() { distanceSensorValues.entrySet() .forEach(entry -> entry.getValue().add(distanceSensors.get(entry.getKey()).getValue())); lightSensorValues.entrySet() .forEach(entry -> entry.getValue().add(lightSensors.get(entry.getKey()).getValue())); } public double getDistanceSensorDataRaw(Sensor sensor) { return distanceSensors.get(sensor).getValue(); } public double[] getDistanceSensorDataRaw(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getDistanceSensorDataRaw(sensors[i]); } return values; } public double getLightSensorDataRaw(Sensor sensor) { return lightSensors.get(sensor).getValue(); } public double[] getLightSensorDataRaw(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getLightSensorDataRaw(sensors[i]); } return values; } public double getDistanceSensorDataSmoothed(Sensor sensor) { return getMedianValue(distanceSensorValues.get(sensor)); } public double[] getDistanceSensorDataSmoothed(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getDistanceSensorDataSmoothed(sensors[i]); } return values; } public double getLightSensorDataSmoothed(Sensor sensor) { return getMedianValue(lightSensorValues.get(sensor)); } public double[] getLightSensorDataSmoothed(Sensor... sensors) { double[] values = new double[sensors.length]; for (int i = 0; i < values.length; ++i) { values[i] = getLightSensorDataSmoothed(sensors[i]); } return values; } private double getMedianValue(Queue<Double> queue) { Double[] sorted = queue.toArray(new Double[0]); Arrays.sort(sorted); if (sorted.length == 1) { // if only 1 element -> return this element return sorted[0]; } else if (sorted.length % 2 == 1) { // if number of values is odd -> return avg. value of the two central values return (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2d; } else { // if number of values is even -> return central value return sorted[sorted.length / 2]; } } protected void driveLeftMaxSpeed() { setSpeed(MIN_SPEED, MAX_SPEED); } protected void driveRightMaxSpeed() { setSpeed(MAX_SPEED, MIN_SPEED); } protected void driveForwardMaxSpeed() { setSpeed(MAX_SPEED, MAX_SPEED); } protected void driveStop() { setSpeed(MIN_SPEED, MIN_SPEED); } }
7,267
0.727811
0.721893
220
32.031818
27.430471
117
false
false
0
0
0
0
0
0
1.940909
false
false
8
609150f22051aea52867daa1aa62de3ec23e7a34
19,877,108,703,361
95f873af0087b2e85659762cdfa04c0403879db0
/src/test/java/chronal_charge/CellsGridTest.java
36fca0cc035fab7cbdfffed7761db05082102b03
[]
no_license
Gabou/advent-code-2018
https://github.com/Gabou/advent-code-2018
7cdf46a23e86924e8b3752e5f8d246cba5a6f8e4
9e1c7f08c0353b00505e9c266570e62a38b22736
refs/heads/master
2020-04-09T05:00:48.718000
2019-12-03T17:10:15
2019-12-03T17:10:15
160,047,215
1
0
null
false
2018-12-11T16:56:15
2018-12-02T12:55:48
2018-12-11T13:28:13
2018-12-11T16:56:14
38
0
0
0
Java
false
null
package chronal_charge; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class CellsGridTest { @Test void give_cells_group_fuel_of_size_3_3_at_33_45_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroup(new Position(33,45),new Size(3)); Assertions.assertThat(cellsGroup.fuelLevel()).isEqualTo(new FuelLevel(29)); } @Test void give_cells_group_origin_coordinate_with_largest_fuel_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(new Size(3)); Assertions.assertThat(cellsGroup.position()).isEqualTo(new Position(33,45)); } @Test void give_cells_group_with_largest_fuel_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(); Assertions.assertThat(cellsGroup).isEqualTo(new CellsGroup(new Position(90,269), new Size(16), new FuelLevel(113))); } @Test void give_cells_group_with_largest_fuel_with_serial_number_42() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 42); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(); Assertions.assertThat(cellsGroup).isEqualTo(new CellsGroup(new Position(232,251), new Size(12), new FuelLevel(119))); } }
UTF-8
Java
1,497
java
CellsGridTest.java
Java
[]
null
[]
package chronal_charge; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class CellsGridTest { @Test void give_cells_group_fuel_of_size_3_3_at_33_45_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroup(new Position(33,45),new Size(3)); Assertions.assertThat(cellsGroup.fuelLevel()).isEqualTo(new FuelLevel(29)); } @Test void give_cells_group_origin_coordinate_with_largest_fuel_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(new Size(3)); Assertions.assertThat(cellsGroup.position()).isEqualTo(new Position(33,45)); } @Test void give_cells_group_with_largest_fuel_with_serial_number_18() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 18); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(); Assertions.assertThat(cellsGroup).isEqualTo(new CellsGroup(new Position(90,269), new Size(16), new FuelLevel(113))); } @Test void give_cells_group_with_largest_fuel_with_serial_number_42() { CellsGrid cellsGrid = new CellsGrid(new Size(300), 42); CellsGroup cellsGroup = cellsGrid.cellsGroupsWithLargestFuel(); Assertions.assertThat(cellsGroup).isEqualTo(new CellsGroup(new Position(232,251), new Size(12), new FuelLevel(119))); } }
1,497
0.705411
0.660655
36
40.583332
38.429859
125
false
false
0
0
0
0
0
0
0.777778
false
false
8
6a4f618e112397b4d5ee4acf29e2c31002ce2ef7
5,669,356,884,854
f451899297221cfbe8c6a25c4a0cfb8cba66a890
/cas2xb3_A2_Hameed_AH/src/ConstructedClasses/Main.java
fe0d986971254fc22faf76333d9e935c3a1dc7e9
[]
no_license
andyh98/In-Course-Projects
https://github.com/andyh98/In-Course-Projects
4002f171fea87c2242664697fba2305029308620
50843066cff29826f5af9fb3e879d21a3002a9b2
refs/heads/master
2020-03-07T11:46:42.557000
2018-09-14T02:52:56
2018-09-14T02:52:56
127,463,539
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ConstructedClasses; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import HelperClasses.DirectedEdge; /** *Main runs searching and shortest paths algorithms used. The results are *printed in the text file a2_out.txt * * @author Andy Hameed * */ public class Main { public static DepthFirstPath pthDFS; public static BreadthFirstPaths pthBFS; public static int boston = Digraph.search("BOSTON"); public static int Minn = Digraph.search("MINNEAPOLIS"); public static Digraph routes = new Digraph(32); public Main() throws IOException { /** * Reading Connected Cities and adding weighted edges */ String[] temp; File file = new File("connectedCities.txt"); Scanner sc; try { sc = new Scanner(file); while (sc.hasNext()) { temp= sc.nextLine().split(","); //find weight based on the cheapest meal satisfying conditons float weight = CheapestMeal(Digraph.search(temp[0]), Digraph.search(temp[1].substring(1))); routes.addEdge(new DirectedEdge(Digraph.search(temp[0]),Digraph.search(temp[1].substring(1)),weight)); } sc.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Perform BFS and DFS at Boston and print results pthDFS = new DepthFirstPath(routes, boston); pthBFS = new BreadthFirstPaths(routes, boston); //Write into results file WriteResults(); } private float CheapestMeal(int tail, int head) { // TODO Auto-generated method stub City prev = Gen.cities[tail]; City current = Gen.cities[head]; if (prev.getCityMeal().equals("")) {current.setCityMeal(current.bestMeal().name());return current.bestMeal().price();} //if the previous meal matches the best meal in the current city, //pick the next best meal in the city if (prev.getCityMeal().equals(current.bestMeal().name())){current.setCityMeal(current.secondBestMeal().name());return current.secondBestMeal().price();} return current.bestMeal().price(); } public static void WriteResults() throws IOException { FileWriter fw = new FileWriter("a2_out.txt"); BufferedWriter results; results = new BufferedWriter(fw); //BFS results results.write("BFS: "); for (Integer w : pthBFS.pathTo(Minn)) { results.append(" " + Gen.cities[w].getName() + ","); } //DFS results results.newLine(); results.write("DFS: "); for (Integer w : pthDFS.pathTo(Minn)) { results.append(" " + Gen.cities[w].getName() + ","); } //Printing out results for shortest path Dijkstras shortestPath = new Dijkstras(routes, boston); results.newLine(); results.newLine(); results.append(" City | Meal Choice | Meal Cost"); results.newLine(); results.append(" BOSTON "); for (DirectedEdge w : shortestPath.pathTo(Minn)) { results.newLine(); results.append(" " + Gen.cities[w.to()].getName() + "|" + Gen.cities[w.to()].getCityMeal() + " | $" + w.weight()); } results.newLine(); results.append(" Total Cost: $" + shortestPath.distTo(Minn)); results.close(); results.close(); } }
UTF-8
Java
3,267
java
Main.java
Java
[ { "context": "*printed in the text file a2_out.txt\n *\n * @author Andy Hameed\n *\n */\n\npublic class Main {\n\t\n\tpublic static Dept", "end": 379, "score": 0.9998804330825806, "start": 368, "tag": "NAME", "value": "Andy Hameed" } ]
null
[]
package ConstructedClasses; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import HelperClasses.DirectedEdge; /** *Main runs searching and shortest paths algorithms used. The results are *printed in the text file a2_out.txt * * @author <NAME> * */ public class Main { public static DepthFirstPath pthDFS; public static BreadthFirstPaths pthBFS; public static int boston = Digraph.search("BOSTON"); public static int Minn = Digraph.search("MINNEAPOLIS"); public static Digraph routes = new Digraph(32); public Main() throws IOException { /** * Reading Connected Cities and adding weighted edges */ String[] temp; File file = new File("connectedCities.txt"); Scanner sc; try { sc = new Scanner(file); while (sc.hasNext()) { temp= sc.nextLine().split(","); //find weight based on the cheapest meal satisfying conditons float weight = CheapestMeal(Digraph.search(temp[0]), Digraph.search(temp[1].substring(1))); routes.addEdge(new DirectedEdge(Digraph.search(temp[0]),Digraph.search(temp[1].substring(1)),weight)); } sc.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Perform BFS and DFS at Boston and print results pthDFS = new DepthFirstPath(routes, boston); pthBFS = new BreadthFirstPaths(routes, boston); //Write into results file WriteResults(); } private float CheapestMeal(int tail, int head) { // TODO Auto-generated method stub City prev = Gen.cities[tail]; City current = Gen.cities[head]; if (prev.getCityMeal().equals("")) {current.setCityMeal(current.bestMeal().name());return current.bestMeal().price();} //if the previous meal matches the best meal in the current city, //pick the next best meal in the city if (prev.getCityMeal().equals(current.bestMeal().name())){current.setCityMeal(current.secondBestMeal().name());return current.secondBestMeal().price();} return current.bestMeal().price(); } public static void WriteResults() throws IOException { FileWriter fw = new FileWriter("a2_out.txt"); BufferedWriter results; results = new BufferedWriter(fw); //BFS results results.write("BFS: "); for (Integer w : pthBFS.pathTo(Minn)) { results.append(" " + Gen.cities[w].getName() + ","); } //DFS results results.newLine(); results.write("DFS: "); for (Integer w : pthDFS.pathTo(Minn)) { results.append(" " + Gen.cities[w].getName() + ","); } //Printing out results for shortest path Dijkstras shortestPath = new Dijkstras(routes, boston); results.newLine(); results.newLine(); results.append(" City | Meal Choice | Meal Cost"); results.newLine(); results.append(" BOSTON "); for (DirectedEdge w : shortestPath.pathTo(Minn)) { results.newLine(); results.append(" " + Gen.cities[w.to()].getName() + "|" + Gen.cities[w.to()].getCityMeal() + " | $" + w.weight()); } results.newLine(); results.append(" Total Cost: $" + shortestPath.distTo(Minn)); results.close(); results.close(); } }
3,262
0.67034
0.667279
113
27.920355
28.173338
154
false
false
0
0
0
0
0
0
2.486726
false
false
8
5b000b056bc12b77199e1505dbf06afdd7ad36c5
3,332,894,651,446
504d88dcd9744e97d34f32b7a75d9e7cdd7caf1c
/DVN-root/DVN-web/src/main/java/edu/harvard/iq/dvn/core/web/util/DateValidator.java
1afaabe3872bcb121254d67c4e483eb88f7a06c9
[]
no_license
IQSS/dvn
https://github.com/IQSS/dvn
85df3ca018f0e88ecc4490ef33971c6bc156f6bc
6a9cb81cd9e00d61033a48b2ead4c140b3559906
refs/heads/develop
2020-04-04T19:05:07.569000
2015-06-04T14:25:52
2015-06-04T14:25:52
7,610,332
5
4
null
false
2014-07-08T12:01:52
2013-01-14T18:44:27
2014-06-30T18:25:56
2014-05-16T14:13:34
269,326
17
11
0
Java
null
null
/* Copyright (C) 2005-2012, by the President and Fellows of Harvard College. 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. Dataverse Network - A web application to share, preserve and analyze research data. Developed at the Institute for Quantitative Social Science, Harvard University. Version 3.0. */ /* * DateValidator.java * * Created on February 23, 2007, 3:37 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package edu.harvard.iq.dvn.core.web.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; /** * * @author ekraffmiller */ public class DateValidator implements Validator, java.io.Serializable { /** Creates a new instance of DateValidator */ public DateValidator() { } public void validate(FacesContext context, UIComponent toValidate, Object value) { String dateString = ((String) value).trim(); boolean valid = validate(dateString); if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage("Invalid Date Format. Valid formats are YYYY-MM-DD, YYYY-MM, or YYYY. Optionally, 'BC' can be appended to the year. (By default, AD is assumed.)"); context.addMessage(toValidate.getClientId(context), message); } } private boolean validate(String dateString) { boolean valid=false; valid = isValid(dateString,"yyyy-MM-dd"); if (!valid ) { valid = isValid(dateString, "yyyy-MM"); } if (!valid) { valid = isValid(dateString,"yyyy"); } if (!valid ) { valid = isValid(dateString, "yyyyyyyyy-MM-dd GG"); } if (!valid ) { valid = isValid(dateString, "yyyyyyyyy-MM GG"); } if (!valid) { valid = isValid(dateString,"yyyyyyyyy GG"); } return valid; } private boolean isValid(String dateString, String pattern) { boolean valid=true; Date date; SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); try { dateString = dateString.trim(); date = sdf.parse(dateString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int era = calendar.get(Calendar.ERA); if (era == GregorianCalendar.AD ) { if ( year > 9999) { valid=false; } } // System.out.println("pattern is "+ pattern); // System.out.println("Year is "+year); // System.out.println("Calendar date is "+date.toString()); // System.out.println("Era is "+calendar.get(Calendar.ERA)); }catch (ParseException e) { valid=false; } if (dateString.length()>pattern.length()) { valid=false; } return valid; } public static void main(String args[]) { DateValidator validator = new DateValidator(); System.out.println("Result is "+validator.validate("-20080-02 ")); } }
UTF-8
Java
4,126
java
DateValidator.java
Java
[ { "context": "avax.faces.validator.Validator;\n\n/**\n *\n * @author ekraffmiller\n */\npublic class DateValidator implements Validat", "end": 1434, "score": 0.9996566772460938, "start": 1422, "tag": "USERNAME", "value": "ekraffmiller" } ]
null
[]
/* Copyright (C) 2005-2012, by the President and Fellows of Harvard College. 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. Dataverse Network - A web application to share, preserve and analyze research data. Developed at the Institute for Quantitative Social Science, Harvard University. Version 3.0. */ /* * DateValidator.java * * Created on February 23, 2007, 3:37 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package edu.harvard.iq.dvn.core.web.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; /** * * @author ekraffmiller */ public class DateValidator implements Validator, java.io.Serializable { /** Creates a new instance of DateValidator */ public DateValidator() { } public void validate(FacesContext context, UIComponent toValidate, Object value) { String dateString = ((String) value).trim(); boolean valid = validate(dateString); if (!valid) { ((UIInput)toValidate).setValid(false); FacesMessage message = new FacesMessage("Invalid Date Format. Valid formats are YYYY-MM-DD, YYYY-MM, or YYYY. Optionally, 'BC' can be appended to the year. (By default, AD is assumed.)"); context.addMessage(toValidate.getClientId(context), message); } } private boolean validate(String dateString) { boolean valid=false; valid = isValid(dateString,"yyyy-MM-dd"); if (!valid ) { valid = isValid(dateString, "yyyy-MM"); } if (!valid) { valid = isValid(dateString,"yyyy"); } if (!valid ) { valid = isValid(dateString, "yyyyyyyyy-MM-dd GG"); } if (!valid ) { valid = isValid(dateString, "yyyyyyyyy-MM GG"); } if (!valid) { valid = isValid(dateString,"yyyyyyyyy GG"); } return valid; } private boolean isValid(String dateString, String pattern) { boolean valid=true; Date date; SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); try { dateString = dateString.trim(); date = sdf.parse(dateString); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int era = calendar.get(Calendar.ERA); if (era == GregorianCalendar.AD ) { if ( year > 9999) { valid=false; } } // System.out.println("pattern is "+ pattern); // System.out.println("Year is "+year); // System.out.println("Calendar date is "+date.toString()); // System.out.println("Era is "+calendar.get(Calendar.ERA)); }catch (ParseException e) { valid=false; } if (dateString.length()>pattern.length()) { valid=false; } return valid; } public static void main(String args[]) { DateValidator validator = new DateValidator(); System.out.println("Result is "+validator.validate("-20080-02 ")); } }
4,126
0.615851
0.60761
122
32.811474
27.964947
200
false
false
0
0
0
0
0
0
0.581967
false
false
8
f4b91a390186a63b83b5e14a1061787be21c1dc6
16,398,185,188,146
5d668d8f2b8d224e5d3cf44f7b9b1725e92bf4da
/app/src/main/java/com/example/bionintelligence/data/model/VinosModel.java
6d6f76a4fb75cdbf3370bfe6d7e0d71e317a7e54
[]
no_license
YandreNagorniy/bion
https://github.com/YandreNagorniy/bion
468e3ae1a1c1ca4ef04328ebb636ad7bea71abdf
af5c7d246d206340b84f254cdfb211dddd30851c
refs/heads/master
2020-07-04T15:16:01.731000
2019-08-14T09:47:25
2019-08-14T09:47:25
202,321,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.bionintelligence.data.model; //Вынос import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.PrimaryKey; import static android.arch.persistence.room.ForeignKey.CASCADE; @Entity(foreignKeys = @ForeignKey(entity = CultureModel.class, parentColumns = "id", childColumns = "cultureId", onDelete = CASCADE)) public class VinosModel { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(index = true) private int cultureId; @ColumnInfo(name = "vinos_N") private double N; @ColumnInfo(name = "vinos_P2O5") private double P2O5; @ColumnInfo(name = "vinos_K2O") private double K2O; @ColumnInfo(name = "vinos_CaO") private double CaO; @ColumnInfo(name = "vinos_MgO") private double MgO; @ColumnInfo(name = "vinos_S") private double S; public VinosModel(int cultureId, double N, double P2O5, double K2O, double CaO, double MgO, double S) { this.cultureId = cultureId; this.N = N; this.P2O5 = P2O5; this.K2O = K2O; this.CaO = CaO; this.MgO = MgO; this.S = S; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCultureId() { return cultureId; } public void setCultureId(int cultureId) { this.cultureId = cultureId; } public double getN() { return N; } public void setN(double n) { N = n; } public double getP2O5() { return P2O5; } public void setP2O5(double p2O5) { P2O5 = p2O5; } public double getK2O() { return K2O; } public void setK2O(double k2O) { K2O = k2O; } public double getCaO() { return CaO; } public void setCaO(double caO) { CaO = caO; } public double getMgO() { return MgO; } public void setMgO(double mgO) { MgO = mgO; } public double getS() { return S; } public void setS(double s) { S = s; } }
UTF-8
Java
2,224
java
VinosModel.java
Java
[]
null
[]
package com.example.bionintelligence.data.model; //Вынос import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.ForeignKey; import android.arch.persistence.room.PrimaryKey; import static android.arch.persistence.room.ForeignKey.CASCADE; @Entity(foreignKeys = @ForeignKey(entity = CultureModel.class, parentColumns = "id", childColumns = "cultureId", onDelete = CASCADE)) public class VinosModel { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(index = true) private int cultureId; @ColumnInfo(name = "vinos_N") private double N; @ColumnInfo(name = "vinos_P2O5") private double P2O5; @ColumnInfo(name = "vinos_K2O") private double K2O; @ColumnInfo(name = "vinos_CaO") private double CaO; @ColumnInfo(name = "vinos_MgO") private double MgO; @ColumnInfo(name = "vinos_S") private double S; public VinosModel(int cultureId, double N, double P2O5, double K2O, double CaO, double MgO, double S) { this.cultureId = cultureId; this.N = N; this.P2O5 = P2O5; this.K2O = K2O; this.CaO = CaO; this.MgO = MgO; this.S = S; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCultureId() { return cultureId; } public void setCultureId(int cultureId) { this.cultureId = cultureId; } public double getN() { return N; } public void setN(double n) { N = n; } public double getP2O5() { return P2O5; } public void setP2O5(double p2O5) { P2O5 = p2O5; } public double getK2O() { return K2O; } public void setK2O(double k2O) { K2O = k2O; } public double getCaO() { return CaO; } public void setCaO(double caO) { CaO = caO; } public double getMgO() { return MgO; } public void setMgO(double mgO) { MgO = mgO; } public double getS() { return S; } public void setS(double s) { S = s; } }
2,224
0.591708
0.576836
104
20.336538
19.514103
133
false
false
0
0
0
0
0
0
0.442308
false
false
8
0f4ee2996ec39570a41b8f73d539d2dbaa1cb9d8
24,163,486,031,718
f4d072f592405d279087f33f804fc952a7431327
/app/src/main/java/com/project/delivery/Adapters/FlowerUserAdapter.java
f23f7ce6666894fb780735ba977746b9dc38bda1
[]
no_license
ayodyabanuka/FlowerShop
https://github.com/ayodyabanuka/FlowerShop
dffa6775cebe9b3fc0330191177ddc8326b293c8
631f673be61ca030b308df05cc0afac26aa4005c
refs/heads/master
2023-08-11T04:17:39.493000
2021-09-28T20:02:37
2021-09-28T20:02:37
411,422,520
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.delivery.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.project.delivery.Model.flower; import com.project.delivery.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class FlowerUserAdapter extends RecyclerView.Adapter<FlowerUserAdapter.FlowerViewHolder> { Context context; ArrayList<flower> flowerList; public FlowerUserAdapter(Context context, ArrayList<flower> flowerList) { this.context = context; this.flowerList = flowerList; } @NonNull @Override public FlowerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.flower_card_user, parent,false); return new FlowerViewHolder(v); } @Override public void onBindViewHolder(@NonNull FlowerViewHolder holder, int position) { flower flowers = flowerList.get(position); holder.name.setText(flowers.getName()); holder.price.setText(flowers.getPrice()); Picasso.get().load(flowers.getImageurl()).into(holder.flowerImage); } @Override public int getItemCount() { return flowerList.size(); } public static class FlowerViewHolder extends RecyclerView.ViewHolder{ TextView name,price; ImageView flowerImage; public FlowerViewHolder(@NonNull View itemView) { super(itemView); name = itemView.findViewById(R.id.userflower_name); price = itemView.findViewById(R.id.userflower_price); flowerImage = itemView.findViewById(R.id.userflowerimage); } } }
UTF-8
Java
1,903
java
FlowerUserAdapter.java
Java
[]
null
[]
package com.project.delivery.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.project.delivery.Model.flower; import com.project.delivery.R; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class FlowerUserAdapter extends RecyclerView.Adapter<FlowerUserAdapter.FlowerViewHolder> { Context context; ArrayList<flower> flowerList; public FlowerUserAdapter(Context context, ArrayList<flower> flowerList) { this.context = context; this.flowerList = flowerList; } @NonNull @Override public FlowerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.flower_card_user, parent,false); return new FlowerViewHolder(v); } @Override public void onBindViewHolder(@NonNull FlowerViewHolder holder, int position) { flower flowers = flowerList.get(position); holder.name.setText(flowers.getName()); holder.price.setText(flowers.getPrice()); Picasso.get().load(flowers.getImageurl()).into(holder.flowerImage); } @Override public int getItemCount() { return flowerList.size(); } public static class FlowerViewHolder extends RecyclerView.ViewHolder{ TextView name,price; ImageView flowerImage; public FlowerViewHolder(@NonNull View itemView) { super(itemView); name = itemView.findViewById(R.id.userflower_name); price = itemView.findViewById(R.id.userflower_price); flowerImage = itemView.findViewById(R.id.userflowerimage); } } }
1,903
0.712034
0.712034
78
23.397436
26.985912
97
false
false
0
0
0
0
0
0
0.461538
false
false
8
e4e805cf432d4ff76b5d1ed012416b8c1031a693
8,289,286,909,809
dbb9056109c039df6024a063ce995944cfe7dfc0
/src/main/java/demoCalc/ServletCalculatorMine.java
b54e8221e4afcbf412ed89fcbf3a34cb1d660686
[]
no_license
alexeykush/CalcApp
https://github.com/alexeykush/CalcApp
5f346c5ba8ca08e440886eae851eadc6dde410cb
33875a71fdc7815a2aa80b45125befe091dfcbc2
refs/heads/master
2020-04-23T06:59:15.127000
2019-02-16T11:11:44
2019-02-16T11:11:44
170,992,545
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package demoCalc; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; public class ServletCalculatorMine extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Files.copy(Paths.get("src/calc.html"),resp.getOutputStream()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String validQuery = "x=-?\\d+(.\\d+)?&y=-?\\d+(.\\d+)?&op=(add|sub|multi|div)"; PrintWriter writer = resp.getWriter(); // if (!req.getQueryString().matches(validQuery)) { // BufferedReader br = new BufferedReader(new FileReader(new File("badQuery.txt"))); // writer.println(br.lines().collect(Collectors.joining())); // } else { double x = Double.parseDouble(req.getParameter("x")); double y = Double.parseDouble(req.getParameter("y")); String op = req.getParameter("op"); double result = 0; switch (op) { case "add": result = add(x, y); break; case "sub": result = sub(x, y); break; case "multi": result = multi(x, y); break; case "div": result = division(x, y); break; } if (String.valueOf(result).matches("-?[0-9]+.0+")) { writer.printf("<html> <b> %s </b></html>",(int) result); } else { writer.printf("<html> <b> %s </b></html>",result); } // } } private double add(double x, double y) { return x + y; } private double sub(double x, double y) { return x - y; } private double multi(double x, double y) { return x * y; } private double division(double x, double y) { return x / y; } }
UTF-8
Java
2,293
java
ServletCalculatorMine.java
Java
[]
null
[]
package demoCalc; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; public class ServletCalculatorMine extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Files.copy(Paths.get("src/calc.html"),resp.getOutputStream()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String validQuery = "x=-?\\d+(.\\d+)?&y=-?\\d+(.\\d+)?&op=(add|sub|multi|div)"; PrintWriter writer = resp.getWriter(); // if (!req.getQueryString().matches(validQuery)) { // BufferedReader br = new BufferedReader(new FileReader(new File("badQuery.txt"))); // writer.println(br.lines().collect(Collectors.joining())); // } else { double x = Double.parseDouble(req.getParameter("x")); double y = Double.parseDouble(req.getParameter("y")); String op = req.getParameter("op"); double result = 0; switch (op) { case "add": result = add(x, y); break; case "sub": result = sub(x, y); break; case "multi": result = multi(x, y); break; case "div": result = division(x, y); break; } if (String.valueOf(result).matches("-?[0-9]+.0+")) { writer.printf("<html> <b> %s </b></html>",(int) result); } else { writer.printf("<html> <b> %s </b></html>",result); } // } } private double add(double x, double y) { return x + y; } private double sub(double x, double y) { return x - y; } private double multi(double x, double y) { return x * y; } private double division(double x, double y) { return x / y; } }
2,293
0.545573
0.543829
81
27.308641
27.484514
114
false
false
0
0
0
0
0
0
0.617284
false
false
8
1b87ffa7839d3ed0245536810a10e3f78b48ed37
16,982,300,713,462
8b6c47bc961327c20ca344b96937617b6e45c2ea
/src/com/cienet/common/exception/SBHospitalException.java
cc27a10c523e9e617b97854b66c310ebbcb19648
[]
no_license
wuryan/sbhospitalForAlipay
https://github.com/wuryan/sbhospitalForAlipay
4c86e10d40214b89a84402b140f12f2013c4a926
2b137f053bdc8e7848cf72002cc96eebbf5dc708
refs/heads/master
2015-08-14T21:29:01.502000
2014-12-09T10:28:44
2014-12-09T10:28:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cienet.common.exception; /** * 封装系统异常 * * @author zhixinchen * @ClassName: SBHospitalException * @Description: 系统异常封装 * @date: Nov 21, 2013 3:39:37 PM */ public class SBHospitalException extends RuntimeException { /** * 返回码 */ private String returnCode; /** * serialVersionUID */ private static final long serialVersionUID = 6483314525073285807L; /** * Constructs a new runtime exception with <code>null</code> as its detail * message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ public SBHospitalException() { super(); } /** * Constructs a new runtime exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by a call * to {@link #initCause}. * * @param returnCode the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public SBHospitalException(String returnCode) { super(); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param returnCode the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, Throwable cause) { super(cause); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param returnCode the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, String message, Throwable cause) { super(message, cause); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param message the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param returnCode the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, String message) { super(message); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified cause and a detail * message of <tt>(cause==null ? null : cause.toString())</tt> (which * typically contains the class and detail message of <tt>cause</tt>). * This constructor is useful for runtime exceptions that are little more * than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(Throwable cause) { super(cause); } /** * 获取返回码 * * @return */ public String getReturnCode() { return this.returnCode; } /** * 获取返回信息 */ public String getMessage() { return super.getMessage(); } }
UTF-8
Java
4,817
java
SBHospitalException.java
Java
[ { "context": "net.common.exception;\n\n/**\n * 封装系统异常\n *\n * @author zhixinchen\n * @ClassName: SBHospitalException\n * @Descriptio", "end": 76, "score": 0.9995101094245911, "start": 66, "tag": "USERNAME", "value": "zhixinchen" } ]
null
[]
package com.cienet.common.exception; /** * 封装系统异常 * * @author zhixinchen * @ClassName: SBHospitalException * @Description: 系统异常封装 * @date: Nov 21, 2013 3:39:37 PM */ public class SBHospitalException extends RuntimeException { /** * 返回码 */ private String returnCode; /** * serialVersionUID */ private static final long serialVersionUID = 6483314525073285807L; /** * Constructs a new runtime exception with <code>null</code> as its detail * message. The cause is not initialized, and may subsequently be * initialized by a call to {@link #initCause}. */ public SBHospitalException() { super(); } /** * Constructs a new runtime exception with the specified detail message. The * cause is not initialized, and may subsequently be initialized by a call * to {@link #initCause}. * * @param returnCode the detail message. The detail message is saved for later * retrieval by the {@link #getMessage()} method. */ public SBHospitalException(String returnCode) { super(); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param returnCode the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, Throwable cause) { super(cause); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param returnCode the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, String message, Throwable cause) { super(message, cause); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified detail message and * cause. * <p/> * Note that the detail message associated with <code>cause</code> is * <i>not</i> automatically incorporated in this runtime exception's detail * message. * * @param message the detail message (which is saved for later retrieval by the * {@link #getMessage()} method). * @param returnCode the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(String returnCode, String message) { super(message); this.returnCode = returnCode; } /** * Constructs a new runtime exception with the specified cause and a detail * message of <tt>(cause==null ? null : cause.toString())</tt> (which * typically contains the class and detail message of <tt>cause</tt>). * This constructor is useful for runtime exceptions that are little more * than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A <tt>null</tt> value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public SBHospitalException(Throwable cause) { super(cause); } /** * 获取返回码 * * @return */ public String getReturnCode() { return this.returnCode; } /** * 获取返回信息 */ public String getMessage() { return super.getMessage(); } }
4,817
0.596642
0.588667
141
32.794327
30.133631
86
false
false
0
0
0
0
0
0
0.191489
false
false
8
e181a3bc1afcd2a189833d0c41e96a86501d5aec
19,559,281,085,634
c3c3b7e7afa6fd1672b3dc96ad97260b1eeede8a
/src/main/java/org/networkcalculus/snc/gui/AnalyzeDialog.java
ff3c0b62f0efa8fc632a80d2d6cc8bf082dd2baa
[ "MIT" ]
permissive
NetCal/SNC
https://github.com/NetCal/SNC
1d923db1532c548c453f1f8ec88a7d143f9e6d2e
ee6aea8aa8a81438c8801104362cae5da97b2c46
refs/heads/master
2021-05-25T12:05:25.133000
2020-04-01T15:45:36
2020-04-01T15:45:36
127,368,763
3
1
MIT
false
2019-04-09T08:09:59
2018-03-30T02:03:19
2019-02-01T13:14:36
2019-04-09T08:09:58
9,549
0
1
2
Java
false
false
/* * (c) 2017 Michael A. Beck, Sebastian Henningsen * disco | Distributed Computer Systems Lab * University of Kaiserslautern, Germany * All Rights Reserved. * * This software is work in progress and is released in the hope that it will * be useful to the scientific community. It is provided "as is" without * express or implied warranty, including but not limited to the correctness * of the code or its suitability for any particular purpose. * * This software is provided under the MIT License, however, we would * appreciate it if you contacted the respective authors prior to commercial use. * * If you find our software useful, we would appreciate if you mentioned it * in any publication arising from the use of this software or acknowledge * our work otherwise. We would also like to hear of any fixes or useful */ package org.networkcalculus.snc.gui; import java.awt.GridLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.networkcalculus.snc.SNC; import org.networkcalculus.snc.analysis.AnalysisException; import org.networkcalculus.snc.analysis.AnalysisType; import org.networkcalculus.snc.analysis.BoundType; import org.networkcalculus.snc.network.Flow; import org.networkcalculus.snc.network.Network; import org.networkcalculus.snc.network.Vertex; /** * A dialog to poll the user for input to compute a symbolic bound for a {@Network} * * @author Sebastian Henningsen * @author Michael Beck */ public class AnalyzeDialog { private final JPanel panel; private final JLabel vertexOfInterest; private final JLabel flowOfInterest; private final JLabel analysisType; private final JLabel boundType; private final JComboBox<Displayable> vertexSelector; private final JComboBox<Displayable> flowSelector; private final JComboBox<AnalysisType> analysisSelector; private final JComboBox boundSelector; private final GridLayout layout; /** * Construct the dialog and initializes all necessary fields. */ public AnalyzeDialog() { panel = new JPanel(); vertexOfInterest = new JLabel("Vertex Of Interest: "); flowOfInterest = new JLabel("Flow Of Interest: "); analysisType = new JLabel("Analysis Type: "); boundType = new JLabel("Boundtype : "); vertexSelector = new JComboBox(MainWindow.convertDisplayables(SNC.getInstance().getCurrentNetwork().getVertices())); flowSelector = new JComboBox(MainWindow.convertDisplayables(SNC.getInstance().getCurrentNetwork().getFlows())); analysisSelector = new JComboBox(AnalysisType.values()); boundSelector = new JComboBox(BoundType.values()); layout = new GridLayout(0, 2); panel.setLayout(layout); panel.add(vertexOfInterest); panel.add(vertexSelector); panel.add(flowOfInterest); panel.add(flowSelector); panel.add(analysisType); panel.add(analysisSelector); panel.add(boundType); panel.add(boundSelector); } /** * Displays the dialog. */ public void display() { int result = JOptionPane.showConfirmDialog(null, panel, "Analyze Dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { Network nw = SNC.getInstance().getCurrentNetwork(); int flowID = ((Displayable) flowSelector.getSelectedItem()).getID(); Flow flow = nw.getFlow(flowID); int vertexID = ((Displayable) vertexSelector.getSelectedItem()).getID(); Vertex vertex = nw.getVertex(vertexID); try { SNC.getInstance().analyzeNetwork(flow, vertex, (AnalysisType) analysisSelector.getSelectedItem(), (BoundType) boundSelector.getSelectedItem(), nw); } catch(AnalysisException ex) { System.out.println(ex.getMessage()); } // Just for debugging System.out.println(vertexSelector.getSelectedItem() + " " + flowSelector.getSelectedItem() + " " + analysisSelector.getSelectedItem() + " " + boundSelector.getSelectedItem()); } } }
UTF-8
Java
4,288
java
AnalyzeDialog.java
Java
[ { "context": "/*\n * (c) 2017 Michael A. Beck, Sebastian Henningsen\n * \t\tdisco | Distributed C", "end": 31, "score": 0.9998899698257446, "start": 16, "tag": "NAME", "value": "Michael A. Beck" }, { "context": "/*\n * (c) 2017 Michael A. Beck, Sebastian Henningsen\n * \t\tdisco ...
null
[]
/* * (c) 2017 <NAME>, <NAME> * disco | Distributed Computer Systems Lab * University of Kaiserslautern, Germany * All Rights Reserved. * * This software is work in progress and is released in the hope that it will * be useful to the scientific community. It is provided "as is" without * express or implied warranty, including but not limited to the correctness * of the code or its suitability for any particular purpose. * * This software is provided under the MIT License, however, we would * appreciate it if you contacted the respective authors prior to commercial use. * * If you find our software useful, we would appreciate if you mentioned it * in any publication arising from the use of this software or acknowledge * our work otherwise. We would also like to hear of any fixes or useful */ package org.networkcalculus.snc.gui; import java.awt.GridLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.networkcalculus.snc.SNC; import org.networkcalculus.snc.analysis.AnalysisException; import org.networkcalculus.snc.analysis.AnalysisType; import org.networkcalculus.snc.analysis.BoundType; import org.networkcalculus.snc.network.Flow; import org.networkcalculus.snc.network.Network; import org.networkcalculus.snc.network.Vertex; /** * A dialog to poll the user for input to compute a symbolic bound for a {@Network} * * @author <NAME> * @author <NAME> */ public class AnalyzeDialog { private final JPanel panel; private final JLabel vertexOfInterest; private final JLabel flowOfInterest; private final JLabel analysisType; private final JLabel boundType; private final JComboBox<Displayable> vertexSelector; private final JComboBox<Displayable> flowSelector; private final JComboBox<AnalysisType> analysisSelector; private final JComboBox boundSelector; private final GridLayout layout; /** * Construct the dialog and initializes all necessary fields. */ public AnalyzeDialog() { panel = new JPanel(); vertexOfInterest = new JLabel("Vertex Of Interest: "); flowOfInterest = new JLabel("Flow Of Interest: "); analysisType = new JLabel("Analysis Type: "); boundType = new JLabel("Boundtype : "); vertexSelector = new JComboBox(MainWindow.convertDisplayables(SNC.getInstance().getCurrentNetwork().getVertices())); flowSelector = new JComboBox(MainWindow.convertDisplayables(SNC.getInstance().getCurrentNetwork().getFlows())); analysisSelector = new JComboBox(AnalysisType.values()); boundSelector = new JComboBox(BoundType.values()); layout = new GridLayout(0, 2); panel.setLayout(layout); panel.add(vertexOfInterest); panel.add(vertexSelector); panel.add(flowOfInterest); panel.add(flowSelector); panel.add(analysisType); panel.add(analysisSelector); panel.add(boundType); panel.add(boundSelector); } /** * Displays the dialog. */ public void display() { int result = JOptionPane.showConfirmDialog(null, panel, "Analyze Dialog", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { Network nw = SNC.getInstance().getCurrentNetwork(); int flowID = ((Displayable) flowSelector.getSelectedItem()).getID(); Flow flow = nw.getFlow(flowID); int vertexID = ((Displayable) vertexSelector.getSelectedItem()).getID(); Vertex vertex = nw.getVertex(vertexID); try { SNC.getInstance().analyzeNetwork(flow, vertex, (AnalysisType) analysisSelector.getSelectedItem(), (BoundType) boundSelector.getSelectedItem(), nw); } catch(AnalysisException ex) { System.out.println(ex.getMessage()); } // Just for debugging System.out.println(vertexSelector.getSelectedItem() + " " + flowSelector.getSelectedItem() + " " + analysisSelector.getSelectedItem() + " " + boundSelector.getSelectedItem()); } } }
4,245
0.689132
0.687733
109
38.339451
29.474983
139
false
false
0
0
0
0
0
0
0.66055
false
false
8
db0f313d3f71a85d49cdd846bcff35c844f128e5
19,559,281,085,520
8ca30a266c909da45e4f70807e2a51fd862ce44b
/src/main/java/com/secusoft/ssw/mapper/monitor/DepartmentMapper.java
aa03c7a30e5aa4287569e251ee4b6cdd5f049aa9
[]
no_license
zhu1459335028/app
https://github.com/zhu1459335028/app
ec60fff4e83575dcb8dc959acbb430f712e59a9d
610428aa75e2a0377a5121f8573e2d51528b9acc
refs/heads/master
2020-08-15T01:04:59.567000
2019-10-15T12:17:42
2019-10-15T12:17:42
215,257,614
0
0
null
false
2019-10-15T12:21:24
2019-10-15T09:20:05
2019-10-15T12:20:28
2019-10-15T12:21:23
0
0
0
1
JavaScript
false
false
package com.secusoft.ssw.mapper.monitor; import com.secusoft.ssw.model.monitor.Department; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface DepartmentMapper { @Select("SELECT * FROM department where outletid=#{outletid}") List<Department> selectDepartmentByOutletId(@Param("outletid") int outletid); @Select("SELECT * FROM department where outletid=#{outletid} and type=#{type}") List<Department> selectDepartmentByOutletIdAndType(@Param("outletid") int outletid,@Param("type") int type); @Select("SELECT d.type FROM department d " + "inner join employee e on e.departmentid=d.id and e.outletid=d.outletid " + "where e.id=#{employeeid}") Integer selectDepartmentTypeByEmployeeId(@Param("employeeid") String employeeid); }
UTF-8
Java
874
java
DepartmentMapper.java
Java
[]
null
[]
package com.secusoft.ssw.mapper.monitor; import com.secusoft.ssw.model.monitor.Department; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface DepartmentMapper { @Select("SELECT * FROM department where outletid=#{outletid}") List<Department> selectDepartmentByOutletId(@Param("outletid") int outletid); @Select("SELECT * FROM department where outletid=#{outletid} and type=#{type}") List<Department> selectDepartmentByOutletIdAndType(@Param("outletid") int outletid,@Param("type") int type); @Select("SELECT d.type FROM department d " + "inner join employee e on e.departmentid=d.id and e.outletid=d.outletid " + "where e.id=#{employeeid}") Integer selectDepartmentTypeByEmployeeId(@Param("employeeid") String employeeid); }
874
0.7746
0.7746
24
35.416668
32.560093
109
false
false
0
0
0
0
0
0
0.916667
false
false
8
2e9623ed00b926487cf0a520faddbc51d114d5e8
19,559,281,082,393
ac7c25fb8e77e1bd99be7c8e9c03f6f6d9a0aeac
/src/main/java/com/com/springmvc/model/User.java
dec1eb5a107efd1904253a876b49d633c4caf873
[]
no_license
tallurivenkat/SpringMvcAngularApp
https://github.com/tallurivenkat/SpringMvcAngularApp
a20cd609d88541b35a0411dc8b410291a25e0bff
b216d68d8fb46ed2c02a0cc18d85ff044dda7f9b
refs/heads/master
2021-01-17T20:06:04.973000
2016-06-20T21:36:37
2016-06-20T21:36:37
61,581,253
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.com.springmvc.model; /** * @author Venkat Talluri * */ public class User { private long id; /** * @return the id */ public long getId() { return id; } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the address */ public String getAddress() { return address; } /** * @param address the address to set */ public void setAddress(String address) { this.address = address; } /** * @return the active */ public Boolean getActive() { return active; } /** * @param active the active to set */ public void setActive(Boolean active) { this.active = active; } private String username; private String address; private Boolean active; public User(){ id=0; } public User(long id, String username, String address, Boolean active){ this.id = id; this.username = username; this.address = address; this.active = active; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof User)) return false; User other = (User) obj; if (id != other.id) return false; return true; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", address=" + address + ", active=" + active + "]"; } }
UTF-8
Java
1,979
java
User.java
Java
[ { "context": "/\npackage com.com.springmvc.model;\n\n/**\n * @author Venkat Talluri\n *\n */\n\npublic class User {\n \n private long id", "end": 75, "score": 0.9997684359550476, "start": 61, "tag": "NAME", "value": "Venkat Talluri" }, { "context": "ve){\n this.id = id;\n ...
null
[]
/** * */ package com.com.springmvc.model; /** * @author <NAME> * */ public class User { private long id; /** * @return the id */ public long getId() { return id; } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the address */ public String getAddress() { return address; } /** * @param address the address to set */ public void setAddress(String address) { this.address = address; } /** * @return the active */ public Boolean getActive() { return active; } /** * @param active the active to set */ public void setActive(Boolean active) { this.active = active; } private String username; private String address; private Boolean active; public User(){ id=0; } public User(long id, String username, String address, Boolean active){ this.id = id; this.username = username; this.address = address; this.active = active; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof User)) return false; User other = (User) obj; if (id != other.id) return false; return true; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", address=" + address + ", active=" + active + "]"; } }
1,971
0.535624
0.532592
119
15.638656
15.658504
83
false
false
0
0
0
0
0
0
0.764706
false
false
8
595e167f08533becca15352784a45210e8b07a7b
21,277,267,986,005
270fdb967f4a5894201860d6e6cff53a41e694cf
/src/main/java/com/github/platymemo/alaskanativecraft/client/model/entity/SealEntityModel.java
b9fc1e36842eecb4467a296004089c3a1f5e980f
[ "CC0-1.0", "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
Platymemo/alaskanativecraft
https://github.com/Platymemo/alaskanativecraft
93e20d99d7fc5cccd42d68ba1fe158c50c590878
b7335be4a731434a8920614886828ab587eb1bab
refs/heads/quilt-1.19
2023-08-19T21:41:25.369000
2022-10-07T08:36:13
2022-10-07T08:36:13
321,296,674
10
18
CC0-1.0
false
2023-09-03T03:11:15
2020-12-14T09:26:36
2023-07-08T13:36:42
2023-09-03T03:11:12
4,931
9
13
21
Java
false
false
package com.github.platymemo.alaskanativecraft.client.model.entity; import com.github.platymemo.alaskanativecraft.entity.SealEntity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import org.jetbrains.annotations.NotNull; import net.minecraft.client.model.ModelData; import net.minecraft.client.model.ModelPart; import net.minecraft.client.model.ModelPartBuilder; import net.minecraft.client.model.ModelPartData; import net.minecraft.client.model.ModelTransform; import net.minecraft.client.model.TexturedModelData; import net.minecraft.client.render.entity.model.EntityModelPartNames; import net.minecraft.client.render.entity.model.QuadrupedEntityModel; import net.minecraft.util.math.MathHelper; @Environment(EnvType.CLIENT) public class SealEntityModel<T extends SealEntity> extends QuadrupedEntityModel<T> { public static final String STOMACH = "stomach"; public static final String TAIL = "tail"; protected final ModelPart stomach; protected final ModelPart tail; public SealEntityModel(ModelPart root) { super(root, true, 9.0F, 1.0F, 2.0F, 1.5F, 12); this.stomach = root.getChild(STOMACH); this.tail = root.getChild(TAIL); } public static @NotNull TexturedModelData getTexturedModelData() { ModelData modelData = new ModelData(); ModelPartData root = modelData.getRoot(); root.addChild(EntityModelPartNames.RIGHT_FRONT_LEG, ModelPartBuilder.create().uv(38, 6).cuboid(-5.0F, -1.0F, -1.0F, 5.0F, 1.0F, 3.0F), ModelTransform.of(-6.0F, 24.0F, -6.0F, 0.0F, -1.0F, 0.0F) ); root.addChild(EntityModelPartNames.LEFT_FRONT_LEG, ModelPartBuilder.create().uv(32, 27).cuboid(0.0F, -1.0F, -1.0F, 5.0F, 1.0F, 3.0F), ModelTransform.of(5.0F, 24.0F, -6.0F, 0.0F, 1.0F, 0.0F) ); root.addChild(EntityModelPartNames.RIGHT_HIND_LEG, ModelPartBuilder.create().uv(30, 0).cuboid(-2.0F, 0.0F, -1.0F, 3.0F, 1.0F, 5.0F), ModelTransform.pivot(-3.0F, 23.0F, 11.0F) ); root.addChild(EntityModelPartNames.LEFT_HIND_LEG, ModelPartBuilder.create().uv(13, 38).cuboid(-1.0F, 0.0F, -1.1F, 3.0F, 1.0F, 5.0F), ModelTransform.pivot(2.0F, 23.0F, 11.1F) ); root.addChild(EntityModelPartNames.HEAD, ModelPartBuilder.create() .uv(29, 31).cuboid(EntityModelPartNames.NECK, -4.5F, -5.0F, -3.0F, 9.0F, 9.0F, 3.0F) .uv(32, 18).cuboid(-3.5F, -4.0F, -5.0F, 7.0F, 7.0F, 2.0F) .uv(38, 10).cuboid(EntityModelPartNames.NOSE, -2.5F, -1.0F, -7.0F, 5.0F, 3.0F, 2.0F), ModelTransform.pivot(-0.5F, 19.0F, -8.0F) ); root.addChild(EntityModelPartNames.BODY, ModelPartBuilder.create().uv(0, 0).cuboid(-5.5F, -5.0F, -4.0F, 11.0F, 10.0F, 8.0F), ModelTransform.pivot(-0.5F, 19.0F, -4.0F) ); root.addChild(STOMACH, ModelPartBuilder.create().uv(0, 18).cuboid(-4.5F, -4.5F, -3.5F, 9.0F, 9.0F, 7.0F), ModelTransform.pivot(-0.5F, 19.5F, 3.5F) ); root.addChild(TAIL, ModelPartBuilder.create().uv(0, 34).cuboid(-2.5F, -2.5F, -2.0F, 5.0F, 5.0F, 4.0F), ModelTransform.pivot(-0.5F, 21.0F, 9.0F) ); return TexturedModelData.of(modelData, 64, 64); } @Override protected Iterable<ModelPart> getBodyParts() { return Iterables.concat(super.getBodyParts(), ImmutableList.of(this.stomach), ImmutableList.of(this.tail)); } @Override public void setAngles(@NotNull T sealEntity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { this.head.pitch = headPitch * 0.017453292F; this.head.yaw = headYaw * 0.017453292F; this.body.pitch = 0.0F; float flipperAnim = MathHelper.cos(limbAngle * 0.4F) * 0.5F * limbDistance; if (!sealEntity.isTouchingWater() && sealEntity.isOnGround()) { this.rightHindLeg.setAngles(0.0F, -flipperAnim, 0.0F); this.leftHindLeg.setAngles(0.0F, flipperAnim, 0.0F); this.rightFrontLeg.setAngles(0.0F, -flipperAnim * 2.0F, 0.0F); this.leftFrontLeg.setAngles(0.0F, flipperAnim * 2.0F, 0.0F); } else { this.rightHindLeg.setAngles(flipperAnim, 0.0F, 0.0F); this.leftHindLeg.setAngles(-flipperAnim, 0.0F, 0.0F); this.rightFrontLeg.setAngles(1.0F + flipperAnim, -(flipperAnim * 2.0F), -(1.0F + flipperAnim)); this.leftFrontLeg.setAngles(1.0F + flipperAnim, flipperAnim * 2.0F, 1.0F + flipperAnim); } } }
UTF-8
Java
4,290
java
SealEntityModel.java
Java
[ { "context": "package com.github.platymemo.alaskanativecraft.client.model.entity;\n\nimport co", "end": 28, "score": 0.9738130569458008, "start": 19, "tag": "USERNAME", "value": "platymemo" }, { "context": "tivecraft.client.model.entity;\n\nimport com.github.platymemo.alaskanativecra...
null
[]
package com.github.platymemo.alaskanativecraft.client.model.entity; import com.github.platymemo.alaskanativecraft.entity.SealEntity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import org.jetbrains.annotations.NotNull; import net.minecraft.client.model.ModelData; import net.minecraft.client.model.ModelPart; import net.minecraft.client.model.ModelPartBuilder; import net.minecraft.client.model.ModelPartData; import net.minecraft.client.model.ModelTransform; import net.minecraft.client.model.TexturedModelData; import net.minecraft.client.render.entity.model.EntityModelPartNames; import net.minecraft.client.render.entity.model.QuadrupedEntityModel; import net.minecraft.util.math.MathHelper; @Environment(EnvType.CLIENT) public class SealEntityModel<T extends SealEntity> extends QuadrupedEntityModel<T> { public static final String STOMACH = "stomach"; public static final String TAIL = "tail"; protected final ModelPart stomach; protected final ModelPart tail; public SealEntityModel(ModelPart root) { super(root, true, 9.0F, 1.0F, 2.0F, 1.5F, 12); this.stomach = root.getChild(STOMACH); this.tail = root.getChild(TAIL); } public static @NotNull TexturedModelData getTexturedModelData() { ModelData modelData = new ModelData(); ModelPartData root = modelData.getRoot(); root.addChild(EntityModelPartNames.RIGHT_FRONT_LEG, ModelPartBuilder.create().uv(38, 6).cuboid(-5.0F, -1.0F, -1.0F, 5.0F, 1.0F, 3.0F), ModelTransform.of(-6.0F, 24.0F, -6.0F, 0.0F, -1.0F, 0.0F) ); root.addChild(EntityModelPartNames.LEFT_FRONT_LEG, ModelPartBuilder.create().uv(32, 27).cuboid(0.0F, -1.0F, -1.0F, 5.0F, 1.0F, 3.0F), ModelTransform.of(5.0F, 24.0F, -6.0F, 0.0F, 1.0F, 0.0F) ); root.addChild(EntityModelPartNames.RIGHT_HIND_LEG, ModelPartBuilder.create().uv(30, 0).cuboid(-2.0F, 0.0F, -1.0F, 3.0F, 1.0F, 5.0F), ModelTransform.pivot(-3.0F, 23.0F, 11.0F) ); root.addChild(EntityModelPartNames.LEFT_HIND_LEG, ModelPartBuilder.create().uv(13, 38).cuboid(-1.0F, 0.0F, -1.1F, 3.0F, 1.0F, 5.0F), ModelTransform.pivot(2.0F, 23.0F, 11.1F) ); root.addChild(EntityModelPartNames.HEAD, ModelPartBuilder.create() .uv(29, 31).cuboid(EntityModelPartNames.NECK, -4.5F, -5.0F, -3.0F, 9.0F, 9.0F, 3.0F) .uv(32, 18).cuboid(-3.5F, -4.0F, -5.0F, 7.0F, 7.0F, 2.0F) .uv(38, 10).cuboid(EntityModelPartNames.NOSE, -2.5F, -1.0F, -7.0F, 5.0F, 3.0F, 2.0F), ModelTransform.pivot(-0.5F, 19.0F, -8.0F) ); root.addChild(EntityModelPartNames.BODY, ModelPartBuilder.create().uv(0, 0).cuboid(-5.5F, -5.0F, -4.0F, 11.0F, 10.0F, 8.0F), ModelTransform.pivot(-0.5F, 19.0F, -4.0F) ); root.addChild(STOMACH, ModelPartBuilder.create().uv(0, 18).cuboid(-4.5F, -4.5F, -3.5F, 9.0F, 9.0F, 7.0F), ModelTransform.pivot(-0.5F, 19.5F, 3.5F) ); root.addChild(TAIL, ModelPartBuilder.create().uv(0, 34).cuboid(-2.5F, -2.5F, -2.0F, 5.0F, 5.0F, 4.0F), ModelTransform.pivot(-0.5F, 21.0F, 9.0F) ); return TexturedModelData.of(modelData, 64, 64); } @Override protected Iterable<ModelPart> getBodyParts() { return Iterables.concat(super.getBodyParts(), ImmutableList.of(this.stomach), ImmutableList.of(this.tail)); } @Override public void setAngles(@NotNull T sealEntity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { this.head.pitch = headPitch * 0.017453292F; this.head.yaw = headYaw * 0.017453292F; this.body.pitch = 0.0F; float flipperAnim = MathHelper.cos(limbAngle * 0.4F) * 0.5F * limbDistance; if (!sealEntity.isTouchingWater() && sealEntity.isOnGround()) { this.rightHindLeg.setAngles(0.0F, -flipperAnim, 0.0F); this.leftHindLeg.setAngles(0.0F, flipperAnim, 0.0F); this.rightFrontLeg.setAngles(0.0F, -flipperAnim * 2.0F, 0.0F); this.leftFrontLeg.setAngles(0.0F, flipperAnim * 2.0F, 0.0F); } else { this.rightHindLeg.setAngles(flipperAnim, 0.0F, 0.0F); this.leftHindLeg.setAngles(-flipperAnim, 0.0F, 0.0F); this.rightFrontLeg.setAngles(1.0F + flipperAnim, -(flipperAnim * 2.0F), -(1.0F + flipperAnim)); this.leftFrontLeg.setAngles(1.0F + flipperAnim, flipperAnim * 2.0F, 1.0F + flipperAnim); } } }
4,290
0.71655
0.645221
98
42.775509
30.059305
141
false
false
0
0
0
0
0
0
3.653061
false
false
8
b6544119facfc8f134f81868edf6be709c137baa
1,949,915,180,582
4a4fb58f77d3e44b60a0f4bb007d64d64f1aba0e
/sales-order-repository/src/main/java/org/zenbaei/salesOrder/component/customer/entity/Customer.java
38cca5ef2cd6233f0af0b325c9ec589f6959a28e
[]
no_license
zenbaei/sales-order-parent
https://github.com/zenbaei/sales-order-parent
3d5803f22ee17e30bb3c4225a40234bc42707ba5
8d1554ce7fde4d346d82c78190802d3aa8af0e03
refs/heads/master
2016-08-08T18:48:14.324000
2016-03-04T02:41:23
2016-03-04T02:41:23
52,194,485
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zenbaei.salesOrder.component.customer.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.validator.constraints.NotBlank; import org.zenbaei.salesOrder.common.entity.BaseEntity; @Entity @Table(name = "CUSTOMERS") @DynamicUpdate(true) public class Customer extends BaseEntity { @NotBlank private String name; @NotBlank @Column(unique = true) private String code; private String address; private String phone1; private String phone2; @Column(name = "CREDIT_LIMIT") private double creditLimit; @Column(name = "CURRENT_CREDIT") private double currentCredit; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public double getCurrentCredit() { return currentCredit; } public void setCurrentCredit(double currentCredit) { this.currentCredit = currentCredit; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public double getCreditLimit() { return creditLimit; } public void setCreditLimit(double creditLimit) { this.creditLimit = creditLimit; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Customer)) return false; Customer object = (Customer) obj; if (id != null || object.getId() != null && id.equals(object.getId())) return true; if (id != null || object.getId() != null && !id.equals(object.getId())) return false; if (code == null || code.trim().isEmpty() || object.getCode() == null || object.getCode().trim().isEmpty()) return false; if (code.trim().equals(object.getCode().trim())) return true; return false; } @Override public int hashCode() { if (id != null) return id.hashCode(); return code == null || code.trim().isEmpty() ? 0 : code.trim().hashCode(); } @Override public String toString() { return "Customer [name=" + name + ", code=" + code + ", address=" + address + ", phone1=" + phone1 + ", phone2=" + phone2 + ", creditLimit=" + creditLimit + ", currentCredit=" + currentCredit + "]"; } }
UTF-8
Java
2,685
java
Customer.java
Java
[]
null
[]
package org.zenbaei.salesOrder.component.customer.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.validator.constraints.NotBlank; import org.zenbaei.salesOrder.common.entity.BaseEntity; @Entity @Table(name = "CUSTOMERS") @DynamicUpdate(true) public class Customer extends BaseEntity { @NotBlank private String name; @NotBlank @Column(unique = true) private String code; private String address; private String phone1; private String phone2; @Column(name = "CREDIT_LIMIT") private double creditLimit; @Column(name = "CURRENT_CREDIT") private double currentCredit; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public double getCurrentCredit() { return currentCredit; } public void setCurrentCredit(double currentCredit) { this.currentCredit = currentCredit; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public double getCreditLimit() { return creditLimit; } public void setCreditLimit(double creditLimit) { this.creditLimit = creditLimit; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Customer)) return false; Customer object = (Customer) obj; if (id != null || object.getId() != null && id.equals(object.getId())) return true; if (id != null || object.getId() != null && !id.equals(object.getId())) return false; if (code == null || code.trim().isEmpty() || object.getCode() == null || object.getCode().trim().isEmpty()) return false; if (code.trim().equals(object.getCode().trim())) return true; return false; } @Override public int hashCode() { if (id != null) return id.hashCode(); return code == null || code.trim().isEmpty() ? 0 : code.trim().hashCode(); } @Override public String toString() { return "Customer [name=" + name + ", code=" + code + ", address=" + address + ", phone1=" + phone1 + ", phone2=" + phone2 + ", creditLimit=" + creditLimit + ", currentCredit=" + currentCredit + "]"; } }
2,685
0.653631
0.646555
126
20.309525
22.225563
113
false
false
0
0
0
0
0
0
0.714286
false
false
8
010ad870fd1083c4246cf68a6c1b27562a65c506
11,295,763,988,507
32da1b7b08c02c4640e25d106c739b9d94824f7a
/ad-common-utils/src/main/java/pe/fu/common/utils/XmlUtils.java
ae363922e8fdaf08947aa08185b4530d616a22e0
[ "Apache-2.0" ]
permissive
ontology-fhcj/ad
https://github.com/ontology-fhcj/ad
50eada5bc850279cd1ef6e122197c18412346f28
de2c9228996fd84c1d3c7db3f9a6e039a11d4d7d
refs/heads/master
2018-04-08T15:24:27.282000
2017-07-30T08:29:19
2017-07-30T08:29:19
89,757,188
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.fu.common.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public abstract class XmlUtils { /** * 创建一个XML文档 * * @param xml * @return * @throws DocumentException */ public static Document parseDocument(String xml) throws DocumentException { if (StringUtils.isEmpty(xml)) { return DocumentHelper.createDocument(); } return DocumentHelper.parseText(xml); } /** * 创建一个XML文档 * * @param file * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Document parseDocument(File file, String charsetName) throws DocumentException, IOException { return parseDocument(FileUtils.readFile(file, charsetName)); } /** * 创建一个XML文档 * * @param is * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Document parseDocument(InputStream is, String charsetName) throws DocumentException, IOException { return parseDocument(StringUtils.inputStreamToString(is, charsetName)); } /** * 解析XML字符串生成XML元素对象 * * @param xml * @return * @throws DocumentException */ public static Element parseElement(String xml) throws DocumentException { return parseDocument(xml).getRootElement(); } /** * 根据文件名读取XML元素对象 * * @param file * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Element parseElement(File file, String charsetName) throws DocumentException, IOException { return parseElement(FileUtils.readFile(file, charsetName)); } /** * 根据XML字符流生成XML元素对象 * * @param is * @param charsetName * @return * @throws IOException * @throws DocumentException */ public static Element parseElement(InputStream is, String charsetName) throws DocumentException, IOException { return parseElement(StringUtils.inputStreamToString(is, charsetName)); } /** * 获取元素属性值 * * @param element * @param attributeNames * 为空则获取所有属性 * @return */ public static Map<String, String> getAttributes(Element element, List<String> attributeNames, boolean isIgnoreCase) { if (isIgnoreCase && attributeNames != null) { List<String> tempAttributeNames = new ArrayList<String>(); for (String attributeName : attributeNames) { tempAttributeNames.add(attributeName.toUpperCase()); } attributeNames.clear(); attributeNames.addAll(tempAttributeNames); } Map<String, String> attrMap = new HashMap<String, String>(); if (element != null) { List<?> objects = element.attributes(); for (Object o : objects) { if (o instanceof Attribute) { Attribute attr = (Attribute) o; if (attributeNames == null || attributeNames.isEmpty()) { attrMap.put(attr.getName(), attr.getValue()); } else if (attributeNames.contains(isIgnoreCase ? attr.getName().toUpperCase() : attr.getName())) { attrMap.put(attr.getName(), attr.getValue()); } } } } return attrMap; } /** * 获取子节点属性 * * @param element * @param childElementNames * @param attributeNames * @return */ public static List<Map<String, String>> getChildrenAttributes(Element element, List<String> childElementNames, List<String> attributeNames, boolean isIgnoreCase4AttributeName) { List<Map<String, String>> rt = new ArrayList<Map<String, String>>(); if (element == null) { return rt; } List<?> elements = element.elements(); if (elements == null) { return rt; } for (Object o : elements) { if (o instanceof Element) { Element el = (Element) o; if (childElementNames == null || childElementNames.isEmpty()) { rt.add(getAttributes(el, attributeNames, isIgnoreCase4AttributeName)); } else if (childElementNames.contains(el.getName())) { rt.add(getAttributes(el, attributeNames, isIgnoreCase4AttributeName)); } } } return rt; } /** * 将xml文件格式化成XSLT描述的格式 * * @param sourceText * @param styleSheetText * @return * @throws DocumentException * @throws TransformerException */ public static Document xsltTransform(String sourceText, String styleSheetText) throws DocumentException, TransformerException { return xsltTransform(parseDocument(sourceText), parseDocument(styleSheetText)); } /** * 将xml文件格式化成XSLT描述的格式 * * @param sourceDocument * @param styleSheetDocument * @return * @throws TransformerException */ public static Document xsltTransform(Document sourceDocument, Document styleSheetDocument) throws TransformerException { // 资源 DocumentSource sourceDs = new DocumentSource(sourceDocument); DocumentSource styleSheetDs = new DocumentSource(styleSheetDocument); // 结果 DocumentResult result = new DocumentResult(); // 创建转换器 Transformer transformer = TransformerFactory.newInstance().newTransformer(styleSheetDs); transformer.transform(sourceDs, result); return result.getDocument(); } }
UTF-8
Java
5,599
java
XmlUtils.java
Java
[]
null
[]
package pe.fu.common.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public abstract class XmlUtils { /** * 创建一个XML文档 * * @param xml * @return * @throws DocumentException */ public static Document parseDocument(String xml) throws DocumentException { if (StringUtils.isEmpty(xml)) { return DocumentHelper.createDocument(); } return DocumentHelper.parseText(xml); } /** * 创建一个XML文档 * * @param file * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Document parseDocument(File file, String charsetName) throws DocumentException, IOException { return parseDocument(FileUtils.readFile(file, charsetName)); } /** * 创建一个XML文档 * * @param is * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Document parseDocument(InputStream is, String charsetName) throws DocumentException, IOException { return parseDocument(StringUtils.inputStreamToString(is, charsetName)); } /** * 解析XML字符串生成XML元素对象 * * @param xml * @return * @throws DocumentException */ public static Element parseElement(String xml) throws DocumentException { return parseDocument(xml).getRootElement(); } /** * 根据文件名读取XML元素对象 * * @param file * @param charsetName * @return * @throws DocumentException * @throws IOException */ public static Element parseElement(File file, String charsetName) throws DocumentException, IOException { return parseElement(FileUtils.readFile(file, charsetName)); } /** * 根据XML字符流生成XML元素对象 * * @param is * @param charsetName * @return * @throws IOException * @throws DocumentException */ public static Element parseElement(InputStream is, String charsetName) throws DocumentException, IOException { return parseElement(StringUtils.inputStreamToString(is, charsetName)); } /** * 获取元素属性值 * * @param element * @param attributeNames * 为空则获取所有属性 * @return */ public static Map<String, String> getAttributes(Element element, List<String> attributeNames, boolean isIgnoreCase) { if (isIgnoreCase && attributeNames != null) { List<String> tempAttributeNames = new ArrayList<String>(); for (String attributeName : attributeNames) { tempAttributeNames.add(attributeName.toUpperCase()); } attributeNames.clear(); attributeNames.addAll(tempAttributeNames); } Map<String, String> attrMap = new HashMap<String, String>(); if (element != null) { List<?> objects = element.attributes(); for (Object o : objects) { if (o instanceof Attribute) { Attribute attr = (Attribute) o; if (attributeNames == null || attributeNames.isEmpty()) { attrMap.put(attr.getName(), attr.getValue()); } else if (attributeNames.contains(isIgnoreCase ? attr.getName().toUpperCase() : attr.getName())) { attrMap.put(attr.getName(), attr.getValue()); } } } } return attrMap; } /** * 获取子节点属性 * * @param element * @param childElementNames * @param attributeNames * @return */ public static List<Map<String, String>> getChildrenAttributes(Element element, List<String> childElementNames, List<String> attributeNames, boolean isIgnoreCase4AttributeName) { List<Map<String, String>> rt = new ArrayList<Map<String, String>>(); if (element == null) { return rt; } List<?> elements = element.elements(); if (elements == null) { return rt; } for (Object o : elements) { if (o instanceof Element) { Element el = (Element) o; if (childElementNames == null || childElementNames.isEmpty()) { rt.add(getAttributes(el, attributeNames, isIgnoreCase4AttributeName)); } else if (childElementNames.contains(el.getName())) { rt.add(getAttributes(el, attributeNames, isIgnoreCase4AttributeName)); } } } return rt; } /** * 将xml文件格式化成XSLT描述的格式 * * @param sourceText * @param styleSheetText * @return * @throws DocumentException * @throws TransformerException */ public static Document xsltTransform(String sourceText, String styleSheetText) throws DocumentException, TransformerException { return xsltTransform(parseDocument(sourceText), parseDocument(styleSheetText)); } /** * 将xml文件格式化成XSLT描述的格式 * * @param sourceDocument * @param styleSheetDocument * @return * @throws TransformerException */ public static Document xsltTransform(Document sourceDocument, Document styleSheetDocument) throws TransformerException { // 资源 DocumentSource sourceDs = new DocumentSource(sourceDocument); DocumentSource styleSheetDs = new DocumentSource(styleSheetDocument); // 结果 DocumentResult result = new DocumentResult(); // 创建转换器 Transformer transformer = TransformerFactory.newInstance().newTransformer(styleSheetDs); transformer.transform(sourceDs, result); return result.getDocument(); } }
5,599
0.71792
0.716063
207
25.019323
26.336353
113
false
false
0
0
0
0
0
0
1.826087
false
false
8
24b365e7056493121e9c843d76be32077a145099
21,174,188,774,458
7f76f1f87f19237ec672d00bbeaf5626d675c090
/eclipse-workspace/JavaProgramming/src/strings/StringPalindrome.java
49edb7afbcb40fd2b7517313a3aee4907d1b9ef6
[]
no_license
pappumahato/java
https://github.com/pappumahato/java
14649b9b500d0435fea99c0f01863802c853e3c4
2f31815786b6d8e072b5c9dddb01f6629ed4496a
refs/heads/master
2020-05-09T16:40:53.952000
2019-04-14T08:29:33
2019-04-14T08:29:33
181,274,528
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package strings; import java.util.Scanner; public class StringPalindrome { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String st=sc.nextLine(); String nstr=""; char ch[]=st.toCharArray(); for (int i = 0; i < ch.length/2; i++) { char t=ch[i]; ch[i]=ch[ch.length-1-i]; ch[ch.length-1-i]=t; } nstr=new String(ch); if(nstr.equalsIgnoreCase(st)) System.out.println(st+" string is palindrome"); else System.out.println(st+" string is not palindrome"); } }
UTF-8
Java
567
java
StringPalindrome.java
Java
[]
null
[]
package strings; import java.util.Scanner; public class StringPalindrome { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String st=sc.nextLine(); String nstr=""; char ch[]=st.toCharArray(); for (int i = 0; i < ch.length/2; i++) { char t=ch[i]; ch[i]=ch[ch.length-1-i]; ch[ch.length-1-i]=t; } nstr=new String(ch); if(nstr.equalsIgnoreCase(st)) System.out.println(st+" string is palindrome"); else System.out.println(st+" string is not palindrome"); } }
567
0.650794
0.643739
26
20.807692
16.344887
54
false
false
0
0
0
0
0
0
2.115385
false
false
8
2ba9193a8b8865b35eeb0f6e3367a1b04e23a84c
24,635,932,433,957
468e04949d04ff74f3ef4ecc466bf21286f7b914
/GongYi/GongYi/src/com/ZXLimg/ItemAction.java
292370eaf8c842e43a86dce892bd30e77f9fbebf
[]
no_license
tmz8023/GonYi
https://github.com/tmz8023/GonYi
06113b1f175ff93430a156e69b8b8ed4ed592384
e0a1151e9012c9cfa7b595fa94d3494cc96edb86
refs/heads/master
2021-01-01T17:49:52.317000
2017-07-25T03:07:29
2017-07-25T03:07:29
98,168,488
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ZXLimg; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; public class ItemAction { SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dd=time.format(new Date()); dao da=new Impl(); imgInfo nn=new imgInfo(); ItemInfo itf; public ItemInfo getItf() { return itf; } public void setItf(ItemInfo itf) { this.itf = itf; } public String select(){ nn.setId(itf.getId()); nn.setName(itf.getName()); nn.setContent(itf.getContent()); nn.setImg(itf.getImg()); nn.setDate(dd); nn.setFinals(itf.getFinals()); nn.setImgId(itf.getImgId()); nn.setImgName(itf.getImgName()); List<imgInfo> li=da.select(); HttpSession se=ServletActionContext.getRequest().getSession(); se.setAttribute("kk", li); System.out.println("pp"); return "sel"; } }
UTF-8
Java
944
java
ItemAction.java
Java
[]
null
[]
package com.ZXLimg; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; public class ItemAction { SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dd=time.format(new Date()); dao da=new Impl(); imgInfo nn=new imgInfo(); ItemInfo itf; public ItemInfo getItf() { return itf; } public void setItf(ItemInfo itf) { this.itf = itf; } public String select(){ nn.setId(itf.getId()); nn.setName(itf.getName()); nn.setContent(itf.getContent()); nn.setImg(itf.getImg()); nn.setDate(dd); nn.setFinals(itf.getFinals()); nn.setImgId(itf.getImgId()); nn.setImgName(itf.getImgName()); List<imgInfo> li=da.select(); HttpSession se=ServletActionContext.getRequest().getSession(); se.setAttribute("kk", li); System.out.println("pp"); return "sel"; } }
944
0.695975
0.694915
51
17.509804
16.837601
67
false
false
0
0
0
0
0
0
1.529412
false
false
8
a39822e217e66f4e64134b5b79a5ee850560bbbb
11,123,965,324,479
646420561caa1955fba459a19f99635a634e79a6
/OCEJWSD/services/ServiceLocatorPattern/src/test/java/com/sydor/ocejwsd/service/locator/pattern/ServiceLocatorIT.java
729d149605023ea0447538cd7840efeb6e938fa7
[]
no_license
andrzejsydor/ocejwsd
https://github.com/andrzejsydor/ocejwsd
6798201fcb48103f799b5173d5e2389fbb081af8
07d3e217fca6481d6e0be2f901a3793fbb590f3c
refs/heads/master
2020-02-21T21:18:28.815000
2014-11-20T20:13:25
2014-11-20T20:13:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sydor.ocejwsd.service.locator.pattern; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import static org.junit.Assert.*; public class ServiceLocatorIT { @Test public void testGetService1() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { Class<String> stringClass = String.class; Constructor<String> constructor = stringClass.getConstructor(String.class); String jndiName = constructor.newInstance("Service1"); Service service = ServiceLocator.getService(jndiName); assertTrue(service instanceof Service1); } @Test public void testGetService2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { Class<?> stringClass = Class.forName("java.lang.String"); Constructor<String> stringConstructor = (Constructor<String>) stringClass.getConstructor(String.class); String jndiName = (String) stringConstructor.newInstance("Service2"); Service service = ServiceLocator.getService(jndiName); assertTrue(service instanceof Service2); } @Test public void returnNullWhenGetNonExistingService() { String jndiName = "none"; Service service = ServiceLocator.getService(jndiName); assertNull(service); } }
UTF-8
Java
1,546
java
ServiceLocatorIT.java
Java
[]
null
[]
package com.sydor.ocejwsd.service.locator.pattern; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import static org.junit.Assert.*; public class ServiceLocatorIT { @Test public void testGetService1() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { Class<String> stringClass = String.class; Constructor<String> constructor = stringClass.getConstructor(String.class); String jndiName = constructor.newInstance("Service1"); Service service = ServiceLocator.getService(jndiName); assertTrue(service instanceof Service1); } @Test public void testGetService2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { Class<?> stringClass = Class.forName("java.lang.String"); Constructor<String> stringConstructor = (Constructor<String>) stringClass.getConstructor(String.class); String jndiName = (String) stringConstructor.newInstance("Service2"); Service service = ServiceLocator.getService(jndiName); assertTrue(service instanceof Service2); } @Test public void returnNullWhenGetNonExistingService() { String jndiName = "none"; Service service = ServiceLocator.getService(jndiName); assertNull(service); } }
1,546
0.730919
0.727037
40
36.650002
43.355247
189
false
false
0
0
0
0
0
0
0.675
false
false
8
70d4d21005043057ca3e7e557c643f6863811546
17,935,783,473,613
22096407fd585e33edd8b3f516b625e7f9442e22
/Person/src/jp/co/internous/action/Test.java
5e66ee9a38638e49642e19b5e4b3c88319cc38db
[]
no_license
mi-ko-cute/java-object
https://github.com/mi-ko-cute/java-object
25b1b214032602cb9b6b6dc93786dc7a639d2466
257c1d2c1883d7c1b8e8ca83471f996ad2c6a778
refs/heads/master
2020-06-13T13:15:11.865000
2019-07-01T12:33:32
2019-07-01T12:33:32
194,667,761
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.co.internous.action; public class Test { public static void main(String[]args){ Person taro = new Person(); taro.name = "山田太郎"; taro.age = 20; taro.phoneNumber = "090-1111-1111"; taro.address = "kyoto"; System.out.println(taro.name); System.out.println(taro.age); System.out.println(taro.phoneNumber); System.out.println(taro.address); taro.talk(); taro.walk(); taro.run(); Person ziro = new Person(); ziro.name = "木村次郎"; ziro.age = 18; ziro.phoneNumber = "080-2222-2222"; ziro.address = "tokyo"; System.out.println(ziro.name); System.out.println(ziro.age); System.out.println(ziro.phoneNumber); System.out.println(ziro.address); ziro.talk(); ziro.walk(); ziro.run(); Person hanako = new Person(); hanako.name = "鈴木花子"; hanako.age = 16; hanako.phoneNumber = "080-3333-3333"; hanako.address = "hokkaido"; System.out.println(hanako.name); System.out.println(hanako.age); System.out.println(hanako.phoneNumber); System.out.println(hanako.address); hanako.talk(); hanako.walk(); hanako.run(); Person kazuki = new Person(); kazuki.name = "櫻井一毅"; kazuki.age = 25; kazuki.phoneNumber = "080-9999-9999"; kazuki.address = "USA"; System.out.println(kazuki.name); System.out.println(kazuki.age); System.out.println(kazuki.phoneNumber); System.out.println(kazuki.address); kazuki.talk(); kazuki.walk(); kazuki.run(); Robot aibo = new Robot(); aibo.name = "アイボ"; aibo.talk(); aibo.walk(); aibo.run(); Robot asimo = new Robot(); asimo.name = "アシモ"; asimo.talk(); asimo.walk(); asimo.run(); Robot pepper = new Robot(); pepper.name = "ペッパー君"; pepper.talk(); pepper.walk(); pepper.run(); } }
UTF-8
Java
1,783
java
Test.java
Java
[ { "context": "gs){\n\t\tPerson taro = new Person();\n\t\ttaro.name = \"山田太郎\";\n\t\ttaro.age = 20;\n\t\ttaro.phoneNumber = \"090-1111", "end": 142, "score": 0.9996187686920166, "start": 138, "tag": "NAME", "value": "山田太郎" }, { "context": "();\n\n\t\tPerson ziro = new Person();\n\t\tz...
null
[]
package jp.co.internous.action; public class Test { public static void main(String[]args){ Person taro = new Person(); taro.name = "山田太郎"; taro.age = 20; taro.phoneNumber = "090-1111-1111"; taro.address = "kyoto"; System.out.println(taro.name); System.out.println(taro.age); System.out.println(taro.phoneNumber); System.out.println(taro.address); taro.talk(); taro.walk(); taro.run(); Person ziro = new Person(); ziro.name = "木村次郎"; ziro.age = 18; ziro.phoneNumber = "080-2222-2222"; ziro.address = "tokyo"; System.out.println(ziro.name); System.out.println(ziro.age); System.out.println(ziro.phoneNumber); System.out.println(ziro.address); ziro.talk(); ziro.walk(); ziro.run(); Person hanako = new Person(); hanako.name = "鈴木花子"; hanako.age = 16; hanako.phoneNumber = "080-3333-3333"; hanako.address = "hokkaido"; System.out.println(hanako.name); System.out.println(hanako.age); System.out.println(hanako.phoneNumber); System.out.println(hanako.address); hanako.talk(); hanako.walk(); hanako.run(); Person kazuki = new Person(); kazuki.name = "櫻井一毅"; kazuki.age = 25; kazuki.phoneNumber = "080-9999-9999"; kazuki.address = "USA"; System.out.println(kazuki.name); System.out.println(kazuki.age); System.out.println(kazuki.phoneNumber); System.out.println(kazuki.address); kazuki.talk(); kazuki.walk(); kazuki.run(); Robot aibo = new Robot(); aibo.name = "アイボ"; aibo.talk(); aibo.walk(); aibo.run(); Robot asimo = new Robot(); asimo.name = "アシモ"; asimo.talk(); asimo.walk(); asimo.run(); Robot pepper = new Robot(); pepper.name = "ペッパー君"; pepper.talk(); pepper.walk(); pepper.run(); } }
1,783
0.653557
0.623482
83
19.831326
12.907287
41
false
false
0
0
0
0
0
0
2.313253
false
false
8
340a89613ab7bf0261ebda8b130bd7fed380a8d3
29,334,626,651,850
8bf189d33021429900b9093a0790495c932f541e
/cookbook/src/modelo/Receita.java
41ace2896415384f5f51fe3d70fd510e40ea4ffe
[]
no_license
fcabral1980/cookbook
https://github.com/fcabral1980/cookbook
e685a782682748afff8ed7f716e912fe5c2b5c01
6816f1e8e159657e7d5bfc099279dd973449769a
refs/heads/master
2021-07-03T03:05:47.864000
2017-09-21T23:08:58
2017-09-21T23:08:58
104,275,214
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modelo; import java.util.Objects; public class Receita { private Integer id; private String nome; private String ingredientes; private String preparo; private String ModoServir; private Categoria categoria; public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria c) { this.categoria = c; c.setReceita(this); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getIngredientes() { return ingredientes; } public void setIngredientes(String ingredientes) { this.ingredientes = ingredientes; } public String getPreparo() { return preparo; } public void setPreparo(String preparo) { this.preparo = preparo; } public String getModoServir() { return ModoServir; } public void setModoServir(String ModoServir) { this.ModoServir = ModoServir; } @Override public int hashCode() { int hash = 3; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Receita other = (Receita) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
UTF-8
Java
1,766
java
Receita.java
Java
[]
null
[]
package modelo; import java.util.Objects; public class Receita { private Integer id; private String nome; private String ingredientes; private String preparo; private String ModoServir; private Categoria categoria; public Categoria getCategoria() { return categoria; } public void setCategoria(Categoria c) { this.categoria = c; c.setReceita(this); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getIngredientes() { return ingredientes; } public void setIngredientes(String ingredientes) { this.ingredientes = ingredientes; } public String getPreparo() { return preparo; } public void setPreparo(String preparo) { this.preparo = preparo; } public String getModoServir() { return ModoServir; } public void setModoServir(String ModoServir) { this.ModoServir = ModoServir; } @Override public int hashCode() { int hash = 3; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Receita other = (Receita) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } }
1,766
0.53171
0.531144
87
18.298851
15.104323
54
false
false
0
0
0
0
0
0
0.344828
false
false
8
6b5ce46a30a4dd12613e47846e7bde5aeb06f8b0
37,890,201,509,549
47513f75a72077baf0a12b0a4d9d83b9cab9824c
/BlueJ/Lessons/Lesson5/PracticeProgram.java
c49597fcf7000b3e746df05c2affbe0e8ca8bc65
[]
no_license
calvinrboyce/BlueJ
https://github.com/calvinrboyce/BlueJ
0fd10e286827e8e8c237dcd91584d442453214f5
0cb23531e75ee6734d2dc4d30f93b37a96f1f653
refs/heads/master
2021-08-23T10:46:52.035000
2017-12-04T15:40:44
2017-12-04T15:40:44
113,060,645
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Calvin Boyce #1 9/26/17 * Lesson 5 practice program */ class PracticeProgram { public static void main (String args[]) { double d = (double)5/4; //same as 5.0/4(double) only applies to the 5 System.out.println(d); //1.0 int j = 5; int k = 4; d = (double)(j/k); //(j/k) is in its own little world and performs //a double, 1.0 System.out.println(d); //1.0 }//end of main() }//end of class
UTF-8
Java
459
java
PracticeProgram.java
Java
[ { "context": "/* Calvin Boyce #1 9/26/17\n * Lesson 5 practice program\n */\nclass", "end": 15, "score": 0.9998903274536133, "start": 3, "tag": "NAME", "value": "Calvin Boyce" } ]
null
[]
/* <NAME> #1 9/26/17 * Lesson 5 practice program */ class PracticeProgram { public static void main (String args[]) { double d = (double)5/4; //same as 5.0/4(double) only applies to the 5 System.out.println(d); //1.0 int j = 5; int k = 4; d = (double)(j/k); //(j/k) is in its own little world and performs //a double, 1.0 System.out.println(d); //1.0 }//end of main() }//end of class
453
0.555556
0.509804
16
27.75
21.305809
77
false
false
0
0
0
0
0
0
0.4375
false
false
8
622ca5d6d072b8434b16d0afebe5b0b35ddeced5
17,635,135,771,544
94d229cb222f14e77e4e8458a04e7addaa6a165c
/src/Cell.java
0ce0e051aaa12875372f2a700ee525db6fd2bd03
[]
no_license
kurkjian/city-builder
https://github.com/kurkjian/city-builder
ecc827ef302f504079b847c1b74b0dd59185e958
66b93d3ab9f0ea3a469667a04ed94d80a49fd067
refs/heads/master
2020-03-11T22:22:05.925000
2018-06-12T19:59:58
2018-06-12T19:59:58
130,290,464
0
2
null
false
2018-06-12T19:59:59
2018-04-20T01:13:24
2018-04-24T02:44:33
2018-06-12T19:59:59
597
0
2
2
Java
false
null
import mayflower.*; import java.awt.Image; import java.awt.Graphics; import java.util.*; public class Cell extends Actor { private int x; private int y; private int width; private int height; private Image image; public Cell() { } public Cell(int a, int b, int w, int h) { x = a; y = b; width = w; height = h; } public void act() { } public int getx(){ return x; } public int gety(){ return y; } public void setx(int x) { this.x = x; } public void sety(int y) { this.y = y; } public List<Cell> getNeighbors(Level level, int x, int y) { Cell[][] map = level.getMap().getMap(); List<Cell> ret = new ArrayList<>(); if(x - 1 > -1) { ret.add(map[x-1][y]); } if(x + 1 < map.length) { ret.add(map[x+1][y]); } if(y - 1 > -1) { ret.add(map[x][y-1]); } if(y + 1 < map[0].length) { ret.add(map[x][y+1]); } return ret; } }
UTF-8
Java
1,159
java
Cell.java
Java
[]
null
[]
import mayflower.*; import java.awt.Image; import java.awt.Graphics; import java.util.*; public class Cell extends Actor { private int x; private int y; private int width; private int height; private Image image; public Cell() { } public Cell(int a, int b, int w, int h) { x = a; y = b; width = w; height = h; } public void act() { } public int getx(){ return x; } public int gety(){ return y; } public void setx(int x) { this.x = x; } public void sety(int y) { this.y = y; } public List<Cell> getNeighbors(Level level, int x, int y) { Cell[][] map = level.getMap().getMap(); List<Cell> ret = new ArrayList<>(); if(x - 1 > -1) { ret.add(map[x-1][y]); } if(x + 1 < map.length) { ret.add(map[x+1][y]); } if(y - 1 > -1) { ret.add(map[x][y-1]); } if(y + 1 < map[0].length) { ret.add(map[x][y+1]); } return ret; } }
1,159
0.434858
0.425367
73
14.890411
13.25675
61
false
false
0
0
0
0
0
0
0.39726
false
false
8
b55911e3c42c8400549cb9a095dfdb9ee0e12d01
38,886,633,931,858
188b08dde7ce75b93d7cf6de28dbadea8e96bff9
/Algorithms/src/com/leetcode/prep/LeetCode146.java
27c357ba05ba652fd2a171cf07efa460a48335f8
[]
no_license
uttej-reddy/DataStructures-And-Algorithms
https://github.com/uttej-reddy/DataStructures-And-Algorithms
eb1f130dbd51fdecfd95b80f08984f34dc903b36
6c7aa8fb65de4d93a1bdfbe62b84dc92af3664b3
refs/heads/master
2021-05-12T04:33:50.492000
2020-05-29T16:45:17
2020-05-29T16:45:17
117,165,475
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leetcode.prep; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; public class LeetCode146 { public static void main(String[] args) { LRUCache lru = new LRUCache(2); lru.put(1, 1); lru.put(2,2); System.out.println(lru.get(1)); // returns 1 lru.put(3, 3); // evicts key 2 System.out.println(lru.get(2)); // returns -1 (not found) lru.put(4, 4); // evicts key 1 System.out.println(lru.get(1)); // returns -1 (not found) System.out.println(lru.get(3)); // returns 3 System.out.println(lru.get(4)); } static class LRUCache { int capacity; Queue<Integer> q = new LinkedList<Integer>(); Map<Integer,Integer> m = new HashMap<Integer,Integer>(); public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { int l = q.size(); while(l>0){ int pop = q.poll(); l--; if(pop != key) q.add(pop); } q.add(key); if(m.containsKey(key)) return m.get(key); else return -1; } public void put(int key, int value) { if(m.size() < capacity) m.put(key,value); else{ int pop = q.poll(); m.remove(pop); m.put(key,value); } q.add(key); } } }
UTF-8
Java
1,508
java
LeetCode146.java
Java
[]
null
[]
package com.leetcode.prep; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; public class LeetCode146 { public static void main(String[] args) { LRUCache lru = new LRUCache(2); lru.put(1, 1); lru.put(2,2); System.out.println(lru.get(1)); // returns 1 lru.put(3, 3); // evicts key 2 System.out.println(lru.get(2)); // returns -1 (not found) lru.put(4, 4); // evicts key 1 System.out.println(lru.get(1)); // returns -1 (not found) System.out.println(lru.get(3)); // returns 3 System.out.println(lru.get(4)); } static class LRUCache { int capacity; Queue<Integer> q = new LinkedList<Integer>(); Map<Integer,Integer> m = new HashMap<Integer,Integer>(); public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { int l = q.size(); while(l>0){ int pop = q.poll(); l--; if(pop != key) q.add(pop); } q.add(key); if(m.containsKey(key)) return m.get(key); else return -1; } public void put(int key, int value) { if(m.size() < capacity) m.put(key,value); else{ int pop = q.poll(); m.remove(pop); m.put(key,value); } q.add(key); } } }
1,508
0.497347
0.480769
65
22.200001
16.950788
65
false
false
0
0
0
0
0
0
1.569231
false
false
8
6bab65113306a5d107fd9d261cbb4b5fb3a80e25
34,900,904,295,232
db77908c40c076bb713c1b00fd633457658964a3
/common/ifs-application-commons/src/test/java/org/innovateuk/ifs/application/readonly/populator/ApplicationReadOnlyViewModelPopulatorTest.java
2f8bd5201dd1fe5d3651c8e2e6c020ec01a95e05
[ "MIT" ]
permissive
InnovateUKGitHub/innovation-funding-service
https://github.com/InnovateUKGitHub/innovation-funding-service
e3807613fd3c398931918c6cc773d13874331cdc
964969b6dc9c78750738ef683076558cc897c1c8
refs/heads/development
2023-08-04T04:04:05.501000
2022-11-11T14:48:30
2022-11-11T14:48:30
87,336,871
30
20
MIT
false
2023-07-19T21:23:46
2017-04-05T17:20:38
2023-03-15T17:10:05
2023-07-19T21:23:46
784,740
24
12
16
Java
false
false
package org.innovateuk.ifs.application.readonly.populator; import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData; import org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationQuestionReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationSectionReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.FinanceReadOnlyViewModel; import org.innovateuk.ifs.application.resource.*; import org.innovateuk.ifs.application.service.ApplicationRestService; import org.innovateuk.ifs.application.service.QuestionRestService; import org.innovateuk.ifs.application.service.QuestionStatusRestService; import org.innovateuk.ifs.application.service.SectionRestService; import org.innovateuk.ifs.assessment.resource.ApplicationAssessmentResource; import org.innovateuk.ifs.assessment.service.AssessorFormInputResponseRestService; import org.innovateuk.ifs.async.generation.AsyncFuturesGenerator; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.CompetitionEoiEvidenceConfigResource; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionTypeEnum; import org.innovateuk.ifs.competition.resource.GrantTermsAndConditionsResource; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.form.resource.FormInputResource; import org.innovateuk.ifs.form.resource.QuestionResource; import org.innovateuk.ifs.form.resource.SectionResource; import org.innovateuk.ifs.form.resource.SectionType; import org.innovateuk.ifs.form.service.FormInputResponseRestService; import org.innovateuk.ifs.form.service.FormInputRestService; import org.innovateuk.ifs.horizon.resource.ApplicationHorizonWorkProgrammeResource; import org.innovateuk.ifs.horizon.resource.HorizonWorkProgrammeResource; import org.innovateuk.ifs.horizon.service.HorizonWorkProgrammeRestService; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.question.resource.QuestionSetupType; import org.innovateuk.ifs.supporter.resource.SupporterAssignmentResource; import org.innovateuk.ifs.supporter.resource.SupporterState; import org.innovateuk.ifs.supporter.service.SupporterAssignmentRestService; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.innovateuk.ifs.user.resource.Role; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.OrganisationRestService; import org.innovateuk.ifs.user.service.ProcessRoleRestService; import org.innovateuk.ifs.workflow.resource.State; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.*; import java.util.stream.Collectors; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.innovateuk.ifs.AsyncTestExpectationHelper.setupAsyncExpectations; import static org.innovateuk.ifs.application.builder.ApplicationAssessmentResourceBuilder.newApplicationAssessmentResource; import static org.innovateuk.ifs.application.builder.ApplicationExpressionOfInterestConfigResourceBuilder.newApplicationExpressionOfInterestConfigResource; import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static org.innovateuk.ifs.application.builder.FormInputResponseResourceBuilder.newFormInputResponseResource; import static org.innovateuk.ifs.application.builder.QuestionStatusResourceBuilder.newQuestionStatusResource; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.competition.builder.GrantTermsAndConditionsResourceBuilder.newGrantTermsAndConditionsResource; import static org.innovateuk.ifs.form.builder.FormInputResourceBuilder.newFormInputResource; import static org.innovateuk.ifs.form.builder.QuestionResourceBuilder.newQuestionResource; import static org.innovateuk.ifs.form.builder.SectionResourceBuilder.newSectionResource; import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource; import static org.innovateuk.ifs.supporter.builder.SupporterAssignmentResourceBuilder.newSupporterAssignmentResource; import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static org.springframework.test.util.ReflectionTestUtils.setField; @RunWith(MockitoJUnitRunner.Silent.class) public class ApplicationReadOnlyViewModelPopulatorTest { @InjectMocks private ApplicationReadOnlyViewModelPopulator populator; @Mock private ApplicationRestService applicationRestService; @Mock private CompetitionRestService competitionRestService; @Mock private FormInputRestService formInputRestService; @Mock private FormInputResponseRestService formInputResponseRestService; @Mock private SectionRestService sectionRestService; @Mock private QuestionRestService questionRestService; @Mock private FinanceReadOnlyViewModelPopulator financeSummaryViewModelPopulator; @Mock private QuestionStatusRestService questionStatusRestService; @Mock private OrganisationRestService organisationRestService; @Mock private List<QuestionReadOnlyViewModelPopulator<?>> mocklist; @Mock private ProcessRoleRestService processRoleRestService; @Mock private AssessorFormInputResponseRestService assessorFormInputResponseRestService; @Mock private AsyncFuturesGenerator futuresGeneratorMock; @Mock private SupporterAssignmentRestService supporterAssignmentRestService; @Mock private HorizonWorkProgrammeRestService horizonWorkProgrammeRestService; @Mock private EoiEvidenceReadOnlyViewModelPopulator eoiEvidenceReadOnlyViewModelPopulator; private final long applicationId = 1L; private final long assessmentId = 2L; private final long eoiApplicationId = 3L; private final QuestionReadOnlyViewModelPopulator mockPopulator = mock(QuestionReadOnlyViewModelPopulator.class); private List<FormInputResource> formInputs = new ArrayList<>(); private List<FormInputResponseResource> responses = new ArrayList<>(); private List<ApplicationHorizonWorkProgrammeResource> workProgrammeFuture = new ArrayList<>(); @Before public void setupExpectations() { setupAsyncExpectations(futuresGeneratorMock); formInputs = newFormInputResource().withQuestion(2L).build(1); responses = newFormInputResponseResource().withFormInputs(formInputs.get(0).getId()).build(1); workProgrammeFuture = singletonList(new ApplicationHorizonWorkProgrammeResource()); } @Test public void populate() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .build(3); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.getQuestions().iterator().next(), expectedRowModel); ApplicationSectionReadOnlyViewModel financeSection = iterator.next(); assertEquals(financeSection.getName(), "Finance section"); assertEquals(financeSection.getQuestions().iterator().next(), expectedFinanceSummary); assertFalse(viewModel.isKtpCompetition()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateKtp() { OrganisationResource organisation = newOrganisationResource().build(); UserResource user = newUserResource() .withRolesGlobal(asList(Role.KNOWLEDGE_TRANSFER_ADVISER, Role.ASSESSOR)) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeAllAssessorFeedback(true) .setIncludeAllSupporterFeedback(true); setField(populator, "populatorMap", asMap(QuestionSetupType.KTP_ASSESSMENT, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Knowledge Transfer Partnership (KTP)") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.KTP) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withLeadOrganisationId(organisation.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.KTP_ASSESSMENT) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); List<SectionResource> sections = newSectionResource() .withName("Score assessment") .withChildSections(Collections.emptyList()) .withQuestions(questions.stream() .filter(questionResource -> questionResource.getQuestionSetupType() == QuestionSetupType.KTP_ASSESSMENT) .map(QuestionResource::getId).collect(Collectors.toList())) .withType(SectionType.KTP_ASSESSMENT) .build(1); ProcessRoleResource processRole = newProcessRoleResource() .withRole(ProcessRoleType.KNOWLEDGE_TRANSFER_ADVISER, ProcessRoleType.ASSESSOR) .withUser(user) .build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .withOverallFeedback("Overall Feedback") .build(); List<SupporterAssignmentResource> supporterResponseFuture = newSupporterAssignmentResource() .withAssignmentId(1, 2, 3, 4, 5) .withState(SupporterState.ACCEPTED, SupporterState.ACCEPTED, SupporterState.REJECTED, SupporterState.REJECTED, SupporterState.CREATED) .withComments("accepted one", "accepted two", "rejected one", "rejected two", "created") .withUserSimpleOrganisation("Org A", "Org B", "Org C", "Org D", "Org E") .build(5); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), supporterResponseFuture, Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(supporterAssignmentRestService.getAssignmentsByApplicationId(applicationId)).thenReturn(restSuccess(supporterResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(settings, viewModel.getSettings()); assertEquals(viewModel.getSections().size(), 1); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel scoreAssessmentSection = iterator.next(); assertEquals(scoreAssessmentSection.getName(), "Score assessment"); assertEquals(scoreAssessmentSection.getQuestions().iterator().next(), expectedRowModel); assertTrue(viewModel.isShouldDisplayKtpApplicationFeedback()); assertNotNull(viewModel.getOverallFeedbacks()); assertEquals(1, viewModel.getOverallFeedbacks().size()); assertEquals("Overall Feedback", viewModel.getOverallFeedbacks().get(0)); assertNotNull(viewModel.getAssignments()); assertEquals(3, viewModel.getAssignments().size()); assertNotNull(viewModel.getAssignments().get("accepted")); assertEquals(2, viewModel.getAssignments().get("accepted").size()); assertNotNull(viewModel.getAssignments().get("accepted").get(0)); assertEquals("accepted one", viewModel.getAssignments().get("accepted").get(0).getComments()); assertEquals("Org A", viewModel.getAssignments().get("accepted").get(0).getUserSimpleOrganisation()); assertNotNull(viewModel.getAssignments().get("accepted").get(1)); assertEquals("accepted two", viewModel.getAssignments().get("accepted").get(1).getComments()); assertEquals("Org B", viewModel.getAssignments().get("accepted").get(1).getUserSimpleOrganisation()); assertTrue(viewModel.isAccepted()); assertEquals(2, viewModel.getAcceptedCount()); assertNotNull(viewModel.getAssignments().get("rejected")); assertEquals(2, viewModel.getAssignments().get("rejected").size()); assertNotNull(viewModel.getAssignments().get("rejected").get(0)); assertEquals("rejected one", viewModel.getAssignments().get("rejected").get(0).getComments()); assertEquals("Org C", viewModel.getAssignments().get("rejected").get(0).getUserSimpleOrganisation()); assertNotNull(viewModel.getAssignments().get("rejected").get(1)); assertEquals("rejected two", viewModel.getAssignments().get("rejected").get(1).getComments()); assertEquals("Org D", viewModel.getAssignments().get("rejected").get(1).getUserSimpleOrganisation()); assertTrue(viewModel.isDeclined()); assertEquals(2, viewModel.getDeclinedCount()); assertNotNull(viewModel.getAssignments().get("created")); assertEquals(1, viewModel.getAssignments().get("created").size()); assertNotNull(viewModel.getAssignments().get("created").get(0)); assertEquals("created", viewModel.getAssignments().get("created").get(0).getComments()); assertEquals("Org E", viewModel.getAssignments().get("created").get(0).getUserSimpleOrganisation()); assertTrue(viewModel.isPending()); assertEquals(1, viewModel.getPendingCount()); assertTrue(viewModel.isKtpCompetition()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateHecp() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true); setField(populator, "populatorMap", asMap(QuestionSetupType.HORIZON_WORK_PROGRAMME, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Horizon Europe Guarantee") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.HECP) .withTermsAndConditions(grantTermsAndConditionsResource) .withCompetitionTypeEnum(CompetitionTypeEnum.HORIZON_EUROPE_GUARANTEE) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.HORIZON_WORK_PROGRAMME) .withName("Work programme") .withShortName("Work programme") .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section") .withChildSections(Collections.emptyList(), Collections.singletonList(1L)) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList()) .withType(SectionType.PROJECT_DETAILS, SectionType.FINANCE) .build(2); HorizonWorkProgrammeResource workProgramme = new HorizonWorkProgrammeResource(6, "CL6", null, true); HorizonWorkProgrammeResource callerId = new HorizonWorkProgrammeResource(6, "CL6", workProgramme, true); workProgrammeFuture = asList(new ApplicationHorizonWorkProgrammeResource(applicationId, workProgramme), new ApplicationHorizonWorkProgrammeResource(applicationId, callerId)); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, emptyList(), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.getQuestions().iterator().next(), expectedRowModel); assertEquals(workProgrammeFuture, expectedData.getApplicationHorizonWorkProgrammeResource().get()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateEOI() { String title = "Eoi Evidence"; String name = "eoi_evidence.pdf"; int filesizeBytes = 4380; String mediaType = ".pdf"; long fileEntryId = 1234L; UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationExpressionOfInterestConfigResource applicationExpressionOfInterestConfig = newApplicationExpressionOfInterestConfigResource() .withEnabledForExpressionOfInterest(true) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeQuestionNumber(false); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionEoiEvidenceConfigResource competitionEoiEvidenceConfigResource = CompetitionEoiEvidenceConfigResource.builder() .evidenceRequired(true) .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .withCompetitionEoiEvidenceConfigResource(competitionEoiEvidenceConfigResource) .build(); ApplicationEoiEvidenceResponseResource applicationEoiEvidenceResponseResource = ApplicationEoiEvidenceResponseResource.builder() .fileState(State.SUBMITTED) .build(); OrganisationResource organisation = newOrganisationResource().build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withApplicationExpressionOfInterestConfigResource(applicationExpressionOfInterestConfig) .withApplicationState(ApplicationState.SUBMITTED) .withSubmittedDate(ZonedDateTime.now()) .withApplicationEoiEvidenceResponseResource(applicationEoiEvidenceResponseResource) .withLeadOrganisationId(organisation.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .withEnabledForPreRegistration(false) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .withEnabledForPreRegistration(false) .build(3); ProcessRoleResource processRole = newProcessRoleResource() .withRole(ProcessRoleType.LEADAPPLICANT) .withUser(user) .withOrganisation(organisation.getId()) .build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); EoiEvidenceReadOnlyViewModel eoiEvidenceReadOnlyViewModel = EoiEvidenceReadOnlyViewModel.builder() .applicationId(applicationId) .expressionOfInterestApplication(true) .title(title) .build(); eoiEvidenceReadOnlyViewModel.setName(name); eoiEvidenceReadOnlyViewModel.setFilesizeBytes(filesizeBytes); eoiEvidenceReadOnlyViewModel.setMediaType(mediaType); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(eoiEvidenceReadOnlyViewModelPopulator.populate(application)).thenReturn(eoiEvidenceReadOnlyViewModel); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); assertFalse(viewModel.isEoiFullApplication()); assertTrue(viewModel.isExpressionOfInterestApplication()); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.isVisible(), false); assertEquals(sectionWithQuestion.getQuestions().size(), 0); ApplicationSectionReadOnlyViewModel financeSection = iterator.next(); assertEquals(financeSection.getName(), "Finance section"); assertEquals(financeSection.isVisible(), false); assertEquals(financeSection.getQuestions().iterator().next(), expectedFinanceSummary); EoiEvidenceReadOnlyViewModel eoiViewModel = viewModel.getEoiEvidenceReadOnlyViewModel(); assertNotNull(eoiViewModel); assertEquals(applicationId, eoiViewModel.getApplicationId().longValue()); assertEquals(title, eoiViewModel.getTitle()); assertEquals(name, eoiViewModel.getName()); assertEquals(filesizeBytes, eoiViewModel.getFilesizeBytes()); assertEquals(mediaType, eoiViewModel.getMediaType()); } @Test public void populateEOIFullApplication() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationExpressionOfInterestConfigResource applicationExpressionOfInterestConfig = newApplicationExpressionOfInterestConfigResource() .withEnabledForExpressionOfInterest(false) .withEoiApplicationId(eoiApplicationId) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeQuestionNumber(false); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withApplicationExpressionOfInterestConfigResource(applicationExpressionOfInterestConfig) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .withEnabledForPreRegistration(false) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .withEnabledForPreRegistration(false) .build(3); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertTrue(viewModel.isEoiFullApplication()); assertFalse(viewModel.isExpressionOfInterestApplication()); } }
UTF-8
Java
42,249
java
ApplicationReadOnlyViewModelPopulatorTest.java
Java
[ { "context": "RoleType.LEADAPPLICANT)\n .withUser(user)\n .withOrganisation(organisation.g", "end": 31832, "score": 0.8505504727363586, "start": 31828, "tag": "USERNAME", "value": "user" } ]
null
[]
package org.innovateuk.ifs.application.readonly.populator; import org.innovateuk.ifs.application.readonly.ApplicationReadOnlyData; import org.innovateuk.ifs.application.readonly.ApplicationReadOnlySettings; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationQuestionReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.ApplicationSectionReadOnlyViewModel; import org.innovateuk.ifs.application.readonly.viewmodel.FinanceReadOnlyViewModel; import org.innovateuk.ifs.application.resource.*; import org.innovateuk.ifs.application.service.ApplicationRestService; import org.innovateuk.ifs.application.service.QuestionRestService; import org.innovateuk.ifs.application.service.QuestionStatusRestService; import org.innovateuk.ifs.application.service.SectionRestService; import org.innovateuk.ifs.assessment.resource.ApplicationAssessmentResource; import org.innovateuk.ifs.assessment.service.AssessorFormInputResponseRestService; import org.innovateuk.ifs.async.generation.AsyncFuturesGenerator; import org.innovateuk.ifs.competition.publiccontent.resource.FundingType; import org.innovateuk.ifs.competition.resource.CompetitionEoiEvidenceConfigResource; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionTypeEnum; import org.innovateuk.ifs.competition.resource.GrantTermsAndConditionsResource; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.form.resource.FormInputResource; import org.innovateuk.ifs.form.resource.QuestionResource; import org.innovateuk.ifs.form.resource.SectionResource; import org.innovateuk.ifs.form.resource.SectionType; import org.innovateuk.ifs.form.service.FormInputResponseRestService; import org.innovateuk.ifs.form.service.FormInputRestService; import org.innovateuk.ifs.horizon.resource.ApplicationHorizonWorkProgrammeResource; import org.innovateuk.ifs.horizon.resource.HorizonWorkProgrammeResource; import org.innovateuk.ifs.horizon.service.HorizonWorkProgrammeRestService; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.question.resource.QuestionSetupType; import org.innovateuk.ifs.supporter.resource.SupporterAssignmentResource; import org.innovateuk.ifs.supporter.resource.SupporterState; import org.innovateuk.ifs.supporter.service.SupporterAssignmentRestService; import org.innovateuk.ifs.user.resource.ProcessRoleResource; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.innovateuk.ifs.user.resource.Role; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.OrganisationRestService; import org.innovateuk.ifs.user.service.ProcessRoleRestService; import org.innovateuk.ifs.workflow.resource.State; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.util.*; import java.util.stream.Collectors; import static com.google.common.collect.Lists.newArrayList; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.innovateuk.ifs.AsyncTestExpectationHelper.setupAsyncExpectations; import static org.innovateuk.ifs.application.builder.ApplicationAssessmentResourceBuilder.newApplicationAssessmentResource; import static org.innovateuk.ifs.application.builder.ApplicationExpressionOfInterestConfigResourceBuilder.newApplicationExpressionOfInterestConfigResource; import static org.innovateuk.ifs.application.builder.ApplicationResourceBuilder.newApplicationResource; import static org.innovateuk.ifs.application.builder.FormInputResponseResourceBuilder.newFormInputResponseResource; import static org.innovateuk.ifs.application.builder.QuestionStatusResourceBuilder.newQuestionStatusResource; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; import static org.innovateuk.ifs.competition.builder.GrantTermsAndConditionsResourceBuilder.newGrantTermsAndConditionsResource; import static org.innovateuk.ifs.form.builder.FormInputResourceBuilder.newFormInputResource; import static org.innovateuk.ifs.form.builder.QuestionResourceBuilder.newQuestionResource; import static org.innovateuk.ifs.form.builder.SectionResourceBuilder.newSectionResource; import static org.innovateuk.ifs.organisation.builder.OrganisationResourceBuilder.newOrganisationResource; import static org.innovateuk.ifs.supporter.builder.SupporterAssignmentResourceBuilder.newSupporterAssignmentResource; import static org.innovateuk.ifs.user.builder.ProcessRoleResourceBuilder.newProcessRoleResource; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static org.springframework.test.util.ReflectionTestUtils.setField; @RunWith(MockitoJUnitRunner.Silent.class) public class ApplicationReadOnlyViewModelPopulatorTest { @InjectMocks private ApplicationReadOnlyViewModelPopulator populator; @Mock private ApplicationRestService applicationRestService; @Mock private CompetitionRestService competitionRestService; @Mock private FormInputRestService formInputRestService; @Mock private FormInputResponseRestService formInputResponseRestService; @Mock private SectionRestService sectionRestService; @Mock private QuestionRestService questionRestService; @Mock private FinanceReadOnlyViewModelPopulator financeSummaryViewModelPopulator; @Mock private QuestionStatusRestService questionStatusRestService; @Mock private OrganisationRestService organisationRestService; @Mock private List<QuestionReadOnlyViewModelPopulator<?>> mocklist; @Mock private ProcessRoleRestService processRoleRestService; @Mock private AssessorFormInputResponseRestService assessorFormInputResponseRestService; @Mock private AsyncFuturesGenerator futuresGeneratorMock; @Mock private SupporterAssignmentRestService supporterAssignmentRestService; @Mock private HorizonWorkProgrammeRestService horizonWorkProgrammeRestService; @Mock private EoiEvidenceReadOnlyViewModelPopulator eoiEvidenceReadOnlyViewModelPopulator; private final long applicationId = 1L; private final long assessmentId = 2L; private final long eoiApplicationId = 3L; private final QuestionReadOnlyViewModelPopulator mockPopulator = mock(QuestionReadOnlyViewModelPopulator.class); private List<FormInputResource> formInputs = new ArrayList<>(); private List<FormInputResponseResource> responses = new ArrayList<>(); private List<ApplicationHorizonWorkProgrammeResource> workProgrammeFuture = new ArrayList<>(); @Before public void setupExpectations() { setupAsyncExpectations(futuresGeneratorMock); formInputs = newFormInputResource().withQuestion(2L).build(1); responses = newFormInputResponseResource().withFormInputs(formInputs.get(0).getId()).build(1); workProgrammeFuture = singletonList(new ApplicationHorizonWorkProgrammeResource()); } @Test public void populate() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .build(3); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.getQuestions().iterator().next(), expectedRowModel); ApplicationSectionReadOnlyViewModel financeSection = iterator.next(); assertEquals(financeSection.getName(), "Finance section"); assertEquals(financeSection.getQuestions().iterator().next(), expectedFinanceSummary); assertFalse(viewModel.isKtpCompetition()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateKtp() { OrganisationResource organisation = newOrganisationResource().build(); UserResource user = newUserResource() .withRolesGlobal(asList(Role.KNOWLEDGE_TRANSFER_ADVISER, Role.ASSESSOR)) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeAllAssessorFeedback(true) .setIncludeAllSupporterFeedback(true); setField(populator, "populatorMap", asMap(QuestionSetupType.KTP_ASSESSMENT, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Knowledge Transfer Partnership (KTP)") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.KTP) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withLeadOrganisationId(organisation.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.KTP_ASSESSMENT) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); List<SectionResource> sections = newSectionResource() .withName("Score assessment") .withChildSections(Collections.emptyList()) .withQuestions(questions.stream() .filter(questionResource -> questionResource.getQuestionSetupType() == QuestionSetupType.KTP_ASSESSMENT) .map(QuestionResource::getId).collect(Collectors.toList())) .withType(SectionType.KTP_ASSESSMENT) .build(1); ProcessRoleResource processRole = newProcessRoleResource() .withRole(ProcessRoleType.KNOWLEDGE_TRANSFER_ADVISER, ProcessRoleType.ASSESSOR) .withUser(user) .build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .withOverallFeedback("Overall Feedback") .build(); List<SupporterAssignmentResource> supporterResponseFuture = newSupporterAssignmentResource() .withAssignmentId(1, 2, 3, 4, 5) .withState(SupporterState.ACCEPTED, SupporterState.ACCEPTED, SupporterState.REJECTED, SupporterState.REJECTED, SupporterState.CREATED) .withComments("accepted one", "accepted two", "rejected one", "rejected two", "created") .withUserSimpleOrganisation("Org A", "Org B", "Org C", "Org D", "Org E") .build(5); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), supporterResponseFuture, Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(supporterAssignmentRestService.getAssignmentsByApplicationId(applicationId)).thenReturn(restSuccess(supporterResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(settings, viewModel.getSettings()); assertEquals(viewModel.getSections().size(), 1); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel scoreAssessmentSection = iterator.next(); assertEquals(scoreAssessmentSection.getName(), "Score assessment"); assertEquals(scoreAssessmentSection.getQuestions().iterator().next(), expectedRowModel); assertTrue(viewModel.isShouldDisplayKtpApplicationFeedback()); assertNotNull(viewModel.getOverallFeedbacks()); assertEquals(1, viewModel.getOverallFeedbacks().size()); assertEquals("Overall Feedback", viewModel.getOverallFeedbacks().get(0)); assertNotNull(viewModel.getAssignments()); assertEquals(3, viewModel.getAssignments().size()); assertNotNull(viewModel.getAssignments().get("accepted")); assertEquals(2, viewModel.getAssignments().get("accepted").size()); assertNotNull(viewModel.getAssignments().get("accepted").get(0)); assertEquals("accepted one", viewModel.getAssignments().get("accepted").get(0).getComments()); assertEquals("Org A", viewModel.getAssignments().get("accepted").get(0).getUserSimpleOrganisation()); assertNotNull(viewModel.getAssignments().get("accepted").get(1)); assertEquals("accepted two", viewModel.getAssignments().get("accepted").get(1).getComments()); assertEquals("Org B", viewModel.getAssignments().get("accepted").get(1).getUserSimpleOrganisation()); assertTrue(viewModel.isAccepted()); assertEquals(2, viewModel.getAcceptedCount()); assertNotNull(viewModel.getAssignments().get("rejected")); assertEquals(2, viewModel.getAssignments().get("rejected").size()); assertNotNull(viewModel.getAssignments().get("rejected").get(0)); assertEquals("rejected one", viewModel.getAssignments().get("rejected").get(0).getComments()); assertEquals("Org C", viewModel.getAssignments().get("rejected").get(0).getUserSimpleOrganisation()); assertNotNull(viewModel.getAssignments().get("rejected").get(1)); assertEquals("rejected two", viewModel.getAssignments().get("rejected").get(1).getComments()); assertEquals("Org D", viewModel.getAssignments().get("rejected").get(1).getUserSimpleOrganisation()); assertTrue(viewModel.isDeclined()); assertEquals(2, viewModel.getDeclinedCount()); assertNotNull(viewModel.getAssignments().get("created")); assertEquals(1, viewModel.getAssignments().get("created").size()); assertNotNull(viewModel.getAssignments().get("created").get(0)); assertEquals("created", viewModel.getAssignments().get("created").get(0).getComments()); assertEquals("Org E", viewModel.getAssignments().get("created").get(0).getUserSimpleOrganisation()); assertTrue(viewModel.isPending()); assertEquals(1, viewModel.getPendingCount()); assertTrue(viewModel.isKtpCompetition()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateHecp() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true); setField(populator, "populatorMap", asMap(QuestionSetupType.HORIZON_WORK_PROGRAMME, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Horizon Europe Guarantee") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.HECP) .withTermsAndConditions(grantTermsAndConditionsResource) .withCompetitionTypeEnum(CompetitionTypeEnum.HORIZON_EUROPE_GUARANTEE) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.HORIZON_WORK_PROGRAMME) .withName("Work programme") .withShortName("Work programme") .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section") .withChildSections(Collections.emptyList(), Collections.singletonList(1L)) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList()) .withType(SectionType.PROJECT_DETAILS, SectionType.FINANCE) .build(2); HorizonWorkProgrammeResource workProgramme = new HorizonWorkProgrammeResource(6, "CL6", null, true); HorizonWorkProgrammeResource callerId = new HorizonWorkProgrammeResource(6, "CL6", workProgramme, true); workProgrammeFuture = asList(new ApplicationHorizonWorkProgrammeResource(applicationId, workProgramme), new ApplicationHorizonWorkProgrammeResource(applicationId, callerId)); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, emptyList(), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.getQuestions().iterator().next(), expectedRowModel); assertEquals(workProgrammeFuture, expectedData.getApplicationHorizonWorkProgrammeResource().get()); assertFalse(viewModel.isExpressionOfInterestApplication()); verify(mockPopulator).populate(questions.get(0), expectedData, settings); } @Test public void populateEOI() { String title = "Eoi Evidence"; String name = "eoi_evidence.pdf"; int filesizeBytes = 4380; String mediaType = ".pdf"; long fileEntryId = 1234L; UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationExpressionOfInterestConfigResource applicationExpressionOfInterestConfig = newApplicationExpressionOfInterestConfigResource() .withEnabledForExpressionOfInterest(true) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeQuestionNumber(false); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionEoiEvidenceConfigResource competitionEoiEvidenceConfigResource = CompetitionEoiEvidenceConfigResource.builder() .evidenceRequired(true) .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .withCompetitionEoiEvidenceConfigResource(competitionEoiEvidenceConfigResource) .build(); ApplicationEoiEvidenceResponseResource applicationEoiEvidenceResponseResource = ApplicationEoiEvidenceResponseResource.builder() .fileState(State.SUBMITTED) .build(); OrganisationResource organisation = newOrganisationResource().build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withApplicationExpressionOfInterestConfigResource(applicationExpressionOfInterestConfig) .withApplicationState(ApplicationState.SUBMITTED) .withSubmittedDate(ZonedDateTime.now()) .withApplicationEoiEvidenceResponseResource(applicationEoiEvidenceResponseResource) .withLeadOrganisationId(organisation.getId()) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .withEnabledForPreRegistration(false) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .withEnabledForPreRegistration(false) .build(3); ProcessRoleResource processRole = newProcessRoleResource() .withRole(ProcessRoleType.LEADAPPLICANT) .withUser(user) .withOrganisation(organisation.getId()) .build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); EoiEvidenceReadOnlyViewModel eoiEvidenceReadOnlyViewModel = EoiEvidenceReadOnlyViewModel.builder() .applicationId(applicationId) .expressionOfInterestApplication(true) .title(title) .build(); eoiEvidenceReadOnlyViewModel.setName(name); eoiEvidenceReadOnlyViewModel.setFilesizeBytes(filesizeBytes); eoiEvidenceReadOnlyViewModel.setMediaType(mediaType); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(eoiEvidenceReadOnlyViewModelPopulator.populate(application)).thenReturn(eoiEvidenceReadOnlyViewModel); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertEquals(viewModel.getSettings(), settings); assertEquals(viewModel.getSections().size(), 2); assertFalse(viewModel.isEoiFullApplication()); assertTrue(viewModel.isExpressionOfInterestApplication()); Iterator<ApplicationSectionReadOnlyViewModel> iterator = viewModel.getSections().iterator(); ApplicationSectionReadOnlyViewModel sectionWithQuestion = iterator.next(); assertEquals(sectionWithQuestion.getName(), "Section with questions"); assertEquals(sectionWithQuestion.isVisible(), false); assertEquals(sectionWithQuestion.getQuestions().size(), 0); ApplicationSectionReadOnlyViewModel financeSection = iterator.next(); assertEquals(financeSection.getName(), "Finance section"); assertEquals(financeSection.isVisible(), false); assertEquals(financeSection.getQuestions().iterator().next(), expectedFinanceSummary); EoiEvidenceReadOnlyViewModel eoiViewModel = viewModel.getEoiEvidenceReadOnlyViewModel(); assertNotNull(eoiViewModel); assertEquals(applicationId, eoiViewModel.getApplicationId().longValue()); assertEquals(title, eoiViewModel.getTitle()); assertEquals(name, eoiViewModel.getName()); assertEquals(filesizeBytes, eoiViewModel.getFilesizeBytes()); assertEquals(mediaType, eoiViewModel.getMediaType()); } @Test public void populateEOIFullApplication() { UserResource user = newUserResource() .withRoleGlobal(Role.APPLICANT) .build(); ApplicationExpressionOfInterestConfigResource applicationExpressionOfInterestConfig = newApplicationExpressionOfInterestConfigResource() .withEnabledForExpressionOfInterest(false) .withEoiApplicationId(eoiApplicationId) .build(); ApplicationReadOnlySettings settings = ApplicationReadOnlySettings.defaultSettings() .setIncludeQuestionLinks(true) .setIncludeStatuses(true) .setAssessmentId(assessmentId) .setIncludeQuestionNumber(false); setField(populator, "populatorMap", asMap(QuestionSetupType.APPLICATION_TEAM, mockPopulator)); setField(populator, "asyncFuturesGenerator", futuresGeneratorMock); GrantTermsAndConditionsResource grantTermsAndConditionsResource = newGrantTermsAndConditionsResource() .withName("Innovate UK") .build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.GRANT) .withTermsAndConditions(grantTermsAndConditionsResource) .build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .withApplicationExpressionOfInterestConfigResource(applicationExpressionOfInterestConfig) .build(); List<QuestionResource> questions = newQuestionResource() .withQuestionSetupType(QuestionSetupType.APPLICATION_TEAM) .withEnabledForPreRegistration(false) .build(1); List<QuestionStatusResource> questionStatuses = newQuestionStatusResource() .withQuestion(questions.get(0).getId()) .build(1); OrganisationResource organisation = newOrganisationResource().build(); List<SectionResource> sections = newSectionResource() .withName("Section with questions", "Finance section", "Score assessment") .withChildSections(Collections.emptyList(), Collections.singletonList(1L), Collections.emptyList()) .withQuestions(questions.stream().map(QuestionResource::getId).collect(Collectors.toList()), emptyList(), emptyList()) .withType(SectionType.GENERAL, SectionType.FINANCE, SectionType.KTP_ASSESSMENT) .withEnabledForPreRegistration(false) .build(3); ProcessRoleResource processRole = newProcessRoleResource().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).build(); Map<Long, BigDecimal> scores = new HashMap<>(); scores.put(1L, new BigDecimal("9")); Map<Long, String> feedback = new HashMap<>(); feedback.put(1L, "Hello world"); ApplicationAssessmentResource assessorResponseFuture = newApplicationAssessmentResource() .withApplicationId(applicationId) .withTestId(3L) .withAveragePercentage(new BigDecimal("50.0")) .withScores(scores) .withFeedback(feedback) .build(); ApplicationReadOnlyData expectedData = new ApplicationReadOnlyData(application, competition, user, newArrayList(processRole), questions, formInputs, responses, questionStatuses, singletonList(assessorResponseFuture), emptyList(), Optional.of(workProgrammeFuture)); ApplicationQuestionReadOnlyViewModel expectedRowModel = mock(ApplicationQuestionReadOnlyViewModel.class); FinanceReadOnlyViewModel expectedFinanceSummary = mock(FinanceReadOnlyViewModel.class); when(financeSummaryViewModelPopulator.populate(expectedData)).thenReturn(expectedFinanceSummary); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(questionRestService.findByCompetition(competition.getId())).thenReturn(restSuccess(questions)); when(formInputRestService.getByCompetitionId(competition.getId())).thenReturn(restSuccess(formInputs)); when(formInputResponseRestService.getResponsesByApplicationId(application.getId())).thenReturn(restSuccess(responses)); when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation)); when(questionStatusRestService.findByApplicationAndOrganisation(applicationId, organisation.getId())).thenReturn(restSuccess(questionStatuses)); when(sectionRestService.getByCompetition(competition.getId())).thenReturn(restSuccess(sections)); when(processRoleRestService.findProcessRole(application.getId())).thenReturn(restSuccess(newArrayList(processRole))); when(assessorFormInputResponseRestService.getApplicationAssessment(applicationId, assessmentId)).thenReturn(restSuccess(assessorResponseFuture)); when(horizonWorkProgrammeRestService.findSelected(applicationId)).thenReturn(restSuccess(workProgrammeFuture)); when(mockPopulator.populate(questions.get(0), expectedData, settings)).thenReturn(expectedRowModel); ApplicationReadOnlyViewModel viewModel = populator.populate(applicationId, user, settings); assertTrue(viewModel.isEoiFullApplication()); assertFalse(viewModel.isExpressionOfInterestApplication()); } }
42,249
0.739852
0.737154
707
58.758133
41.029255
166
false
false
0
0
0
0
0
0
0.855728
false
false
8
d6aa30cc4442101292ba891600cfc32ba866f148
35,356,170,820,861
b46d0a987800e5319a7407794fa72fae6d390574
/src/com/company/Main.java
5a5f9bd1bb5d7316067db9e0c98813904a797778
[]
no_license
EserskyD/Guias
https://github.com/EserskyD/Guias
9c558053f625866ef4485444132976f6f80a3592
11da0d01a894548fe1a5541076cc49327939ee44
refs/heads/master
2023-04-01T04:31:18.124000
2021-04-09T17:27:04
2021-04-09T17:27:04
351,874,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.Scanner; import java.io.IOException; public class Main { public static void main(String[] args) { Scanner nuevoScanner = new Scanner(System.in); Scanner intScanner = new Scanner(System.in); int varInt = 2, varX = 3, varY = 4, numero; double varDou = 1.2584, varM = 1.101010, varN = 1.202020; String varChar = "H" ,nombre; System.out.println(varInt); System.out.println(varDou); System.out.println(varChar); System.out.println(varX + "+" + varY + "=" + (varX+varY)); System.out.println(varM + "+" + varN + " = " + (varM+varN)); System.out.print(varInt + "+77="); varInt = (varInt + 77); System.out.println(varInt); System.out.print(varInt + "-3="); varInt = (varInt - 3); System.out.println(varInt); System.out.print(varInt + "*2="); varInt = (varInt * 2); System.out.println(varInt); System.out.println("Ingrese un nombre: "); nombre = nuevoScanner.nextLine(); System.out.println("Buenos días " + nombre); System.out.println("Ingrese un número: "); numero = intScanner.nextInt(); if ((numero % 2) == 1) { System.out.println("El numero es impar"); } else if((numero % 2) == 0) { System.out.println("El numero es par"); } } }
UTF-8
Java
1,435
java
Main.java
Java
[]
null
[]
package com.company; import java.util.Scanner; import java.io.IOException; public class Main { public static void main(String[] args) { Scanner nuevoScanner = new Scanner(System.in); Scanner intScanner = new Scanner(System.in); int varInt = 2, varX = 3, varY = 4, numero; double varDou = 1.2584, varM = 1.101010, varN = 1.202020; String varChar = "H" ,nombre; System.out.println(varInt); System.out.println(varDou); System.out.println(varChar); System.out.println(varX + "+" + varY + "=" + (varX+varY)); System.out.println(varM + "+" + varN + " = " + (varM+varN)); System.out.print(varInt + "+77="); varInt = (varInt + 77); System.out.println(varInt); System.out.print(varInt + "-3="); varInt = (varInt - 3); System.out.println(varInt); System.out.print(varInt + "*2="); varInt = (varInt * 2); System.out.println(varInt); System.out.println("Ingrese un nombre: "); nombre = nuevoScanner.nextLine(); System.out.println("Buenos días " + nombre); System.out.println("Ingrese un número: "); numero = intScanner.nextInt(); if ((numero % 2) == 1) { System.out.println("El numero es impar"); } else if((numero % 2) == 0) { System.out.println("El numero es par"); } } }
1,435
0.551989
0.528262
45
30.844444
20.02549
68
false
false
0
0
0
0
0
0
0.777778
false
false
8
a00863f625c4d18654c9ef8501b8bec07305f185
35,390,530,560,979
64f12a1df92016bb451278e4d071d519cb3a548a
/grp86_ueb03/test/grp84_04/MyListTest.java
9ee37c258114288258bd1d28002e12977322fa7e
[]
no_license
klonno22/java-ptl
https://github.com/klonno22/java-ptl
2a1968f3954a3eb3d94eac83ab7f51ae1c7d80bb
c9536c032d16b7fbf5199f8382c44d3e7bc15f91
refs/heads/master
2020-04-20T09:45:40.685000
2019-02-01T23:29:01
2019-02-01T23:29:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package grp84_04; import org.junit.Test; import static org.junit.Assert.*; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; /** * Tests der Methoden, die bereits in der Vorlesung vorgestellt werden. * @author klk */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MyListTest { /** * Erzeugt eine Liste mit den übergebenen Werten. * @param value Werte, die in die Liste eingefügt werden sollen. * @return Liste mit den Werten. */ private MyList createList(char... value) { MyList list = new MyList(); for (char i : value) { list.appendElement(i); } return list; } //<editor-fold defaultstate="collapsed" desc="Methodentests für Methoden aus Vorlesung"> //----------------------------------------------- @Test public void testIsEmpty() { MyList list = new MyList(); assertTrue(list.isEmpty()); list = createList('a'); assertFalse(list.isEmpty()); } @Test public void testAppendElement() { MyList list = new MyList(); assertEquals(0, list.size()); list.appendElement('a'); assertEquals(1, list.size()); } //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="testInsertElement"> @Test public void testInsertElement_InEmptyList() { MyList list = createList(); list.insertElement('a'); assertEquals(1, list.size()); } @Test public void testInsertElement_AtFront() { MyList list = createList('b', 'c', 'd'); list.insertElement('a'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } @Test public void testInsertElement_InMiddle() { MyList list = createList('a', 'c', 'd'); list.insertElement('b'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } @Test public void testInsertElement_AtEnd() { MyList list = createList('a', 'b', 'c'); list.insertElement('d'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } //</editor-fold> //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="testDeleteElement"> @Test public void testDeleteElement_AtFront() { MyList list = createList('a', 'b', 'c'); list.deleteElement('a'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'b', 'c'}, list.getValues()); } @Test public void testDeleteElement_InMiddle() { MyList list = createList('a', 'b', 'c'); list.deleteElement('b'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'a', 'c'}, list.getValues()); } @Test public void testDeleteElement_AtEnd() { MyList list = createList('a', 'b', 'c'); list.deleteElement('c'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'a', 'b'}, list.getValues()); } @Test public void testDeleteElement_NotExisting() { MyList list = createList('a', 'b', 'c'); list.deleteElement('d'); assertEquals(3, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c'}, list.getValues()); } @Test public void testDeleteElement_EmptyList() { MyList list = createList(); list.deleteElement('d'); assertEquals(0, list.size()); assertArrayEquals(new char[]{}, list.getValues()); } //</editor-fold> //</editor-fold> //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="geforderte Situationstests"> /*TODO Test ListOfThree mit Liste {'a', 'c', 'e'} */ /*TODO Test ListWithDoubleValues mit {'a', 'b', 'b', 'c'} */ /*TODO Test ListUnsortedAtBegin mit {'b', 'a', 'c'} */ /*TODO Test ListEmpty mit {} */ /* zu testen ist jeweils - ist leer - ist sortiert - Listenlänge - existiert der Wert [..] (alle vorhandenen und mindestens einen nicht vorhandenen Wert prüfen) - getElementAt() für jeden vorhandenen Wert und für mindestens einen falschen Index zu verwenden sind - assertTrue(), assertFalse(), assertEquals(), bei Bedarf assertArrayEquals() */ @Test public void testListOfThree() { MyList list = createList('a', 'c', 'e'); assertFalse(list.isEmpty()); assertTrue(list.isSorted()); assertEquals(3, list.size()); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('c')); assertTrue(list.existsElement('e')); assertFalse(list.existsElement('d')); assertEquals('a', list.getElementAt(0)); assertEquals('c', list.getElementAt(1)); assertEquals('e', list.getElementAt(2)); assertEquals(0, list.getElementAt(3)); } @Test public void testListWithDoubleValues() { MyList list = createList('a', 'b', 'b', 'c'); assertFalse(list.isEmpty()); assertTrue(list.isSorted()); assertEquals(4, list.size()); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('b')); assertTrue(list.existsElement('c')); assertFalse(list.existsElement('d')); assertEquals('a', list.getElementAt(0)); assertEquals('b', list.getElementAt(1)); assertEquals('b', list.getElementAt(2)); assertEquals('c', list.getElementAt(3)); assertEquals(0, list.getElementAt(4)); } @Test public void testListUnsortedAtBegin() { MyList list = createList('b', 'a', 'c'); assertFalse(list.isEmpty()); assertFalse(list.isSorted()); assertEquals(3, list.size()); assertTrue(list.existsElement('b')); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('c')); assertFalse(list.existsElement('d')); assertEquals('b', list.getElementAt(0)); assertEquals('a', list.getElementAt(1)); assertEquals('c', list.getElementAt(2)); assertEquals(0, list.getElementAt(3)); } @Test public void testListEmpty() { MyList list = createList(); assertTrue(list.isEmpty()); assertFalse(list.isSorted()); assertEquals(0, list.size()); assertFalse(list.existsElement('d')); assertEquals(0, list.getElementAt(0)); } //</editor-fold> }
UTF-8
Java
6,970
java
MyListTest.java
Java
[ { "context": "s in der Vorlesung vorgestellt werden.\r\n * @author klk\r\n */\r\n@FixMethodOrder(MethodSorters.NAME_ASCENDIN", "end": 249, "score": 0.9996147751808167, "start": 246, "tag": "USERNAME", "value": "klk" } ]
null
[]
package grp84_04; import org.junit.Test; import static org.junit.Assert.*; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; /** * Tests der Methoden, die bereits in der Vorlesung vorgestellt werden. * @author klk */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MyListTest { /** * Erzeugt eine Liste mit den übergebenen Werten. * @param value Werte, die in die Liste eingefügt werden sollen. * @return Liste mit den Werten. */ private MyList createList(char... value) { MyList list = new MyList(); for (char i : value) { list.appendElement(i); } return list; } //<editor-fold defaultstate="collapsed" desc="Methodentests für Methoden aus Vorlesung"> //----------------------------------------------- @Test public void testIsEmpty() { MyList list = new MyList(); assertTrue(list.isEmpty()); list = createList('a'); assertFalse(list.isEmpty()); } @Test public void testAppendElement() { MyList list = new MyList(); assertEquals(0, list.size()); list.appendElement('a'); assertEquals(1, list.size()); } //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="testInsertElement"> @Test public void testInsertElement_InEmptyList() { MyList list = createList(); list.insertElement('a'); assertEquals(1, list.size()); } @Test public void testInsertElement_AtFront() { MyList list = createList('b', 'c', 'd'); list.insertElement('a'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } @Test public void testInsertElement_InMiddle() { MyList list = createList('a', 'c', 'd'); list.insertElement('b'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } @Test public void testInsertElement_AtEnd() { MyList list = createList('a', 'b', 'c'); list.insertElement('d'); assertEquals(4, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, list.getValues()); } //</editor-fold> //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="testDeleteElement"> @Test public void testDeleteElement_AtFront() { MyList list = createList('a', 'b', 'c'); list.deleteElement('a'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'b', 'c'}, list.getValues()); } @Test public void testDeleteElement_InMiddle() { MyList list = createList('a', 'b', 'c'); list.deleteElement('b'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'a', 'c'}, list.getValues()); } @Test public void testDeleteElement_AtEnd() { MyList list = createList('a', 'b', 'c'); list.deleteElement('c'); assertEquals(2, list.size()); assertArrayEquals(new char[]{'a', 'b'}, list.getValues()); } @Test public void testDeleteElement_NotExisting() { MyList list = createList('a', 'b', 'c'); list.deleteElement('d'); assertEquals(3, list.size()); assertArrayEquals(new char[]{'a', 'b', 'c'}, list.getValues()); } @Test public void testDeleteElement_EmptyList() { MyList list = createList(); list.deleteElement('d'); assertEquals(0, list.size()); assertArrayEquals(new char[]{}, list.getValues()); } //</editor-fold> //</editor-fold> //----------------------------------------------- //<editor-fold defaultstate="collapsed" desc="geforderte Situationstests"> /*TODO Test ListOfThree mit Liste {'a', 'c', 'e'} */ /*TODO Test ListWithDoubleValues mit {'a', 'b', 'b', 'c'} */ /*TODO Test ListUnsortedAtBegin mit {'b', 'a', 'c'} */ /*TODO Test ListEmpty mit {} */ /* zu testen ist jeweils - ist leer - ist sortiert - Listenlänge - existiert der Wert [..] (alle vorhandenen und mindestens einen nicht vorhandenen Wert prüfen) - getElementAt() für jeden vorhandenen Wert und für mindestens einen falschen Index zu verwenden sind - assertTrue(), assertFalse(), assertEquals(), bei Bedarf assertArrayEquals() */ @Test public void testListOfThree() { MyList list = createList('a', 'c', 'e'); assertFalse(list.isEmpty()); assertTrue(list.isSorted()); assertEquals(3, list.size()); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('c')); assertTrue(list.existsElement('e')); assertFalse(list.existsElement('d')); assertEquals('a', list.getElementAt(0)); assertEquals('c', list.getElementAt(1)); assertEquals('e', list.getElementAt(2)); assertEquals(0, list.getElementAt(3)); } @Test public void testListWithDoubleValues() { MyList list = createList('a', 'b', 'b', 'c'); assertFalse(list.isEmpty()); assertTrue(list.isSorted()); assertEquals(4, list.size()); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('b')); assertTrue(list.existsElement('c')); assertFalse(list.existsElement('d')); assertEquals('a', list.getElementAt(0)); assertEquals('b', list.getElementAt(1)); assertEquals('b', list.getElementAt(2)); assertEquals('c', list.getElementAt(3)); assertEquals(0, list.getElementAt(4)); } @Test public void testListUnsortedAtBegin() { MyList list = createList('b', 'a', 'c'); assertFalse(list.isEmpty()); assertFalse(list.isSorted()); assertEquals(3, list.size()); assertTrue(list.existsElement('b')); assertTrue(list.existsElement('a')); assertTrue(list.existsElement('c')); assertFalse(list.existsElement('d')); assertEquals('b', list.getElementAt(0)); assertEquals('a', list.getElementAt(1)); assertEquals('c', list.getElementAt(2)); assertEquals(0, list.getElementAt(3)); } @Test public void testListEmpty() { MyList list = createList(); assertTrue(list.isEmpty()); assertFalse(list.isSorted()); assertEquals(0, list.size()); assertFalse(list.existsElement('d')); assertEquals(0, list.getElementAt(0)); } //</editor-fold> }
6,970
0.547034
0.541721
218
29.940367
22.161234
99
false
false
0
0
0
0
0
0
0.816514
false
false
8
01fac1b763e0af7778ec7957cf67c8f5d18911c5
37,383,395,361,240
eca0868dc79222498a217bb8a5129924a6f3b348
/interpreter/Program.java
ff736e09c8ce01aff6eea1d61baf6225d4cbd691
[ "MIT" ]
permissive
AndrewHwang97/CSC415-InterpreterSpring2020
https://github.com/AndrewHwang97/CSC415-InterpreterSpring2020
158685823b6127690f738001e5ecb122ae246efd
0d69daa37b4ebd22cf243ed1f6032447ff4cb243
refs/heads/master
2022-07-31T18:50:54.113000
2020-05-02T00:59:26
2020-05-02T00:59:26
266,688,588
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package interpreter; import java.util.ArrayList; import java.util.HashMap; import interpreter.bytecode.*; public class Program { private ArrayList<ByteCode> program; public Program() { program = new ArrayList<>(); } protected ByteCode getCode(int programCounter) { return this.program.get(programCounter); } /** * This function should go through the program and resolve all addresses. * Currently all labels look like LABEL <<num>>>, these need to be converted into * correct addresses so the VirtualMachine knows what to set the Program Counter * HINT: make note what type of data-structure ByteCodes are stored in. */ public void resolveAddress() { HashMap<String,Integer> jumpMap = new HashMap<>(); ByteCode code; for(int i = 0; i < program.size(); i++){ code = this.program.get(i); if(code instanceof LabelCode){ jumpMap.put(program.get(i).toString(), i); //look ofr all label codes and store the label and its addr //in a hashmap //45. Label continue<<9>> // (continue<<9>>, 45) } } for(int i = 0; i < program.size(); i++){ code = this.program.get(i); if(code instanceof JumpCode){ final JumpCode jc = (JumpCode) code; String label = jc.getLabel(); jc.setAddress(jumpMap.get(label)); //cast the code reference to correct concrete type //get label of gotocode //find index of label from jump //set address of gotocode with the returned index } //look for falsebranchcode, goto and call // and get the next the labels appear in the //program arraylist } } public void addToProgram(ByteCode code){ program.add(code); } }
UTF-8
Java
2,033
java
Program.java
Java
[]
null
[]
package interpreter; import java.util.ArrayList; import java.util.HashMap; import interpreter.bytecode.*; public class Program { private ArrayList<ByteCode> program; public Program() { program = new ArrayList<>(); } protected ByteCode getCode(int programCounter) { return this.program.get(programCounter); } /** * This function should go through the program and resolve all addresses. * Currently all labels look like LABEL <<num>>>, these need to be converted into * correct addresses so the VirtualMachine knows what to set the Program Counter * HINT: make note what type of data-structure ByteCodes are stored in. */ public void resolveAddress() { HashMap<String,Integer> jumpMap = new HashMap<>(); ByteCode code; for(int i = 0; i < program.size(); i++){ code = this.program.get(i); if(code instanceof LabelCode){ jumpMap.put(program.get(i).toString(), i); //look ofr all label codes and store the label and its addr //in a hashmap //45. Label continue<<9>> // (continue<<9>>, 45) } } for(int i = 0; i < program.size(); i++){ code = this.program.get(i); if(code instanceof JumpCode){ final JumpCode jc = (JumpCode) code; String label = jc.getLabel(); jc.setAddress(jumpMap.get(label)); //cast the code reference to correct concrete type //get label of gotocode //find index of label from jump //set address of gotocode with the returned index } //look for falsebranchcode, goto and call // and get the next the labels appear in the //program arraylist } } public void addToProgram(ByteCode code){ program.add(code); } }
2,033
0.553861
0.549926
63
30.301588
24.6838
85
false
false
0
0
0
0
0
0
0.396825
false
false
8
285ce5f832dc800cb481ded878f9d7c875162aa0
28,243,704,962,724
7bd76b1ea67c899c145322fc9904aaa4eb4c74f3
/src/ch/dabsoft/dabscheme/vm/Globals.java
15084529c1e883374568664feb192355c6349e85
[]
no_license
damianbrunold/dabscheme
https://github.com/damianbrunold/dabscheme
19ed65ab7ec43c7c16774906b16bb225dfec2629
1b8b08799894b7f738c1d1a87b1d6d742e7f45ab
refs/heads/master
2020-09-01T21:46:36.358000
2019-12-22T20:20:06
2019-12-22T20:20:06
219,066,572
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ch.dabsoft.dabscheme.vm; import ch.dabsoft.dabscheme.primitive.*; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PushbackReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Globals { private Map<String, Object> globals = new HashMap<>(); public Globals(Globals copyfrom) { this.globals.putAll(copyfrom.globals); } public Globals() { bind("*input-port*", new PushbackReader(new InputStreamReader(System.in))); bind("*output-port*", new OutputStreamWriter(System.out)); bind("nil", Value.NIL); bind("+", new PrimitiveAdd()); bind("*", new PrimitiveMul()); bind("-", new PrimitiveSub()); bind("/", new PrimitiveDiv()); bind("=", new PrimitiveNumequal()); bind("<", new PrimitiveNumless()); bind("<=", new PrimitiveNumlessequal()); bind(">", new PrimitiveNumgreater()); bind(">=", new PrimitiveNumgreaterequal()); bind("eq?", new PrimitiveEqP()); bind("cons", new PrimitiveCons()); bind("car", new PrimitiveCar()); bind("cdr", new PrimitiveCdr()); bind("set-car!", new PrimitiveSetCarB()); bind("set-cdr!", new PrimitiveSetCdrB()); bind("append", new PrimitiveAppend()); bind("pair?", new PrimitivePairP()); bind("symbol?", new PrimitiveSymbolP()); bind("boolean?", new PrimitiveBooleanP()); bind("char?", new PrimitiveCharP()); bind("string?", new PrimitiveStringP()); bind("integer?", new PrimitiveIntegerP()); bind("real?", new PrimitiveRealP()); bind("vector?", new PrimitiveVectorP()); bind("lambda?", new PrimitiveLambdaP()); bind("primitive?", new PrimitivePrimitiveP()); bind("sqrt", new PrimitiveSqrt()); bind("gensym", new PrimitiveGensym()); bind("compile", new PrimitiveCompile(this)); bind("vector-length", new PrimitiveVectorLength()); bind("vector-ref", new PrimitiveVectorRef()); bind("vector", new PrimitiveVector()); bind("vector-set!", new PrimitiveVectorSetB()); bind("make-vector", new PrimitiveMakeVector()); bind("string", new PrimitiveString()); bind("string-length", new PrimitiveStringLength()); bind("string-ref", new PrimitiveStringRef()); bind("string->symbol", new PrimitiveStringToSymbol()); bind("string-set!", new PrimitiveStringSetB()); bind("make-string", new PrimitiveMakeString()); bind("string=?", new PrimitiveStringEqP()); bind("string<?", new PrimitiveStringLessP()); bind("string<=?", new PrimitiveStringLessEqP()); bind("string>?", new PrimitiveStringGreaterP()); bind("string>=?", new PrimitiveStringGreaterEqP()); bind("string-copy", new PrimitiveStringCopy()); bind("string-append", new PrimitiveStringAppend()); bind("substring", new PrimitiveSubstring()); bind("symbol->string", new PrimitiveSymbolToString()); bind("char=?", new PrimitiveCharEqP()); bind("char<?", new PrimitiveCharLessP()); bind("char<=?", new PrimitiveCharLessEqP()); bind("char>?", new PrimitiveCharGreaterP()); bind("char>=?", new PrimitiveCharGreaterEqP()); bind("char-alphabetic?", new PrimitiveCharAlphabeticP()); bind("char-numeric?", new PrimitiveCharNumericP()); bind("char-upper-case?", new PrimitiveCharUpperCaseP()); bind("char-lower-case?", new PrimitiveCharLowerCaseP()); bind("char-whitespace?", new PrimitiveCharWhitespaceP()); bind("char-upcase", new PrimitiveCharUpcase()); bind("char-downcase", new PrimitiveCharDowncase()); bind("char->integer", new PrimitiveCharToInteger()); bind("integer->char", new PrimitiveIntegerToChar()); bind("quotient", new PrimitiveQuotient()); bind("remainder", new PrimitiveRemainder()); bind("modulo", new PrimitiveModulo()); bind("truncate", new PrimitiveTruncate()); bind("floor", new PrimitiveFloor()); bind("ceiling", new PrimitiveCeiling()); bind("round", new PrimitiveRound()); bind("expt", new PrimitiveExpt()); bind("exact->inexact", new PrimitiveExactToInexact()); bind("inexact->exact", new PrimitiveInexactToExact()); bind("string->number", new PrimitiveStringToNumber()); bind("number->string", new PrimitiveNumberToString()); bind("log", new PrimitiveLog()); bind("sin", new PrimitiveSin()); bind("cos", new PrimitiveCos()); bind("tan", new PrimitiveTan()); bind("asin", new PrimitiveAsin()); bind("acos", new PrimitiveAcos()); bind("atan", new PrimitiveAtan()); bind("exact?", new PrimitiveExactP()); bind("error", new PrimitiveError()); bind("input-port?", new PrimitiveInputPortP()); bind("output-port?", new PrimitiveOutputPortP()); bind("open-input-file", new PrimitiveOpenInputFile()); bind("open-input-string", new PrimitiveOpenInputString()); bind("close-input-port", new PrimitiveCloseInputPort()); bind("open-output-file", new PrimitiveOpenOutputFile()); bind("open-output-string", new PrimitiveOpenOutputString()); bind("get-output-string", new PrimitiveGetOutputString()); bind("close-output-port", new PrimitiveCloseOutputPort()); bind("string-split", new PrimitiveStringSplit()); bind("string-split-vector", new PrimitiveStringSplitVector()); bind("read-char", new PrimitiveReadChar(this)); bind("peek-char", new PrimitivePeekChar(this)); bind("char-ready?", new PrimitiveCharReadyP(this)); bind("read-line", new PrimitiveReadLine(this)); bind("read", new PrimitiveRead(this)); bind("load", new PrimitiveLoad(this)); bind("eof-object?", new PrimitiveEOFObjectP()); bind("write-char", new PrimitiveWriteChar(this)); bind("write", new PrimitiveWrite(this)); bind("display", new PrimitiveDisplay(this)); bind("newline", new PrimitiveNewline(this)); bind("flush", new PrimitiveFlush(this)); bind("values", new PrimitiveValues()); bind("call-with-current-continuation", getCallCC()); bind("apply", getApply()); bind("call-with-values", getCallWithValues()); bind("eval", new PrimitiveEval(this)); bind("disassemble", new PrimitiveDisassemble(this)); bind("get-code", new PrimitiveGetCode()); bind("get-env", new PrimitiveGetEnv()); bind("instruction-opcode", new PrimitiveInstructionOpcode()); bind("instruction-arg1", new PrimitiveInstructionArg1()); bind("instruction-arg2", new PrimitiveInstructionArg2()); bind("make-instruction", new PrimitiveMakeInstruction()); bind("set-code!", new PrimitiveSetCodeB()); bind("make-dict", new PrimitiveMakeDict()); bind("dict-put", new PrimitiveDictPut()); bind("dict-get", new PrimitiveDictGet()); bind("dict-contains", new PrimitiveDictContains()); bind("dict-clear", new PrimitiveDictClear()); bind("dict-keys", new PrimitiveDictKeys()); bind("dict-size", new PrimitiveDictSize()); bind("exit", new PrimitiveExit()); bind("PI", Math.PI); bind("E", Math.E); } private Object getCallCC() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGS, 1)); instructions.add(new Instruction(Opcode.CC)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, 1)); Lambda callcc = new Lambda(Value.NIL, instructions); callcc.name = "call-with-current-continuation"; return callcc; } private Object getApply() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGSDOT, 1)); instructions.add(new Instruction(Opcode.FLATTEN_APPLY, 0, 1)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, -1)); Lambda apply = new Lambda(Value.NIL, instructions); apply.name = "apply"; return apply; } private Object getCallWithValues() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGS, 2)); instructions.add(new Instruction(Opcode.SAVE, 4)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, 0)); instructions.add(new Instruction(Opcode.FLATTEN_MULTVALS, 0, 1)); instructions.add(new Instruction(Opcode.LVAR, 0, 1)); instructions.add(new Instruction(Opcode.CALLJ, -1)); Lambda apply = new Lambda(Value.NIL, instructions); apply.name = "call-with-values"; return apply; } public boolean isBound(String symbol) { return globals.containsKey(Value.intern(symbol)); } public Object resolve(String symbol) { Object result = globals.get(Value.intern(symbol)); if (result == null) throw new IllegalStateException(symbol + " is not bound"); return result; } public void bind(String symbol, Object value) { globals.put(Value.intern(symbol), value); } public void resetTo(Globals base) { this.globals.clear(); this.globals.putAll(base.globals); } }
UTF-8
Java
9,882
java
Globals.java
Java
[]
null
[]
package ch.dabsoft.dabscheme.vm; import ch.dabsoft.dabscheme.primitive.*; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PushbackReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Globals { private Map<String, Object> globals = new HashMap<>(); public Globals(Globals copyfrom) { this.globals.putAll(copyfrom.globals); } public Globals() { bind("*input-port*", new PushbackReader(new InputStreamReader(System.in))); bind("*output-port*", new OutputStreamWriter(System.out)); bind("nil", Value.NIL); bind("+", new PrimitiveAdd()); bind("*", new PrimitiveMul()); bind("-", new PrimitiveSub()); bind("/", new PrimitiveDiv()); bind("=", new PrimitiveNumequal()); bind("<", new PrimitiveNumless()); bind("<=", new PrimitiveNumlessequal()); bind(">", new PrimitiveNumgreater()); bind(">=", new PrimitiveNumgreaterequal()); bind("eq?", new PrimitiveEqP()); bind("cons", new PrimitiveCons()); bind("car", new PrimitiveCar()); bind("cdr", new PrimitiveCdr()); bind("set-car!", new PrimitiveSetCarB()); bind("set-cdr!", new PrimitiveSetCdrB()); bind("append", new PrimitiveAppend()); bind("pair?", new PrimitivePairP()); bind("symbol?", new PrimitiveSymbolP()); bind("boolean?", new PrimitiveBooleanP()); bind("char?", new PrimitiveCharP()); bind("string?", new PrimitiveStringP()); bind("integer?", new PrimitiveIntegerP()); bind("real?", new PrimitiveRealP()); bind("vector?", new PrimitiveVectorP()); bind("lambda?", new PrimitiveLambdaP()); bind("primitive?", new PrimitivePrimitiveP()); bind("sqrt", new PrimitiveSqrt()); bind("gensym", new PrimitiveGensym()); bind("compile", new PrimitiveCompile(this)); bind("vector-length", new PrimitiveVectorLength()); bind("vector-ref", new PrimitiveVectorRef()); bind("vector", new PrimitiveVector()); bind("vector-set!", new PrimitiveVectorSetB()); bind("make-vector", new PrimitiveMakeVector()); bind("string", new PrimitiveString()); bind("string-length", new PrimitiveStringLength()); bind("string-ref", new PrimitiveStringRef()); bind("string->symbol", new PrimitiveStringToSymbol()); bind("string-set!", new PrimitiveStringSetB()); bind("make-string", new PrimitiveMakeString()); bind("string=?", new PrimitiveStringEqP()); bind("string<?", new PrimitiveStringLessP()); bind("string<=?", new PrimitiveStringLessEqP()); bind("string>?", new PrimitiveStringGreaterP()); bind("string>=?", new PrimitiveStringGreaterEqP()); bind("string-copy", new PrimitiveStringCopy()); bind("string-append", new PrimitiveStringAppend()); bind("substring", new PrimitiveSubstring()); bind("symbol->string", new PrimitiveSymbolToString()); bind("char=?", new PrimitiveCharEqP()); bind("char<?", new PrimitiveCharLessP()); bind("char<=?", new PrimitiveCharLessEqP()); bind("char>?", new PrimitiveCharGreaterP()); bind("char>=?", new PrimitiveCharGreaterEqP()); bind("char-alphabetic?", new PrimitiveCharAlphabeticP()); bind("char-numeric?", new PrimitiveCharNumericP()); bind("char-upper-case?", new PrimitiveCharUpperCaseP()); bind("char-lower-case?", new PrimitiveCharLowerCaseP()); bind("char-whitespace?", new PrimitiveCharWhitespaceP()); bind("char-upcase", new PrimitiveCharUpcase()); bind("char-downcase", new PrimitiveCharDowncase()); bind("char->integer", new PrimitiveCharToInteger()); bind("integer->char", new PrimitiveIntegerToChar()); bind("quotient", new PrimitiveQuotient()); bind("remainder", new PrimitiveRemainder()); bind("modulo", new PrimitiveModulo()); bind("truncate", new PrimitiveTruncate()); bind("floor", new PrimitiveFloor()); bind("ceiling", new PrimitiveCeiling()); bind("round", new PrimitiveRound()); bind("expt", new PrimitiveExpt()); bind("exact->inexact", new PrimitiveExactToInexact()); bind("inexact->exact", new PrimitiveInexactToExact()); bind("string->number", new PrimitiveStringToNumber()); bind("number->string", new PrimitiveNumberToString()); bind("log", new PrimitiveLog()); bind("sin", new PrimitiveSin()); bind("cos", new PrimitiveCos()); bind("tan", new PrimitiveTan()); bind("asin", new PrimitiveAsin()); bind("acos", new PrimitiveAcos()); bind("atan", new PrimitiveAtan()); bind("exact?", new PrimitiveExactP()); bind("error", new PrimitiveError()); bind("input-port?", new PrimitiveInputPortP()); bind("output-port?", new PrimitiveOutputPortP()); bind("open-input-file", new PrimitiveOpenInputFile()); bind("open-input-string", new PrimitiveOpenInputString()); bind("close-input-port", new PrimitiveCloseInputPort()); bind("open-output-file", new PrimitiveOpenOutputFile()); bind("open-output-string", new PrimitiveOpenOutputString()); bind("get-output-string", new PrimitiveGetOutputString()); bind("close-output-port", new PrimitiveCloseOutputPort()); bind("string-split", new PrimitiveStringSplit()); bind("string-split-vector", new PrimitiveStringSplitVector()); bind("read-char", new PrimitiveReadChar(this)); bind("peek-char", new PrimitivePeekChar(this)); bind("char-ready?", new PrimitiveCharReadyP(this)); bind("read-line", new PrimitiveReadLine(this)); bind("read", new PrimitiveRead(this)); bind("load", new PrimitiveLoad(this)); bind("eof-object?", new PrimitiveEOFObjectP()); bind("write-char", new PrimitiveWriteChar(this)); bind("write", new PrimitiveWrite(this)); bind("display", new PrimitiveDisplay(this)); bind("newline", new PrimitiveNewline(this)); bind("flush", new PrimitiveFlush(this)); bind("values", new PrimitiveValues()); bind("call-with-current-continuation", getCallCC()); bind("apply", getApply()); bind("call-with-values", getCallWithValues()); bind("eval", new PrimitiveEval(this)); bind("disassemble", new PrimitiveDisassemble(this)); bind("get-code", new PrimitiveGetCode()); bind("get-env", new PrimitiveGetEnv()); bind("instruction-opcode", new PrimitiveInstructionOpcode()); bind("instruction-arg1", new PrimitiveInstructionArg1()); bind("instruction-arg2", new PrimitiveInstructionArg2()); bind("make-instruction", new PrimitiveMakeInstruction()); bind("set-code!", new PrimitiveSetCodeB()); bind("make-dict", new PrimitiveMakeDict()); bind("dict-put", new PrimitiveDictPut()); bind("dict-get", new PrimitiveDictGet()); bind("dict-contains", new PrimitiveDictContains()); bind("dict-clear", new PrimitiveDictClear()); bind("dict-keys", new PrimitiveDictKeys()); bind("dict-size", new PrimitiveDictSize()); bind("exit", new PrimitiveExit()); bind("PI", Math.PI); bind("E", Math.E); } private Object getCallCC() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGS, 1)); instructions.add(new Instruction(Opcode.CC)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, 1)); Lambda callcc = new Lambda(Value.NIL, instructions); callcc.name = "call-with-current-continuation"; return callcc; } private Object getApply() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGSDOT, 1)); instructions.add(new Instruction(Opcode.FLATTEN_APPLY, 0, 1)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, -1)); Lambda apply = new Lambda(Value.NIL, instructions); apply.name = "apply"; return apply; } private Object getCallWithValues() { List<Instruction> instructions = new ArrayList<>(); instructions.add(new Instruction(Opcode.ARGS, 2)); instructions.add(new Instruction(Opcode.SAVE, 4)); instructions.add(new Instruction(Opcode.LVAR, 0, 0)); instructions.add(new Instruction(Opcode.CALLJ, 0)); instructions.add(new Instruction(Opcode.FLATTEN_MULTVALS, 0, 1)); instructions.add(new Instruction(Opcode.LVAR, 0, 1)); instructions.add(new Instruction(Opcode.CALLJ, -1)); Lambda apply = new Lambda(Value.NIL, instructions); apply.name = "call-with-values"; return apply; } public boolean isBound(String symbol) { return globals.containsKey(Value.intern(symbol)); } public Object resolve(String symbol) { Object result = globals.get(Value.intern(symbol)); if (result == null) throw new IllegalStateException(symbol + " is not bound"); return result; } public void bind(String symbol, Object value) { globals.put(Value.intern(symbol), value); } public void resetTo(Globals base) { this.globals.clear(); this.globals.putAll(base.globals); } }
9,882
0.617486
0.615058
212
44.613209
18.998795
86
false
false
0
0
0
0
0
0
1.589623
false
false
8
7e4ce2f647e4f56c6149bf05cfdd90335ba3c10c
32,134,945,339,637
7c88acc88e28b78b1963a97abbce668471d23b56
/src/lib/classSA/MERCADO_OBJ.java
0f3d835ac7a3a58639e25127dcb2b45bb5a5bf57
[]
no_license
gitexpled/RECOTEC
https://github.com/gitexpled/RECOTEC
832999259abb330482c3bd579887094952e7cb5b
48aff6b320ed86057e494d4b8cef02a0b4a1f8f4
refs/heads/master
2020-08-29T18:19:38.555000
2020-08-27T22:20:15
2020-08-27T22:20:15
218,123,329
0
0
null
false
2021-01-21T01:00:48
2019-10-28T18:59:17
2021-01-18T14:56:53
2021-01-21T01:00:46
110,679
0
0
4
JavaScript
false
false
package lib.classSA; public class MERCADO_OBJ { public int codigo; public String descripcion; }
UTF-8
Java
114
java
MERCADO_OBJ.java
Java
[]
null
[]
package lib.classSA; public class MERCADO_OBJ { public int codigo; public String descripcion; }
114
0.666667
0.666667
9
10.666667
11.294049
27
false
false
0
0
0
0
0
0
0.888889
false
false
8
347344bb6bce6b1ff1979b0e79f0b840ccb17fc7
17,995,912,994,643
ca006741352930386de1f9d735ed7cecdb1e36e6
/src/com/pvv/pulbet/dao/impl/CompeticionDAOImpl.java
8fc93a67facfd4288b443b22d5315d27b7c5de98
[]
no_license
pablovarelavazquez/PulBetServices
https://github.com/pablovarelavazquez/PulBetServices
41921a3aedb7c2f0af5c1dc0ee0d24649a5fde91
6070f219344d476973de0cf292dfcf6259076afb
refs/heads/master
2021-07-07T06:14:23.438000
2020-08-14T15:59:58
2020-08-14T15:59:58
162,279,424
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pvv.pulbet.dao.impl; 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 java.util.Date; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.pvv.pulbet.dao.CompeticionDAO; import com.pvv.pulbet.dao.util.JDBCUtils; import com.pvv.pulbet.exceptions.DataException; import com.pvv.pulbet.exceptions.DuplicateInstanceException; import com.pvv.pulbet.exceptions.InstanceNotFoundException; import com.pvv.pulbet.model.Competicion; public class CompeticionDAOImpl implements CompeticionDAO{ private static Logger logger = LogManager.getLogger(CompeticionDAOImpl.class); @Override public Competicion create(Connection connection, Competicion c) throws DuplicateInstanceException, DataException { if(logger.isDebugEnabled()) { logger.debug("Competicion = {}", c); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String queryString = "INSERT INTO COMPETICION(NOMBRE,ID_DEPORTE,FECHA_INICIO, FECHA_FIN) " + "VALUES (?, ?, ?, ?)"; preparedStatement = connection.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS); int i = 1; preparedStatement.setString(i++, c.getNome()); preparedStatement.setLong(i++, c.getIdDeporte()); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaInicio().getYear())); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaFin().getYear())); int insertedRows = preparedStatement.executeUpdate(); if (insertedRows == 0) { throw new SQLException("Can not add row to table 'COMPETICION'"); } resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { Long id = resultSet.getLong(1); c.setIdCompeticion(id); } else { throw new DataException("Unable to fetch autogenerated primary key"); } return c; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public boolean update(Connection connection, Competicion c) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Competicion = {}", c); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String queryString = "UPDATE COMPETICION " + "SET NOMBRE = ?, " + "SET ID_DEPORTE = ?, " + "SET FECHA_INICIO = ?," + "SET FECHA_FIN = ?," + "WHERE ID_COMPETICION=?"; preparedStatement = connection.prepareStatement(queryString); int i = 1; preparedStatement.setString(i++, c.getNome()); preparedStatement.setLong(i++, c.getIdDeporte()); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaInicio().getTime())); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaFin().getTime())); preparedStatement.setLong(i++, c.getIdCompeticion()); int updatedRows = preparedStatement.executeUpdate(); if (updatedRows == 0) { throw new InstanceNotFoundException("Non se atopou competicion: "+c.getIdCompeticion(), Competicion.class.getName()); } if (updatedRows > 1) { throw new SQLException("Duplicate row for id = '" + c.getIdCompeticion() + "' in table 'competicion'"); } else { return true;} //... } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public long delete(Connection connection, Long id) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {} ", id); } PreparedStatement preparedStatement = null; try { String queryString = "DELETE FROM COMPETICION " + "WHERE ID_COMPETICION = ? "; preparedStatement = connection.prepareStatement(queryString); int i = 1; preparedStatement.setLong(i++, id); long removedRows = preparedStatement.executeUpdate(); if (removedRows == 0) { throw new InstanceNotFoundException("Non se atopou competicion: "+id,Competicion.class.getName()); } return removedRows; } catch (SQLException e) { logger.warn(e.getMessage(), e); throw new DataException(e); } finally { JDBCUtils.closeStatement(preparedStatement); } } @Override public Competicion findById(Connection connection, Long id) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {}", id); } Competicion c = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION,NOMBRE,ID_DEPORTE,FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION " +"WHERE ID_COMPETICION = ? "; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setLong(i++, id); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set if (resultSet.next()) { c = loadNext(connection,resultSet); //System.out.println("Cargado "+u); } else { throw new InstanceNotFoundException("Non se atopou competicion con id = "+id, Competicion.class.getName()); } } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } return c; } @Override public List<Competicion> findByDeporte(Connection connection, Long id) throws DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {}", id); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION " +"WHERE ID_DEPORTE = ? "; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setLong(i++, id); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c= null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public List<Competicion> findAll(Connection connection) throws DataException { PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION"; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c = null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public List<Competicion> findByNombre(Connection connection, String nome) throws DataException { if(logger.isDebugEnabled()) { logger.debug("Nome = {}", nome); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +" FROM COMPETICION " +" WHERE " +" UPPER(NOMBRE) LIKE ?"; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setString(i++, "%"+nome.toUpperCase()+"%"); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c = null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } private Competicion loadNext(Connection connection, ResultSet resultSet) throws SQLException{ Competicion c = new Competicion(); int i = 1; Long idCompeticion = resultSet.getLong(i++); String nome = resultSet.getString(i++); Long idDeporte = resultSet.getLong(i++); Date fechaInicio = resultSet.getDate(i++); Date fechaFin = resultSet.getDate(i++); c.setIdCompeticion(idCompeticion); c.setNome(nome); c.setIdDeporte(idDeporte); c.setFechaInicio(fechaInicio); c.setFechaFin(fechaFin); return c; } }
WINDOWS-1250
Java
10,138
java
CompeticionDAOImpl.java
Java
[]
null
[]
package com.pvv.pulbet.dao.impl; 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 java.util.Date; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.pvv.pulbet.dao.CompeticionDAO; import com.pvv.pulbet.dao.util.JDBCUtils; import com.pvv.pulbet.exceptions.DataException; import com.pvv.pulbet.exceptions.DuplicateInstanceException; import com.pvv.pulbet.exceptions.InstanceNotFoundException; import com.pvv.pulbet.model.Competicion; public class CompeticionDAOImpl implements CompeticionDAO{ private static Logger logger = LogManager.getLogger(CompeticionDAOImpl.class); @Override public Competicion create(Connection connection, Competicion c) throws DuplicateInstanceException, DataException { if(logger.isDebugEnabled()) { logger.debug("Competicion = {}", c); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String queryString = "INSERT INTO COMPETICION(NOMBRE,ID_DEPORTE,FECHA_INICIO, FECHA_FIN) " + "VALUES (?, ?, ?, ?)"; preparedStatement = connection.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS); int i = 1; preparedStatement.setString(i++, c.getNome()); preparedStatement.setLong(i++, c.getIdDeporte()); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaInicio().getYear())); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaFin().getYear())); int insertedRows = preparedStatement.executeUpdate(); if (insertedRows == 0) { throw new SQLException("Can not add row to table 'COMPETICION'"); } resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { Long id = resultSet.getLong(1); c.setIdCompeticion(id); } else { throw new DataException("Unable to fetch autogenerated primary key"); } return c; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public boolean update(Connection connection, Competicion c) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Competicion = {}", c); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String queryString = "UPDATE COMPETICION " + "SET NOMBRE = ?, " + "SET ID_DEPORTE = ?, " + "SET FECHA_INICIO = ?," + "SET FECHA_FIN = ?," + "WHERE ID_COMPETICION=?"; preparedStatement = connection.prepareStatement(queryString); int i = 1; preparedStatement.setString(i++, c.getNome()); preparedStatement.setLong(i++, c.getIdDeporte()); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaInicio().getTime())); preparedStatement.setDate(i++, new java.sql.Date(c.getFechaFin().getTime())); preparedStatement.setLong(i++, c.getIdCompeticion()); int updatedRows = preparedStatement.executeUpdate(); if (updatedRows == 0) { throw new InstanceNotFoundException("Non se atopou competicion: "+c.getIdCompeticion(), Competicion.class.getName()); } if (updatedRows > 1) { throw new SQLException("Duplicate row for id = '" + c.getIdCompeticion() + "' in table 'competicion'"); } else { return true;} //... } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public long delete(Connection connection, Long id) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {} ", id); } PreparedStatement preparedStatement = null; try { String queryString = "DELETE FROM COMPETICION " + "WHERE ID_COMPETICION = ? "; preparedStatement = connection.prepareStatement(queryString); int i = 1; preparedStatement.setLong(i++, id); long removedRows = preparedStatement.executeUpdate(); if (removedRows == 0) { throw new InstanceNotFoundException("Non se atopou competicion: "+id,Competicion.class.getName()); } return removedRows; } catch (SQLException e) { logger.warn(e.getMessage(), e); throw new DataException(e); } finally { JDBCUtils.closeStatement(preparedStatement); } } @Override public Competicion findById(Connection connection, Long id) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {}", id); } Competicion c = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION,NOMBRE,ID_DEPORTE,FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION " +"WHERE ID_COMPETICION = ? "; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setLong(i++, id); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set if (resultSet.next()) { c = loadNext(connection,resultSet); //System.out.println("Cargado "+u); } else { throw new InstanceNotFoundException("Non se atopou competicion con id = "+id, Competicion.class.getName()); } } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } return c; } @Override public List<Competicion> findByDeporte(Connection connection, Long id) throws DataException { if(logger.isDebugEnabled()) { logger.debug("Id = {}", id); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION " +"WHERE ID_DEPORTE = ? "; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setLong(i++, id); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c= null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public List<Competicion> findAll(Connection connection) throws DataException { PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +"FROM COMPETICION"; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c = null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public List<Competicion> findByNombre(Connection connection, String nome) throws DataException { if(logger.isDebugEnabled()) { logger.debug("Nome = {}", nome); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ String sql; sql = "SELECT ID_COMPETICION, NOMBRE, ID_DEPORTE, FECHA_INICIO, FECHA_FIN " +" FROM COMPETICION " +" WHERE " +" UPPER(NOMBRE) LIKE ?"; preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parámetros int i = 1; preparedStatement.setString(i++, "%"+nome.toUpperCase()+"%"); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Competicion> results = new ArrayList<Competicion>(); Competicion c = null; while(resultSet.next()) { c = loadNext(connection,resultSet); results.add(c); } return results; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } private Competicion loadNext(Connection connection, ResultSet resultSet) throws SQLException{ Competicion c = new Competicion(); int i = 1; Long idCompeticion = resultSet.getLong(i++); String nome = resultSet.getString(i++); Long idDeporte = resultSet.getLong(i++); Date fechaInicio = resultSet.getDate(i++); Date fechaFin = resultSet.getDate(i++); c.setIdCompeticion(idCompeticion); c.setNome(nome); c.setIdDeporte(idDeporte); c.setFechaInicio(fechaInicio); c.setFechaFin(fechaFin); return c; } }
10,138
0.660089
0.658313
365
25.767124
27.462612
121
false
false
0
0
0
0
0
0
2.630137
false
false
8
f1b41a31899b9c291dac59ed559e01141a05fc51
13,297,218,790,407
59bf6993d74d8576e7459e08c45b4e8ec872675f
/EgenBeChallenge/src/main/java/com/egen/user/controller/UserSparkController.java
981c99244e056440a1f9bcc987d256f408970f7d
[]
no_license
susmithakota/egen-be-challenge
https://github.com/susmithakota/egen-be-challenge
2605b9f5ba4f21767676ea4a3fe0998e1189fc3f
8325c25b7e85c8517a81aca037cd7e0d520a4006
refs/heads/master
2021-01-01T03:39:39.502000
2016-04-18T01:48:06
2016-04-18T01:48:06
56,464,005
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.egen.user.controller; import spark.Spark; import com.egen.user.service.UserService; import com.egen.util.JacksonUtil; public class UserSparkController { private static final int HTTP_BAD_REQUEST = 404; private static final int HTTP_GOOD_RESPONSE = 200; public static void main(String[] args) { // To get all users Spark.get("/user", (request, response) -> { response.status(HTTP_GOOD_RESPONSE); response.type("application/json"); return new UserService().getUsers(); }); // To insert user Spark.post("/user", (request, response) -> { response.type("application/json"); response.status(HTTP_GOOD_RESPONSE); return new UserService().createUser(JacksonUtil .jsonToObject(request.body())); }); // To update user Spark.put( "/user", (request, response) -> { String result = new UserService().updateUser(JacksonUtil .jsonToObject(request.body())); response.type("application/json"); if (result.equalsIgnoreCase("success")) { response.status(HTTP_GOOD_RESPONSE); return "User updated successfully"; } else { response.status(HTTP_BAD_REQUEST); return "Failed to update ,user not found."; } }); } }
UTF-8
Java
1,279
java
UserSparkController.java
Java
[]
null
[]
package com.egen.user.controller; import spark.Spark; import com.egen.user.service.UserService; import com.egen.util.JacksonUtil; public class UserSparkController { private static final int HTTP_BAD_REQUEST = 404; private static final int HTTP_GOOD_RESPONSE = 200; public static void main(String[] args) { // To get all users Spark.get("/user", (request, response) -> { response.status(HTTP_GOOD_RESPONSE); response.type("application/json"); return new UserService().getUsers(); }); // To insert user Spark.post("/user", (request, response) -> { response.type("application/json"); response.status(HTTP_GOOD_RESPONSE); return new UserService().createUser(JacksonUtil .jsonToObject(request.body())); }); // To update user Spark.put( "/user", (request, response) -> { String result = new UserService().updateUser(JacksonUtil .jsonToObject(request.body())); response.type("application/json"); if (result.equalsIgnoreCase("success")) { response.status(HTTP_GOOD_RESPONSE); return "User updated successfully"; } else { response.status(HTTP_BAD_REQUEST); return "Failed to update ,user not found."; } }); } }
1,279
0.641908
0.637217
50
23.58
19.129129
61
false
false
0
0
0
0
0
0
2.86
false
false
8
cf299267096bc5d17c8050119b7540b850ac4f61
2,972,117,414,540
a23b277bd41edbf569437bdfedad22c2d7733dbe
/acm/P1192__Optimal_Connective_Subset/Main.java
ec3e80c7b9dad9f075793bbb06c8e2369adac648
[]
no_license
alexandrofernando/java
https://github.com/alexandrofernando/java
155ed38df33ae8dae641d327be3c6c355b28082a
a783407eaba29a88123152dd5b2febe10eb7bf1d
refs/heads/master
2021-01-17T06:49:57.241000
2019-07-19T11:34:44
2019-07-19T11:34:44
52,783,678
1
0
null
false
2017-07-03T21:46:00
2016-02-29T10:38:28
2016-03-06T20:47:46
2017-07-03T21:45:54
2,202
0
0
1
Java
null
null
package P1192__Optimal_Connective_Subset; import java.util.Scanner; import java.io.File; import java.util.TreeMap; /** * <p>Title: </p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2005</p> * * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class Main { static int max; static TreeMap<Point, Integer> map; public static void main(String[] args) throws Exception { Scanner cin = new Scanner(System.in); int N = cin.nextInt(); map = new TreeMap<Point, Integer> (); for (int i = 0; i < N; i++) { map.put(new Point(cin.nextInt(), cin.nextInt()), cin.nextInt()); } max = -100000; search(map.firstKey(), (int) 1E7, (int) 1E7); System.out.println(max); } static int search(Point point, int fromX, int fromY) { int sum = map.get(point); int offsetX[] = { -1, 0, 1, 0}; int offsetY[] = { 0, 1, 0, -1}; int add = 0; for (int i = 0; i < 4; i++) { int nextX = point.x + offsetX[i]; int nextY = point.y + offsetY[i]; if (nextX != fromX || nextY != fromY) { Point nextPoint = new Point(nextX, nextY); if (map.containsKey(nextPoint) == true) { int temp = search(nextPoint, point.x, point.y); if (temp > 0) { add += temp; } } } } sum += add; if (sum > max) { max = sum; } return sum; } } class Point implements Comparable<Point> { int x; int y; public Point(int X, int Y) { this.x = X; this.y = Y; } public int compareTo(Point another) { if (this.x != another.x) { return this.x - another.x; } else { return this.y - another.y; } } }
UTF-8
Java
1,966
java
Main.java
Java
[]
null
[]
package P1192__Optimal_Connective_Subset; import java.util.Scanner; import java.io.File; import java.util.TreeMap; /** * <p>Title: </p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2005</p> * * <p>Company: </p> * * @author not attributable * @version 1.0 */ public class Main { static int max; static TreeMap<Point, Integer> map; public static void main(String[] args) throws Exception { Scanner cin = new Scanner(System.in); int N = cin.nextInt(); map = new TreeMap<Point, Integer> (); for (int i = 0; i < N; i++) { map.put(new Point(cin.nextInt(), cin.nextInt()), cin.nextInt()); } max = -100000; search(map.firstKey(), (int) 1E7, (int) 1E7); System.out.println(max); } static int search(Point point, int fromX, int fromY) { int sum = map.get(point); int offsetX[] = { -1, 0, 1, 0}; int offsetY[] = { 0, 1, 0, -1}; int add = 0; for (int i = 0; i < 4; i++) { int nextX = point.x + offsetX[i]; int nextY = point.y + offsetY[i]; if (nextX != fromX || nextY != fromY) { Point nextPoint = new Point(nextX, nextY); if (map.containsKey(nextPoint) == true) { int temp = search(nextPoint, point.x, point.y); if (temp > 0) { add += temp; } } } } sum += add; if (sum > max) { max = sum; } return sum; } } class Point implements Comparable<Point> { int x; int y; public Point(int X, int Y) { this.x = X; this.y = Y; } public int compareTo(Point another) { if (this.x != another.x) { return this.x - another.x; } else { return this.y - another.y; } } }
1,966
0.470498
0.453713
79
23.886076
18.018969
76
false
false
0
0
0
0
0
0
0.696203
false
false
8
fdfa92158050c4a6b1a0df7feb1609902dd26a61
19,980,187,898,953
fc78d615949794fdfb54d359d4b26fd54ed610ac
/core/src/main/java/tachyon/client/table/RawColumn.java
e46287f058ad2d06fc62c1a55b86682f130ff8f6
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
mtunique/tachyon-rdma
https://github.com/mtunique/tachyon-rdma
76fb0ac6524b7e53a88df66d77d26220a4066843
b79cb19c2895d859384aa3aa3f3f11d1aed20e28
refs/heads/master
2022-10-18T07:45:24.482000
2021-04-27T02:29:54
2021-04-27T02:29:54
25,732,604
7
2
Apache-2.0
false
2022-10-05T02:34:25
2014-10-25T13:38:43
2021-04-27T02:29:57
2022-10-05T02:34:24
865
5
2
1
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tachyon.client.table; import java.io.IOException; import tachyon.client.TachyonFS; import tachyon.client.TachyonFile; import tachyon.master.MasterInfo; import tachyon.util.CommonUtils; /** * The column of a <code>RawTable</code>. */ public class RawColumn { private final TachyonFS TFS; private final RawTable RAW_TABLE; private final int COLUMN_INDEX; /** * @param tachyonClient * @param rawTable * @param columnIndex */ RawColumn(TachyonFS tachyonClient, RawTable rawTable, int columnIndex) { TFS = tachyonClient; RAW_TABLE = rawTable; COLUMN_INDEX = columnIndex; } // TODO creating file here should be based on id. public boolean createPartition(int pId) throws IOException { return TFS.createFile(CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX, pId)) > 0; } // TODO creating file here should be based on id. public TachyonFile getPartition(int pId) throws IOException { return getPartition(pId, false); } // TODO creating file here should be based on id. public TachyonFile getPartition(int pId, boolean cachedMetadata) throws IOException { return TFS.getFile( CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX, pId), cachedMetadata); } // TODO creating file here should be based on id. public int partitions() throws IOException { return TFS.getNumberOfFiles(CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX)); } }
UTF-8
Java
2,300
java
RawColumn.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tachyon.client.table; import java.io.IOException; import tachyon.client.TachyonFS; import tachyon.client.TachyonFile; import tachyon.master.MasterInfo; import tachyon.util.CommonUtils; /** * The column of a <code>RawTable</code>. */ public class RawColumn { private final TachyonFS TFS; private final RawTable RAW_TABLE; private final int COLUMN_INDEX; /** * @param tachyonClient * @param rawTable * @param columnIndex */ RawColumn(TachyonFS tachyonClient, RawTable rawTable, int columnIndex) { TFS = tachyonClient; RAW_TABLE = rawTable; COLUMN_INDEX = columnIndex; } // TODO creating file here should be based on id. public boolean createPartition(int pId) throws IOException { return TFS.createFile(CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX, pId)) > 0; } // TODO creating file here should be based on id. public TachyonFile getPartition(int pId) throws IOException { return getPartition(pId, false); } // TODO creating file here should be based on id. public TachyonFile getPartition(int pId, boolean cachedMetadata) throws IOException { return TFS.getFile( CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX, pId), cachedMetadata); } // TODO creating file here should be based on id. public int partitions() throws IOException { return TFS.getNumberOfFiles(CommonUtils.concat(RAW_TABLE.getPath(), MasterInfo.COL + COLUMN_INDEX)); } }
2,300
0.736087
0.733913
66
33.848484
27.896585
96
false
false
0
0
0
0
0
0
0.469697
false
false
8
f36d0472eaa41b85f9b10536970c165b4e29c8c0
171,798,738,214
0d1ab7114a4cd83fbcf1f1efc77b69c95809402d
/src/com/company/Main.java
ebb5799d6afa9b75a81cc6e35fec3d620ae82128
[]
no_license
VeraMG98/RPGGameLasson_5
https://github.com/VeraMG98/RPGGameLasson_5
811cdfcc7f93f4409f94e4f30ad68993982942e8
b28fe74896da6e983c7b89dc8a190644e9632fe9
refs/heads/master
2022-12-19T01:37:13.613000
2020-09-22T13:42:32
2020-09-22T13:42:32
296,837,979
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; public class Main { public static void main(String[] args) { BossClass boss = new BossClass(); boss.setHealth(500); boss.setDamage(50); Weapon bossWeapon = new Weapon(); bossWeapon.setNameWeapon("Sword"); bossWeapon.setTypeWeapon("Physical"); boss.setWeapon(bossWeapon); System.out.println("Boss health " + boss.getHealth() + ", damage " + boss.getDamage() + ", weapon " + boss.getWeapon().getNameWeapon() + " " + boss.getWeapon().getTypeWeapon()); /*bossCreate(); Hero[] heroes = heroCreate(); for (Hero hero : heroes) { System.out.println(hero.getHealth() + " " + hero.getDamage() + " " + hero.getAttackType()); }*/ } /*public static Hero[] heroCreate() { Hero firstHero = new Hero(260, 20, "Physical"); Hero secondHero = new Hero(250, 25, "Magical"); Hero thirdHero = new Hero(200, 0); return new Hero[] {firstHero, secondHero, thirdHero}; } public static void bossCreate() { Boss firstBoss = new Boss(); firstBoss.setHealth(1000); firstBoss.setDamage(50); firstBoss.setProtectionType(""); System.out.println("Boss health " + firstBoss.getHealth() + ", damage " + firstBoss.getDamage() + ", protection " + firstBoss.getProtectionType()); }*/ }
UTF-8
Java
1,444
java
Main.java
Java
[]
null
[]
package com.company; public class Main { public static void main(String[] args) { BossClass boss = new BossClass(); boss.setHealth(500); boss.setDamage(50); Weapon bossWeapon = new Weapon(); bossWeapon.setNameWeapon("Sword"); bossWeapon.setTypeWeapon("Physical"); boss.setWeapon(bossWeapon); System.out.println("Boss health " + boss.getHealth() + ", damage " + boss.getDamage() + ", weapon " + boss.getWeapon().getNameWeapon() + " " + boss.getWeapon().getTypeWeapon()); /*bossCreate(); Hero[] heroes = heroCreate(); for (Hero hero : heroes) { System.out.println(hero.getHealth() + " " + hero.getDamage() + " " + hero.getAttackType()); }*/ } /*public static Hero[] heroCreate() { Hero firstHero = new Hero(260, 20, "Physical"); Hero secondHero = new Hero(250, 25, "Magical"); Hero thirdHero = new Hero(200, 0); return new Hero[] {firstHero, secondHero, thirdHero}; } public static void bossCreate() { Boss firstBoss = new Boss(); firstBoss.setHealth(1000); firstBoss.setDamage(50); firstBoss.setProtectionType(""); System.out.println("Boss health " + firstBoss.getHealth() + ", damage " + firstBoss.getDamage() + ", protection " + firstBoss.getProtectionType()); }*/ }
1,444
0.569252
0.551939
42
33.380951
25.608734
105
false
false
0
0
0
0
0
0
0.785714
false
false
8
3090dde9a17af568a48c7899e3aa5a4f37f32959
9,302,899,202,933
386a506d73c820c32c4684f4eedd65e81de1c192
/FootballTime/app/src/main/java/com/gameloft/footballtime/tab/TabLeague1Fixtures.java
61b2c0ee958e94799212a24df9939d6159055534
[]
no_license
chehuy97/FootballTime
https://github.com/chehuy97/FootballTime
16225422b896dabf55fab05279c9451394d6b72a
7f96072b6373baf839f44624b8a1e9a897776789
refs/heads/master
2020-04-04T10:09:35.139000
2018-11-02T09:36:16
2018-11-02T09:36:16
155,844,463
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gameloft.footballtime.tab; public class TabLeague1Fixtures extends TabBaseFixtures{ @Override public void setUrl() { super.setUrl(); changeUrl("http://api.football-data.org/v1/competitions/450/fixtures"); } }
UTF-8
Java
249
java
TabLeague1Fixtures.java
Java
[]
null
[]
package com.gameloft.footballtime.tab; public class TabLeague1Fixtures extends TabBaseFixtures{ @Override public void setUrl() { super.setUrl(); changeUrl("http://api.football-data.org/v1/competitions/450/fixtures"); } }
249
0.702811
0.682731
9
26.777779
25.314808
79
false
false
0
0
0
0
0
0
0.333333
false
false
8
ad6d2a5e285f5c64de9f77589117b494770e0be7
17,867,064,011,099
720a0bbdf479c818d764b73f0f006ba94638384d
/src/main/java/com/sams/demo/model/response/ResponseBuilder.java
340546612f5a24eb8e478586d0911677f8b3a941
[]
no_license
KyntsevichVova/sams-demo
https://github.com/KyntsevichVova/sams-demo
8ee47dfb0f049945751a0301b32da14a60a5da21
65b6a74c18f84103bf7f5220574aa0a9cdeca2d1
refs/heads/master
2022-01-29T04:51:03.681000
2020-01-10T07:29:46
2020-01-10T07:29:46
215,508,955
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sams.demo.model.response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sams.demo.model.dto.BaseDTO; import com.sams.demo.model.entity.BaseEntity; import com.sams.demo.model.error.ErrorMessage; import com.sams.demo.model.mapper.IDTOMapper; import lombok.Data; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; import static com.sams.demo.model.response.enums.ResponseStatus.FAILURE; import static com.sams.demo.model.response.enums.ResponseStatus.SUCCESS; @Data public class ResponseBuilder<DTO extends BaseDTO, ENTITY extends BaseEntity> { private SamsDemoResponse<DTO> response; private HttpHeaders headers; private HttpStatus httpStatus; private ResponseBuilder() { this.headers = new HttpHeaders(); } private ResponseBuilder(SamsDemoResponse<DTO> response) { this(); this.response = response; } @SuppressWarnings("unchecked") public static ResponseBuilder failure() { SamsDemoResponse response = new SamsDemoResponse<>(FAILURE); return new ResponseBuilder(response); } public static <DTO extends BaseDTO, ENTITY extends BaseEntity> ResponseBuilder<DTO, ENTITY> success() { SamsDemoResponse<DTO> response = new SamsDemoResponse<>(SUCCESS); return new ResponseBuilder<>(response); } public static ResponseBuilder empty() { return new ResponseBuilder(); } public ResponseBuilder<DTO, ENTITY> withPageData(Page<DTO> page) { this.response.setData(page.getContent()); this.response.setTotal(page.getTotalElements()); return this; } public ResponseBuilder<DTO, ENTITY> withPageData(Page<ENTITY> page, IDTOMapper<DTO, ENTITY> mapper) { this.response.setData(mapper.mapToDTOList(page.getContent())); this.response.setTotal(page.getTotalElements()); return this; } public ResponseBuilder<DTO, ENTITY> withData(List<ENTITY> list, IDTOMapper<DTO, ENTITY> mapper) { this.response.setData(mapper.mapToDTOList(list)); this.response.setTotal((long) list.size()); return this; } public ResponseBuilder withErrorMessage(List<ErrorMessage> errors) { this.response.setErrorData(errors); return this; } public ResponseBuilder withLocation(String path, Long id) { URI location = ServletUriComponentsBuilder .fromCurrentServletMapping() .path(path) .build() .expand(id) .toUri(); this.headers.setLocation(location); return this; } public ResponseBuilder withAuthorization(String token) { this.headers.setBearerAuth(token); return this; } public ResponseBuilder<DTO, ENTITY> withHttpStatus(HttpStatus httpStatus) { this.httpStatus = httpStatus; return this; } public ResponseEntity<SamsDemoResponse<DTO>> build() { return new ResponseEntity<>(this.response, this.headers, this.httpStatus); } public String toJson() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(this.build().getBody()); } }
UTF-8
Java
3,562
java
ResponseBuilder.java
Java
[]
null
[]
package com.sams.demo.model.response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sams.demo.model.dto.BaseDTO; import com.sams.demo.model.entity.BaseEntity; import com.sams.demo.model.error.ErrorMessage; import com.sams.demo.model.mapper.IDTOMapper; import lombok.Data; import org.springframework.data.domain.Page; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; import static com.sams.demo.model.response.enums.ResponseStatus.FAILURE; import static com.sams.demo.model.response.enums.ResponseStatus.SUCCESS; @Data public class ResponseBuilder<DTO extends BaseDTO, ENTITY extends BaseEntity> { private SamsDemoResponse<DTO> response; private HttpHeaders headers; private HttpStatus httpStatus; private ResponseBuilder() { this.headers = new HttpHeaders(); } private ResponseBuilder(SamsDemoResponse<DTO> response) { this(); this.response = response; } @SuppressWarnings("unchecked") public static ResponseBuilder failure() { SamsDemoResponse response = new SamsDemoResponse<>(FAILURE); return new ResponseBuilder(response); } public static <DTO extends BaseDTO, ENTITY extends BaseEntity> ResponseBuilder<DTO, ENTITY> success() { SamsDemoResponse<DTO> response = new SamsDemoResponse<>(SUCCESS); return new ResponseBuilder<>(response); } public static ResponseBuilder empty() { return new ResponseBuilder(); } public ResponseBuilder<DTO, ENTITY> withPageData(Page<DTO> page) { this.response.setData(page.getContent()); this.response.setTotal(page.getTotalElements()); return this; } public ResponseBuilder<DTO, ENTITY> withPageData(Page<ENTITY> page, IDTOMapper<DTO, ENTITY> mapper) { this.response.setData(mapper.mapToDTOList(page.getContent())); this.response.setTotal(page.getTotalElements()); return this; } public ResponseBuilder<DTO, ENTITY> withData(List<ENTITY> list, IDTOMapper<DTO, ENTITY> mapper) { this.response.setData(mapper.mapToDTOList(list)); this.response.setTotal((long) list.size()); return this; } public ResponseBuilder withErrorMessage(List<ErrorMessage> errors) { this.response.setErrorData(errors); return this; } public ResponseBuilder withLocation(String path, Long id) { URI location = ServletUriComponentsBuilder .fromCurrentServletMapping() .path(path) .build() .expand(id) .toUri(); this.headers.setLocation(location); return this; } public ResponseBuilder withAuthorization(String token) { this.headers.setBearerAuth(token); return this; } public ResponseBuilder<DTO, ENTITY> withHttpStatus(HttpStatus httpStatus) { this.httpStatus = httpStatus; return this; } public ResponseEntity<SamsDemoResponse<DTO>> build() { return new ResponseEntity<>(this.response, this.headers, this.httpStatus); } public String toJson() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(this.build().getBody()); } }
3,562
0.701291
0.701291
124
27.733871
28.113855
107
false
false
0
0
0
0
0
0
0.508065
false
false
8
1c20abd37c911d0ecec0e5080baa67f0b4737af7
32,856,499,852,798
152719eb497f7e330b53c89d023df30c6a26e2b3
/src/main/java/com/example/sports/model/SysUserModule.java
f1714da4796a1e06413266b65294efdbfc57b800
[]
no_license
LukeHJR/sports
https://github.com/LukeHJR/sports
93512117884282e4369f742cfd3dcd8d9d417d22
a401e0e6a1fad185792d7055bb8f6418d463c97e
refs/heads/master
2020-03-15T13:11:43.226000
2018-05-11T03:00:50
2018-05-11T03:00:50
132,160,693
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sports.model; import java.io.Serializable; import java.util.Date; /** * * * @author hjr * @date 2018-04-24 * */ public class SysUserModule implements Serializable { /** */ private Long id; /** 账号id */ private Integer sysUserId; /** 系统模块id */ private Integer sysModuleId; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getSysUserId() { return sysUserId; } public void setSysUserId(Integer sysUserId) { this.sysUserId = sysUserId; } public Integer getSysModuleId() { return sysModuleId; } public void setSysModuleId(Integer sysModuleId) { this.sysModuleId = sysModuleId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", sysUserId=").append(sysUserId); sb.append(", sysModuleId=").append(sysModuleId); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
UTF-8
Java
1,877
java
SysUserModule.java
Java
[ { "context": "ble;\nimport java.util.Date;\n\n/**\n * \n *\n * @author hjr\n * @date 2018-04-24\n *\n */\npublic class SysUserMo", "end": 113, "score": 0.999688982963562, "start": 110, "tag": "USERNAME", "value": "hjr" } ]
null
[]
package com.example.sports.model; import java.io.Serializable; import java.util.Date; /** * * * @author hjr * @date 2018-04-24 * */ public class SysUserModule implements Serializable { /** */ private Long id; /** 账号id */ private Integer sysUserId; /** 系统模块id */ private Integer sysModuleId; /** 创建时间 */ private Date createTime; /** 更新时间 */ private Date updateTime; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getSysUserId() { return sysUserId; } public void setSysUserId(Integer sysUserId) { this.sysUserId = sysUserId; } public Integer getSysModuleId() { return sysModuleId; } public void setSysModuleId(Integer sysModuleId) { this.sysModuleId = sysModuleId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", sysUserId=").append(sysUserId); sb.append(", sysModuleId=").append(sysModuleId); sb.append(", createTime=").append(createTime); sb.append(", updateTime=").append(updateTime); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
1,877
0.599243
0.594375
86
20.511627
18.595289
66
false
false
0
0
0
0
0
0
0.430233
false
false
8
4970b9ea75b738db96a6ba33699b93d09d73037a
2,379,411,929,924
465f86ec62575e5391fb071cbd1d2bdec263aa94
/op/src/main/java/com/zhicall/op/util/shell/SSHCommandExecutor.java
e2ca567e3bc292e823c8b940c8541055e153b716
[]
no_license
LZHICALL/deploy
https://github.com/LZHICALL/deploy
14a5e5cc4c0349c0a5c3b57a9592da5e5a1e59c4
81cb505194562dd5c7a2535d838affc656152506
refs/heads/master
2021-08-29T02:04:57.461000
2017-12-13T11:10:48
2017-12-13T11:10:48
114,110,690
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhicall.op.util.shell; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.springframework.util.StringUtils; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.zhicall.op.entity.Cmd; /** * This class provide interface to execute command on remote Linux. */ public class SSHCommandExecutor { private String ipAddress; private String username; private String password; public static final int DEFAULT_SSH_PORT = 22; private Vector<String> stdout; public SSHCommandExecutor(final String ipAddress, final String username, final String password) { this.ipAddress = ipAddress; this.username = username; this.password = password; stdout = new Vector<String>(); } public int execute(final String command) { int returnCode = 0; JSch jsch = new JSch(); MyUserInfo userInfo = new MyUserInfo(); try { // Create and connect session. Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT); session.setPassword(password); session.setUserInfo(userInfo); session.connect(); // Create and connect channel. Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); // Get the output of remote command. String line; while ((line = input.readLine()) != null) { stdout.add(line); } input.close(); // Get the return code only after the channel is closed. if (channel.isClosed()) { returnCode = channel.getExitStatus(); } // Disconnect the channel and session. channel.disconnect(); session.disconnect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return returnCode; } public Vector<String> getStandardOutput() { return stdout; } public static Cmd exec(String lastPath, String cmd, String ip, String name, String pwd) { Cmd result = new Cmd(); SSHCommandExecutor sshExecutor = new SSHCommandExecutor(ip, name, pwd); StringBuilder builder = new StringBuilder(); if (lastPath != null) { builder.append("cd ").append(lastPath).append(";"); } builder.append(cmd).append(";").append("pwd"); sshExecutor.execute(builder.toString()); Vector<String> stdout = sshExecutor.getStandardOutput(); builder.setLength(0); for (int i = 0; i < stdout.size(); i++) { if (i == stdout.size() - 1) { result.setPath(stdout.get(i)); } else { builder.append(stdout.get(i)).append("<br/>"); } } result.setResult(builder.toString()); result.setRoot(name); result.setCmd(cmd); result.setLastPath(result.getPath()); showls(sshExecutor, lastPath, result); return result; } public static Cmd execLocal(String lastPath, String name, String cmd) { Cmd result = new Cmd(); if (!StringUtils.isEmpty(cmd)) { String results = ShellUtil.exec(cmd); result.setResult(results); } result.setPath(ShellUtil.exec("pwd")); result.setRoot(name); result.setCmd(cmd); result.setLastPath(result.getPath()); // showls(sshExecutor, lastPath, result); return result; } private static void showls(SSHCommandExecutor sshExecutor,String lastPath,Cmd result) { if (lastPath == null) { return; } List<String> list = new ArrayList<>(); StringBuilder builder = new StringBuilder(); builder.append("cd ").append(lastPath).append(";").append("cd ").append(result.getPath()).append(";ls"); sshExecutor.execute(builder.toString()); Vector<String> stdout = sshExecutor.getStandardOutput(); builder.setLength(0); for (String string : stdout) { list.add(string); } result.setFilename(list); } public static void main(final String[] args) { // SSHCommandExecutor sshExecutor = new // SSHCommandExecutor("172.16.10.174", "root", "Isd@2016"); // // sshExecutor.execute("cd /home; pwd ; ls"); // // Vector<String> stdout = sshExecutor.getStandardOutput(); // for (String str : stdout) { // System.out.println(str); // } } }
UTF-8
Java
4,350
java
SSHCommandExecutor.java
Java
[ { "context": " {\n\t\tthis.ipAddress = ipAddress;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t\tstdout = new Vecto", "end": 856, "score": 0.9989786148071289, "start": 848, "tag": "USERNAME", "value": "username" }, { "context": "ess;\n\t\tthis.username = username;...
null
[]
package com.zhicall.op.util.shell; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.springframework.util.StringUtils; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.zhicall.op.entity.Cmd; /** * This class provide interface to execute command on remote Linux. */ public class SSHCommandExecutor { private String ipAddress; private String username; private String password; public static final int DEFAULT_SSH_PORT = 22; private Vector<String> stdout; public SSHCommandExecutor(final String ipAddress, final String username, final String password) { this.ipAddress = ipAddress; this.username = username; this.password = <PASSWORD>; stdout = new Vector<String>(); } public int execute(final String command) { int returnCode = 0; JSch jsch = new JSch(); MyUserInfo userInfo = new MyUserInfo(); try { // Create and connect session. Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT); session.setPassword(<PASSWORD>); session.setUserInfo(userInfo); session.connect(); // Create and connect channel. Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); // Get the output of remote command. String line; while ((line = input.readLine()) != null) { stdout.add(line); } input.close(); // Get the return code only after the channel is closed. if (channel.isClosed()) { returnCode = channel.getExitStatus(); } // Disconnect the channel and session. channel.disconnect(); session.disconnect(); } catch (JSchException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return returnCode; } public Vector<String> getStandardOutput() { return stdout; } public static Cmd exec(String lastPath, String cmd, String ip, String name, String pwd) { Cmd result = new Cmd(); SSHCommandExecutor sshExecutor = new SSHCommandExecutor(ip, name, pwd); StringBuilder builder = new StringBuilder(); if (lastPath != null) { builder.append("cd ").append(lastPath).append(";"); } builder.append(cmd).append(";").append("pwd"); sshExecutor.execute(builder.toString()); Vector<String> stdout = sshExecutor.getStandardOutput(); builder.setLength(0); for (int i = 0; i < stdout.size(); i++) { if (i == stdout.size() - 1) { result.setPath(stdout.get(i)); } else { builder.append(stdout.get(i)).append("<br/>"); } } result.setResult(builder.toString()); result.setRoot(name); result.setCmd(cmd); result.setLastPath(result.getPath()); showls(sshExecutor, lastPath, result); return result; } public static Cmd execLocal(String lastPath, String name, String cmd) { Cmd result = new Cmd(); if (!StringUtils.isEmpty(cmd)) { String results = ShellUtil.exec(cmd); result.setResult(results); } result.setPath(ShellUtil.exec("pwd")); result.setRoot(name); result.setCmd(cmd); result.setLastPath(result.getPath()); // showls(sshExecutor, lastPath, result); return result; } private static void showls(SSHCommandExecutor sshExecutor,String lastPath,Cmd result) { if (lastPath == null) { return; } List<String> list = new ArrayList<>(); StringBuilder builder = new StringBuilder(); builder.append("cd ").append(lastPath).append(";").append("cd ").append(result.getPath()).append(";ls"); sshExecutor.execute(builder.toString()); Vector<String> stdout = sshExecutor.getStandardOutput(); builder.setLength(0); for (String string : stdout) { list.add(string); } result.setFilename(list); } public static void main(final String[] args) { // SSHCommandExecutor sshExecutor = new // SSHCommandExecutor("172.16.10.174", "root", "<PASSWORD>"); // // sshExecutor.execute("cd /home; pwd ; ls"); // // Vector<String> stdout = sshExecutor.getStandardOutput(); // for (String str : stdout) { // System.out.println(str); // } } }
4,356
0.696322
0.691494
167
25.053892
22.50835
106
false
false
0
0
0
0
0
0
2.251497
false
false
8
e72650a5d3896f28e38edb52298901414481373d
283,467,907,870
f361844c6090b0ce789066880b4c7e47dfb983f2
/bitTools/DynamicStats.java
ec3720fbb7283ff269332c424854dc75005cec20
[]
no_license
diogo-p-nunes/cnv-project
https://github.com/diogo-p-nunes/cnv-project
aaf95169c0f6c249fbc98211efee8b9674f0e58e
fb227cb01b3f8b1dbc21711e5ee635b9ef19b83d
refs/heads/master
2020-05-22T05:24:12.325000
2019-05-19T11:58:08
2019-05-19T11:58:08
186,234,820
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // StatisticsTool.java // // This program measures and instruments to obtain different statistics // about Java programs. // // Copyright (c) 1998 by Han B. Lee (hanlee@cs.colorado.edu). // ALL RIGHTS RESERVED. // // Permission to use, copy, modify, and distribute this software and its // documentation for non-commercial purposes is hereby granted provided // that this copyright notice appears in all copies. // // This software is provided "as is". The licensor makes no warrenties, either // expressed or implied, about its correctness or performance. The licensor // shall not be liable for any damages suffered as a result of using // and modifying this software. import BIT.highBIT.*; import java.io.File; import java.util.Enumeration; import java.util.Vector; import org.apache.commons.lang3.StringUtils; import java.io.FileWriter; import java.io.BufferedWriter; public class DynamicStats { private static double dyn_method_count = 0; private static double dyn_bb_count = 0; private static double dyn_instr_count = 0; private static String cnvProject = "$HOME/cnv-project/metrics"; private static String metricsOutputFile = "dynamicStats_metrics.txt"; public static void writeMetricsToFile(double[] metrics) { /* * Function that receives an array of metrics, transforms into string * and writes them in one line * separated by "|", to the metrics file */ String metricsString = doubleToStringArray(metrics); BufferedWriter outputMetrics = null; try { FileWriter fstream = new FileWriter(cnvProject + "/" + metricsOutputFile, true); //true tells to append data. outputMetrics = new BufferedWriter(fstream); outputMetrics.write(metricsString); outputMetrics.close(); System.out.println("Stored metrics in: " + cnvProject + "/" + metricsOutputFile); return; } catch (Exception e) { System.out.println(e.getMessage()); } } public static String doubleToStringArray(double[] in) { int size = in.length; String[] out = new String[size]; for(int i=0; i<size; i++) { out[i] = "" + in[i]; } return StringUtils.join(out, "|") + "\n"; } public static void doDynamic(File in_dir, File out_dir) { /* * Obtem dados similares aos da static tool, sendo que a diferenca esta no facto de estes serem * obtidos dinamicamente. Isto significa que a static tool iria considerar (por exemplo) todos os BB * do ficheiro .class, indiferentemente do facto de esse BB ser executado ou nao. A dynamic tool adiciona * codigo de instrumentacao ANTES da chamada de (por exemplo) cada metodo para incrementar o numero de method * calls dinamicamente. Ora, se um metodo nunca e executado aquando da execucao do ficheiro .class, entao * o codigo de instrumentacao tambem nao sera, e o contador nao ira contabilizar - que 3 exatamente * o comportamento pretendido para esta ferramenta. * * * A dynamic tool tem a particularidade (em comparacao com a static tool) de no final de todos os metodos * (ou routines) adicionar uma invocacao a um metodo de instrumentacao que imprime os resultados de analise * para o stdout. */ String filelist[] = in_dir.list(); for (int i = 0; i < filelist.length; i++) { String filename = filelist[i]; if (filename.endsWith(".class")) { String in_filename = in_dir.getAbsolutePath() + System.getProperty("file.separator") + filename; String out_filename = out_dir.getAbsolutePath() + System.getProperty("file.separator") + filename; ClassInfo ci = new ClassInfo(in_filename); for (Enumeration e = ci.getRoutines().elements(); e.hasMoreElements(); ) { Routine routine = (Routine) e.nextElement(); routine.addBefore("DynamicStats", "dynMethodCount", new Integer(1)); for (Enumeration b = routine.getBasicBlocks().elements(); b.hasMoreElements(); ) { BasicBlock bb = (BasicBlock) b.nextElement(); bb.addBefore("DynamicStats", "dynInstrCount", new Integer(bb.size())); } } ci.addAfter("DynamicStats", "printDynamic", "null"); ci.write(out_filename); } } } public static synchronized void printDynamic(String foo) { if (dyn_method_count == 0) { double[] metrics = { dyn_method_count, dyn_bb_count, dyn_instr_count}; writeMetricsToFile(metrics); return; } float instr_per_bb = (float) dyn_instr_count / (float) dyn_bb_count; float instr_per_method = (float) dyn_instr_count / (float) dyn_method_count; float bb_per_method = (float) dyn_bb_count / (float) dyn_method_count; double[] metrics = { dyn_method_count, dyn_bb_count, dyn_instr_count, instr_per_bb, instr_per_method, bb_per_method}; writeMetricsToFile(metrics); } public static synchronized void dynInstrCount(int incr) { dyn_instr_count += incr; dyn_bb_count++; } public static synchronized void dynMethodCount(int incr) { dyn_method_count++; } public static void main(String argv[]) throws Exception { if (argv.length != 2) { System.exit(-1); } try { File in_dir = new File(argv[0]); File out_dir = new File(argv[1]); if (in_dir.isDirectory() && out_dir.isDirectory()) { doDynamic(in_dir, out_dir); } else { System.exit(-1); } } catch (NullPointerException e) { System.exit(-1); } } }
UTF-8
Java
6,010
java
DynamicStats.java
Java
[ { "context": "/ about Java programs.\n//\n// Copyright (c) 1998 by Han B. Lee (hanlee@cs.colorado.edu).\n// ALL RIGHTS RESERVED.", "end": 163, "score": 0.9998683333396912, "start": 153, "tag": "NAME", "value": "Han B. Lee" }, { "context": "programs.\n//\n// Copyright (c) 1998 by Han ...
null
[]
// // StatisticsTool.java // // This program measures and instruments to obtain different statistics // about Java programs. // // Copyright (c) 1998 by <NAME> (<EMAIL>). // ALL RIGHTS RESERVED. // // Permission to use, copy, modify, and distribute this software and its // documentation for non-commercial purposes is hereby granted provided // that this copyright notice appears in all copies. // // This software is provided "as is". The licensor makes no warrenties, either // expressed or implied, about its correctness or performance. The licensor // shall not be liable for any damages suffered as a result of using // and modifying this software. import BIT.highBIT.*; import java.io.File; import java.util.Enumeration; import java.util.Vector; import org.apache.commons.lang3.StringUtils; import java.io.FileWriter; import java.io.BufferedWriter; public class DynamicStats { private static double dyn_method_count = 0; private static double dyn_bb_count = 0; private static double dyn_instr_count = 0; private static String cnvProject = "$HOME/cnv-project/metrics"; private static String metricsOutputFile = "dynamicStats_metrics.txt"; public static void writeMetricsToFile(double[] metrics) { /* * Function that receives an array of metrics, transforms into string * and writes them in one line * separated by "|", to the metrics file */ String metricsString = doubleToStringArray(metrics); BufferedWriter outputMetrics = null; try { FileWriter fstream = new FileWriter(cnvProject + "/" + metricsOutputFile, true); //true tells to append data. outputMetrics = new BufferedWriter(fstream); outputMetrics.write(metricsString); outputMetrics.close(); System.out.println("Stored metrics in: " + cnvProject + "/" + metricsOutputFile); return; } catch (Exception e) { System.out.println(e.getMessage()); } } public static String doubleToStringArray(double[] in) { int size = in.length; String[] out = new String[size]; for(int i=0; i<size; i++) { out[i] = "" + in[i]; } return StringUtils.join(out, "|") + "\n"; } public static void doDynamic(File in_dir, File out_dir) { /* * Obtem dados similares aos da static tool, sendo que a diferenca esta no facto de estes serem * obtidos dinamicamente. Isto significa que a static tool iria considerar (por exemplo) todos os BB * do ficheiro .class, indiferentemente do facto de esse BB ser executado ou nao. A dynamic tool adiciona * codigo de instrumentacao ANTES da chamada de (por exemplo) cada metodo para incrementar o numero de method * calls dinamicamente. Ora, se um metodo nunca e executado aquando da execucao do ficheiro .class, entao * o codigo de instrumentacao tambem nao sera, e o contador nao ira contabilizar - que 3 exatamente * o comportamento pretendido para esta ferramenta. * * * A dynamic tool tem a particularidade (em comparacao com a static tool) de no final de todos os metodos * (ou routines) adicionar uma invocacao a um metodo de instrumentacao que imprime os resultados de analise * para o stdout. */ String filelist[] = in_dir.list(); for (int i = 0; i < filelist.length; i++) { String filename = filelist[i]; if (filename.endsWith(".class")) { String in_filename = in_dir.getAbsolutePath() + System.getProperty("file.separator") + filename; String out_filename = out_dir.getAbsolutePath() + System.getProperty("file.separator") + filename; ClassInfo ci = new ClassInfo(in_filename); for (Enumeration e = ci.getRoutines().elements(); e.hasMoreElements(); ) { Routine routine = (Routine) e.nextElement(); routine.addBefore("DynamicStats", "dynMethodCount", new Integer(1)); for (Enumeration b = routine.getBasicBlocks().elements(); b.hasMoreElements(); ) { BasicBlock bb = (BasicBlock) b.nextElement(); bb.addBefore("DynamicStats", "dynInstrCount", new Integer(bb.size())); } } ci.addAfter("DynamicStats", "printDynamic", "null"); ci.write(out_filename); } } } public static synchronized void printDynamic(String foo) { if (dyn_method_count == 0) { double[] metrics = { dyn_method_count, dyn_bb_count, dyn_instr_count}; writeMetricsToFile(metrics); return; } float instr_per_bb = (float) dyn_instr_count / (float) dyn_bb_count; float instr_per_method = (float) dyn_instr_count / (float) dyn_method_count; float bb_per_method = (float) dyn_bb_count / (float) dyn_method_count; double[] metrics = { dyn_method_count, dyn_bb_count, dyn_instr_count, instr_per_bb, instr_per_method, bb_per_method}; writeMetricsToFile(metrics); } public static synchronized void dynInstrCount(int incr) { dyn_instr_count += incr; dyn_bb_count++; } public static synchronized void dynMethodCount(int incr) { dyn_method_count++; } public static void main(String argv[]) throws Exception { if (argv.length != 2) { System.exit(-1); } try { File in_dir = new File(argv[0]); File out_dir = new File(argv[1]); if (in_dir.isDirectory() && out_dir.isDirectory()) { doDynamic(in_dir, out_dir); } else { System.exit(-1); } } catch (NullPointerException e) { System.exit(-1); } } }
5,991
0.611148
0.607987
154
38.025974
33.753876
121
false
false
0
0
0
0
0
0
0.597403
false
false
8
5a55068968b1bbfc53a5c024c3e081b5e03b70a9
1,881,195,733,586
8dafaa95a736c07ac717d6ef640874ac2730570c
/app/src/main/java/com/gs/rxjavaexample/MainActivity.java
c769bc79ec887aa961eb903f327d91ad84c8e252
[ "MIT" ]
permissive
ghanshyam34/RxJavaExample
https://github.com/ghanshyam34/RxJavaExample
24c320c5ed1786152abc221500ea0e4589cc2c82
9bd72e96c1a4e0aea59d4786a6cdc89092ab6c08
refs/heads/master
2022-03-22T07:37:46.982000
2019-11-15T15:49:26
2019-11-15T15:49:26
221,397,995
0
0
null
false
2019-11-15T15:31:22
2019-11-13T07:26:20
2019-11-15T15:28:21
2019-11-15T15:31:11
127
0
0
0
Java
false
false
package com.gs.rxjavaexample; import android.os.Bundle; import com.gs.rxjavaexample.base.BaseActivity; import com.gs.rxjavaexample.model.TestApi; import com.gs.rxjavaexample.remote.ApiResponseListener; import com.gs.rxjavaexample.utils.Logger; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); callApi(); } public void callApi(){ new TestApi().callApi(new ApiResponseListener() { @Override public void onSuccess(Object response) { Logger.i("response_success",""+response); } @Override public void onFaillure(String response) { Logger.i("response_faillure",""+response); } }); } }
UTF-8
Java
887
java
MainActivity.java
Java
[]
null
[]
package com.gs.rxjavaexample; import android.os.Bundle; import com.gs.rxjavaexample.base.BaseActivity; import com.gs.rxjavaexample.model.TestApi; import com.gs.rxjavaexample.remote.ApiResponseListener; import com.gs.rxjavaexample.utils.Logger; public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); callApi(); } public void callApi(){ new TestApi().callApi(new ApiResponseListener() { @Override public void onSuccess(Object response) { Logger.i("response_success",""+response); } @Override public void onFaillure(String response) { Logger.i("response_faillure",""+response); } }); } }
887
0.64487
0.64487
31
27.612904
21.136541
58
false
false
0
0
0
0
0
0
0.451613
false
false
8
f7872b274ee555c90426e48aeb0aa422c92f5512
31,937,376,855,214
97491d299346ae911afcf333df7acae22091ef93
/src/java/test/edu/cmu/ml/proppr/prove/QueryParserTest.java
f0ee8c1014acfdef8530636680b40dfabc52fd07
[ "Apache-2.0" ]
permissive
TeamCohen/ProPPR
https://github.com/TeamCohen/ProPPR
0212062f67a8060a2b4e2645ffbd8c99f02f7403
2e0d978f96c2377ef3d26b80c17f38d2804f496c
refs/heads/working
2021-01-09T21:31:58.269000
2017-11-04T02:59:58
2017-11-04T02:59:58
15,980,440
142
52
null
false
2015-10-07T16:51:57
2014-01-16T20:45:50
2015-09-30T07:12:57
2015-10-07T16:51:56
62,294
48
26
0
Java
null
null
package edu.cmu.ml.proppr.prove; import static org.junit.Assert.*; import org.junit.Test; import edu.cmu.ml.proppr.prove.wam.ConstantArgument; import edu.cmu.ml.proppr.prove.wam.Query; import edu.cmu.ml.proppr.prove.wam.VariableArgument; public class QueryParserTest { public void checkTo0(Query q) { assertEquals("query length",1,q.getRhs().length); assertEquals("head functor","bob",q.getRhs()[0].getFunctor()); } @Test public void testArity0() { Query q = Query.parse("bob"); checkTo0(q); assertEquals("head arity",0,q.getRhs()[0].getArity()); } @Test public void testArity1() { Query q = Query.parse("bob(joe)"); System.out.println(q); checkTo0(q); assertEquals("head arity",1,q.getRhs()[0].getArity()); assertEquals("head arg0",new ConstantArgument("joe"),q.getRhs()[0].getArg(0)); } @Test public void testArity2() { Query q = Query.parse("bob(joe,X)"); q.variabilize(); System.out.println(q); checkTo0(q); assertEquals("head arity",2,q.getRhs()[0].getArity()); assertEquals("head arg0",new ConstantArgument("joe"),q.getRhs()[0].getArg(0)); assertEquals("head arg1",new VariableArgument(-1),q.getRhs()[0].getArg(1)); } }
UTF-8
Java
1,182
java
QueryParserTest.java
Java
[ { "context": "oid testArity1() {\n\t\tQuery q = Query.parse(\"bob(joe)\");\n\t\tSystem.out.println(q);\n\t\tcheckTo0(q);\n\t\tass", "end": 640, "score": 0.5044199228286743, "start": 639, "tag": "NAME", "value": "e" }, { "context": "\n\t\tassertEquals(\"head arg0\",new ConstantArgumen...
null
[]
package edu.cmu.ml.proppr.prove; import static org.junit.Assert.*; import org.junit.Test; import edu.cmu.ml.proppr.prove.wam.ConstantArgument; import edu.cmu.ml.proppr.prove.wam.Query; import edu.cmu.ml.proppr.prove.wam.VariableArgument; public class QueryParserTest { public void checkTo0(Query q) { assertEquals("query length",1,q.getRhs().length); assertEquals("head functor","bob",q.getRhs()[0].getFunctor()); } @Test public void testArity0() { Query q = Query.parse("bob"); checkTo0(q); assertEquals("head arity",0,q.getRhs()[0].getArity()); } @Test public void testArity1() { Query q = Query.parse("bob(joe)"); System.out.println(q); checkTo0(q); assertEquals("head arity",1,q.getRhs()[0].getArity()); assertEquals("head arg0",new ConstantArgument("joe"),q.getRhs()[0].getArg(0)); } @Test public void testArity2() { Query q = Query.parse("bob(joe,X)"); q.variabilize(); System.out.println(q); checkTo0(q); assertEquals("head arity",2,q.getRhs()[0].getArity()); assertEquals("head arg0",new ConstantArgument("joe"),q.getRhs()[0].getArg(0)); assertEquals("head arg1",new VariableArgument(-1),q.getRhs()[0].getArg(1)); } }
1,182
0.688663
0.667513
44
25.863636
23.879995
80
false
false
0
0
0
0
0
0
2
false
false
8
1c231f7a14ab2f836bbb2fdd57b52504e513dd75
11,836,929,886,445
a429955cff8b92d99119beeb7fd8aab75181c36a
/src/sample/MyGymManager.java
d9aa861c93910af0dbde5dce4e097bea86068052
[]
no_license
Abishani/Gym-Management-System
https://github.com/Abishani/Gym-Management-System
0a8f80f5617cdf0e27ad75a24e5bccba0e2272e2
0fb118133e2d43c698c8a6b04fe100645b5cae69
refs/heads/main
2023-05-14T17:46:59.154000
2021-06-04T16:19:39
2021-06-04T16:19:39
373,883,085
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; import javafx.scene.control.Label; import java.io.*; import java.util.*; public class MyGymManager implements GymManager { private ArrayList<DefaultMember> memberList = new ArrayList<DefaultMember>(); //creating a list to store member details @Override public void addNewMember(DefaultMember member) { //creating method to add members in the list if (memberList.size() < 100) { memberList.add(member); for (int i = 0; i < 1; i++) { //Displaying the outputs===================================================== System.out.print(member.getName() + " " + "Details are successfully added\n"); System.out.println("No of occupied spaces : " + memberList.size()); System.out.println("No of available spaces : " + (100 - memberList.size())); } } else { System.out.println("There are no free spaces available"); //creating a message when there is no available places } } @Override public boolean deleteMember(int membershipNumber) { //creating a method to delete member details boolean flag = false; for (DefaultMember member : memberList) { if (Objects.equals(member.getMembershipNumber(), membershipNumber)) { flag = true; memberList.remove(member); //displaying the outputs======================================================================== System.out.println("Member with the membership number " + membershipNumber + " Successfully removed"); System.out.println("No of occupied slots : " + memberList.size()); System.out.println("No of free slots: " + (100 - memberList.size())); //testing whether the member is instance of Student member or Over 60 member or default member if (member instanceof StudentMember) { System.out.println("Member type is: StudentMember"); } else if (member instanceof Over60Member) { System.out.println("Member type is: Over60Member"); } else { System.out.println("Member type is: DefaultMember"); } break; } } if (!flag) { System.out.println(membershipNumber + "is not found"); //If the details display the message } return false; } @Override public void printListOfMember() { // Print the details of members for (DefaultMember member : memberList) { System.out.println("==========================================="); System.out.println("Membership Number : " + member.getMembershipNumber() + " "); if (member instanceof StudentMember) { //to test member is instance of Membership types(StudentMember,Over60Member,DefaultMember) System.out.println("Member type is : StudentMember"); System.out.println("School Name:" + ((StudentMember) member).getSchoolName()); } else if (member instanceof Over60Member) { System.out.println("Member type is : Over60Member"); System.out.println("Age :" + ((Over60Member) member).getAge()); } else { System.out.println("Member type is: DefaultMember"); } //Printing the details of members ==================================== System.out.println("First Name is :" + member.getName() + " "); System.out.println("NIC Number is :" + member.getPhoneNumber() + " "); System.out.println("Contact Number is :" + member.getNicNumber() + " "); System.out.println("Membership start date is :" + member.getStartMembershipDate()); } if (memberList.size() == 0) { System.out.println("Empty List"); //If the details display the message } } @Override //sorting member list public List<DefaultMember> sort() { //sorting the member names in ascending order ArrayList<String> memberData = new ArrayList<>(); //get the names to the arraylist for (int i = 0; i < memberList.size(); i++) { String name = memberList.get(i).getName(); memberData.add(name); } //array to store member names String[] array = memberData.toArray(new String[]{}); //sorting names in ascending order BubbleSort.sort(array, true); //convert array to lsit List<String> sortList = Arrays.asList(array); //match member names with object for (String element : sortList) { for (DefaultMember o : memberList) { if (element.equals(o.getName())) { System.out.println(o.toString()); } } } return memberList; } @Override public void search(String searchValue, Label lbl) { DefaultMember[] members = memberList.toArray(new DefaultMember[]{}); ArrayList<DefaultMember> arrayList = new ArrayList<>(); File file = new File("searchMemberDetails.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNext()) { int membershipNumber = scanner.nextInt(); String memName = scanner.next(); String startMembershipDate = scanner.next(); String nicNum = scanner.next(); String phoneNumber = scanner.next(); String schoolName = scanner.next(); int memAge = scanner.nextInt(); String membershipType = scanner.next(); DefaultMember member = null; //inserting data into the table if (membershipType.equals("student")) { member = new StudentMember(membershipNumber, memName,startMembershipDate,nicNum, phoneNumber, schoolName); } else if (membershipType.equals("over60")) { member = new Over60Member(membershipNumber, memName, startMembershipDate, phoneNumber, membershipType, memAge,nicNum); } else { member = new DefaultMember(membershipNumber, memName, startMembershipDate, phoneNumber, membershipType,nicNum); } arrayList.add(member); } String memName; int id; for (DefaultMember member : arrayList) { System.out.println(member.toString()); if (searchValue.equals(member.getName()) || searchValue == String.valueOf(member.getMembershipNumber())) { lbl.setText(member.toString()); break; } else { lbl.setText("not found"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } } @Override //storing the member details public void save() { DefaultMember[] save = memberList.toArray(new DefaultMember[]{}); File file = new File("memberDetails.txt"); BufferedWriter output; try (FileWriter fileWriter = new FileWriter(file)) { output = new BufferedWriter(fileWriter); int q = memberList.size(); for (int a = 0; a < memberList.size(); a++) { String schoolName; int age; if (memberList.get(a) instanceof StudentMember) { schoolName = ((StudentMember) memberList.get(a)).getSchoolName(); output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " schoolName : " + ((StudentMember) memberList.get(a)).getSchoolName() + " NIC Name : " + memberList.get(a).getNicNumber() ); } else if (memberList.get(a) instanceof Over60Member) { age = ((Over60Member) memberList.get(a)).getAge(); output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " Age : " + ((Over60Member) memberList.get(a)).getAge() + " NIC Name : " + memberList.get(a).getNicNumber() ); } else { output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " NIC Name : " + memberList.get(a).getNicNumber() ); } System.out.println("saved successfully"); output.flush(); output.newLine(); } } catch (IOException e) { System.out.println("No data to save"); } } public void saveForSearch() { DefaultMember[] save = memberList.toArray(new DefaultMember[]{}); File file = new File("searchMemberDetails.txt"); BufferedWriter fileOut; try (FileWriter fileWriter = new FileWriter(file)) { fileOut = new BufferedWriter(fileWriter); int q = memberList.size(); for (int a = 0; a < memberList.size(); a++) { String schoolName; int age; if (memberList.get(a) instanceof StudentMember) { schoolName = ((StudentMember) memberList.get(a)).getSchoolName(); fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getPhoneNumber() + " " + memberList.get(a).getNicNumber() + " " + ((StudentMember) memberList.get(a)).getSchoolName() + " 0" + " student"); } else if (memberList.get(a) instanceof Over60Member) { age = ((Over60Member) memberList.get(a)).getAge(); fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getPhoneNumber() + " " + memberList.get(a).getNicNumber() + " null" + " " + ((Over60Member) memberList.get(a)).getAge() + " over60"); } else { fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getNicNumber() + " " + memberList.get(a).getPhoneNumber() + " null 0 default"); } System.out.println("Details are saved successfully"); fileOut.flush(); ///file.flush is use to filter the details to fileOut.newLine(); } } catch (IOException e) { System.out.println("No data to save"); } } //searching member details public static <T> int searchRecord(T[] array, T searchValue) { for (int i = 0; i < array.length; i++) { if (array[i].equals(searchValue)) { return i; } } return -1; } }
UTF-8
Java
13,259
java
MyGymManager.java
Java
[]
null
[]
package sample; import javafx.scene.control.Label; import java.io.*; import java.util.*; public class MyGymManager implements GymManager { private ArrayList<DefaultMember> memberList = new ArrayList<DefaultMember>(); //creating a list to store member details @Override public void addNewMember(DefaultMember member) { //creating method to add members in the list if (memberList.size() < 100) { memberList.add(member); for (int i = 0; i < 1; i++) { //Displaying the outputs===================================================== System.out.print(member.getName() + " " + "Details are successfully added\n"); System.out.println("No of occupied spaces : " + memberList.size()); System.out.println("No of available spaces : " + (100 - memberList.size())); } } else { System.out.println("There are no free spaces available"); //creating a message when there is no available places } } @Override public boolean deleteMember(int membershipNumber) { //creating a method to delete member details boolean flag = false; for (DefaultMember member : memberList) { if (Objects.equals(member.getMembershipNumber(), membershipNumber)) { flag = true; memberList.remove(member); //displaying the outputs======================================================================== System.out.println("Member with the membership number " + membershipNumber + " Successfully removed"); System.out.println("No of occupied slots : " + memberList.size()); System.out.println("No of free slots: " + (100 - memberList.size())); //testing whether the member is instance of Student member or Over 60 member or default member if (member instanceof StudentMember) { System.out.println("Member type is: StudentMember"); } else if (member instanceof Over60Member) { System.out.println("Member type is: Over60Member"); } else { System.out.println("Member type is: DefaultMember"); } break; } } if (!flag) { System.out.println(membershipNumber + "is not found"); //If the details display the message } return false; } @Override public void printListOfMember() { // Print the details of members for (DefaultMember member : memberList) { System.out.println("==========================================="); System.out.println("Membership Number : " + member.getMembershipNumber() + " "); if (member instanceof StudentMember) { //to test member is instance of Membership types(StudentMember,Over60Member,DefaultMember) System.out.println("Member type is : StudentMember"); System.out.println("School Name:" + ((StudentMember) member).getSchoolName()); } else if (member instanceof Over60Member) { System.out.println("Member type is : Over60Member"); System.out.println("Age :" + ((Over60Member) member).getAge()); } else { System.out.println("Member type is: DefaultMember"); } //Printing the details of members ==================================== System.out.println("First Name is :" + member.getName() + " "); System.out.println("NIC Number is :" + member.getPhoneNumber() + " "); System.out.println("Contact Number is :" + member.getNicNumber() + " "); System.out.println("Membership start date is :" + member.getStartMembershipDate()); } if (memberList.size() == 0) { System.out.println("Empty List"); //If the details display the message } } @Override //sorting member list public List<DefaultMember> sort() { //sorting the member names in ascending order ArrayList<String> memberData = new ArrayList<>(); //get the names to the arraylist for (int i = 0; i < memberList.size(); i++) { String name = memberList.get(i).getName(); memberData.add(name); } //array to store member names String[] array = memberData.toArray(new String[]{}); //sorting names in ascending order BubbleSort.sort(array, true); //convert array to lsit List<String> sortList = Arrays.asList(array); //match member names with object for (String element : sortList) { for (DefaultMember o : memberList) { if (element.equals(o.getName())) { System.out.println(o.toString()); } } } return memberList; } @Override public void search(String searchValue, Label lbl) { DefaultMember[] members = memberList.toArray(new DefaultMember[]{}); ArrayList<DefaultMember> arrayList = new ArrayList<>(); File file = new File("searchMemberDetails.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNext()) { int membershipNumber = scanner.nextInt(); String memName = scanner.next(); String startMembershipDate = scanner.next(); String nicNum = scanner.next(); String phoneNumber = scanner.next(); String schoolName = scanner.next(); int memAge = scanner.nextInt(); String membershipType = scanner.next(); DefaultMember member = null; //inserting data into the table if (membershipType.equals("student")) { member = new StudentMember(membershipNumber, memName,startMembershipDate,nicNum, phoneNumber, schoolName); } else if (membershipType.equals("over60")) { member = new Over60Member(membershipNumber, memName, startMembershipDate, phoneNumber, membershipType, memAge,nicNum); } else { member = new DefaultMember(membershipNumber, memName, startMembershipDate, phoneNumber, membershipType,nicNum); } arrayList.add(member); } String memName; int id; for (DefaultMember member : arrayList) { System.out.println(member.toString()); if (searchValue.equals(member.getName()) || searchValue == String.valueOf(member.getMembershipNumber())) { lbl.setText(member.toString()); break; } else { lbl.setText("not found"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } } @Override //storing the member details public void save() { DefaultMember[] save = memberList.toArray(new DefaultMember[]{}); File file = new File("memberDetails.txt"); BufferedWriter output; try (FileWriter fileWriter = new FileWriter(file)) { output = new BufferedWriter(fileWriter); int q = memberList.size(); for (int a = 0; a < memberList.size(); a++) { String schoolName; int age; if (memberList.get(a) instanceof StudentMember) { schoolName = ((StudentMember) memberList.get(a)).getSchoolName(); output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " schoolName : " + ((StudentMember) memberList.get(a)).getSchoolName() + " NIC Name : " + memberList.get(a).getNicNumber() ); } else if (memberList.get(a) instanceof Over60Member) { age = ((Over60Member) memberList.get(a)).getAge(); output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " Age : " + ((Over60Member) memberList.get(a)).getAge() + " NIC Name : " + memberList.get(a).getNicNumber() ); } else { output.write( " Membership Number : " + memberList.get(a).getMembershipNumber() + " Name : " + memberList.get(a).getName() + " startMembershipDate : " + memberList.get(a).getStartMembershipDate() + " phoneNumber : " + memberList.get(a).getPhoneNumber() + " NIC Name : " + memberList.get(a).getNicNumber() ); } System.out.println("saved successfully"); output.flush(); output.newLine(); } } catch (IOException e) { System.out.println("No data to save"); } } public void saveForSearch() { DefaultMember[] save = memberList.toArray(new DefaultMember[]{}); File file = new File("searchMemberDetails.txt"); BufferedWriter fileOut; try (FileWriter fileWriter = new FileWriter(file)) { fileOut = new BufferedWriter(fileWriter); int q = memberList.size(); for (int a = 0; a < memberList.size(); a++) { String schoolName; int age; if (memberList.get(a) instanceof StudentMember) { schoolName = ((StudentMember) memberList.get(a)).getSchoolName(); fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getPhoneNumber() + " " + memberList.get(a).getNicNumber() + " " + ((StudentMember) memberList.get(a)).getSchoolName() + " 0" + " student"); } else if (memberList.get(a) instanceof Over60Member) { age = ((Over60Member) memberList.get(a)).getAge(); fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getPhoneNumber() + " " + memberList.get(a).getNicNumber() + " null" + " " + ((Over60Member) memberList.get(a)).getAge() + " over60"); } else { fileOut.write( memberList.get(a).getMembershipNumber() + " " + memberList.get(a).getName() + " " + memberList.get(a).getStartMembershipDate() + " " + memberList.get(a).getNicNumber() + " " + memberList.get(a).getPhoneNumber() + " null 0 default"); } System.out.println("Details are saved successfully"); fileOut.flush(); ///file.flush is use to filter the details to fileOut.newLine(); } } catch (IOException e) { System.out.println("No data to save"); } } //searching member details public static <T> int searchRecord(T[] array, T searchValue) { for (int i = 0; i < array.length; i++) { if (array[i].equals(searchValue)) { return i; } } return -1; } }
13,259
0.485255
0.481409
301
42.049835
34.545086
144
false
false
0
0
0
0
79
0.005958
0.445183
false
false
8
1166b7253926c3672904d9bf18b1a1aa7bf839e2
24,541,443,134,580
dd625875ac591e2b455753bf90dd7f5c95e2e1a1
/src/main/java/teamfour/tasc/model/task/util/TaskCompleteConverter.java
9483a013d83257dd54fc3c263b508863309b7bf9
[ "MIT" ]
permissive
mitigator/main
https://github.com/mitigator/main
984d3e77eba1b946e14ba7def7d8708d2c35f559
b068977e39cb5ff1c6c2bbb5f6619f0b37e1e49d
refs/heads/master
2021-01-11T03:39:41.906000
2016-10-19T06:16:03
2016-10-19T06:16:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package teamfour.tasc.model.task.util; import java.util.Date; import teamfour.tasc.commons.exceptions.IllegalValueException; import teamfour.tasc.model.task.Complete; import teamfour.tasc.model.task.Deadline; import teamfour.tasc.model.task.Name; import teamfour.tasc.model.task.Period; import teamfour.tasc.model.task.ReadOnlyTask; import teamfour.tasc.model.task.Recurrence; import teamfour.tasc.model.task.Task; import teamfour.tasc.model.task.exceptions.TaskAlreadyCompletedException; /** * Converts a given uncompleted task to a * completed task. If the task is a recurrence, * then only the first occurrence is completed, and * the remaining recurring tasks will be uncompleted. */ public class TaskCompleteConverter { private final Task completedTask; private final Task uncompletedRemainingRecurringTask; public static final String TASK_NAME_COMPLETED_SUFFIX = "[Completed At %s]"; /** * Constructor for converter. * @throws IllegalValueException */ public TaskCompleteConverter(ReadOnlyTask uncompletedTask, Date currentTime) throws IllegalArgumentException, TaskAlreadyCompletedException, IllegalValueException { if (uncompletedTask == null) { throw new IllegalArgumentException(); } if (currentTime == null) { throw new IllegalArgumentException(); } if (uncompletedTask.getComplete().isCompleted() == true) { throw new TaskAlreadyCompletedException(); } String completedString = String.format(TASK_NAME_COMPLETED_SUFFIX, currentTime); this.completedTask = new Task( new Name(uncompletedTask.getName().getName() + completedString), new Complete(true), uncompletedTask.getDeadline(), uncompletedTask.getPeriod(), new Recurrence(), uncompletedTask.getTags()); Recurrence oldRecurrence = uncompletedTask.getRecurrence(); Recurrence newRecurrence = oldRecurrence.getRecurrenceWithOneFrequencyLess(); if (newRecurrence == null) { this.uncompletedRemainingRecurringTask = null; } else { Deadline newDeadline = uncompletedTask.getDeadline(); Period newPeriod = uncompletedTask.getPeriod(); if (newDeadline.hasDeadline()) { newDeadline = new Deadline( oldRecurrence.getNextDateAfterRecurrence(newDeadline.getDeadline())); } if (newPeriod.hasPeriod()) { newPeriod = new Period( oldRecurrence.getNextDateAfterRecurrence(newPeriod.getStartTime()), oldRecurrence.getNextDateAfterRecurrence(newPeriod.getEndTime())); } this.uncompletedRemainingRecurringTask = new Task(uncompletedTask.getName(), new Complete(false), newDeadline, newPeriod, newRecurrence, uncompletedTask.getTags()); } } public Task getCompletedTask() { return completedTask; } public Task getUncompletedRemainingRecurringTask() { return uncompletedRemainingRecurringTask; } }
UTF-8
Java
3,371
java
TaskCompleteConverter.java
Java
[]
null
[]
package teamfour.tasc.model.task.util; import java.util.Date; import teamfour.tasc.commons.exceptions.IllegalValueException; import teamfour.tasc.model.task.Complete; import teamfour.tasc.model.task.Deadline; import teamfour.tasc.model.task.Name; import teamfour.tasc.model.task.Period; import teamfour.tasc.model.task.ReadOnlyTask; import teamfour.tasc.model.task.Recurrence; import teamfour.tasc.model.task.Task; import teamfour.tasc.model.task.exceptions.TaskAlreadyCompletedException; /** * Converts a given uncompleted task to a * completed task. If the task is a recurrence, * then only the first occurrence is completed, and * the remaining recurring tasks will be uncompleted. */ public class TaskCompleteConverter { private final Task completedTask; private final Task uncompletedRemainingRecurringTask; public static final String TASK_NAME_COMPLETED_SUFFIX = "[Completed At %s]"; /** * Constructor for converter. * @throws IllegalValueException */ public TaskCompleteConverter(ReadOnlyTask uncompletedTask, Date currentTime) throws IllegalArgumentException, TaskAlreadyCompletedException, IllegalValueException { if (uncompletedTask == null) { throw new IllegalArgumentException(); } if (currentTime == null) { throw new IllegalArgumentException(); } if (uncompletedTask.getComplete().isCompleted() == true) { throw new TaskAlreadyCompletedException(); } String completedString = String.format(TASK_NAME_COMPLETED_SUFFIX, currentTime); this.completedTask = new Task( new Name(uncompletedTask.getName().getName() + completedString), new Complete(true), uncompletedTask.getDeadline(), uncompletedTask.getPeriod(), new Recurrence(), uncompletedTask.getTags()); Recurrence oldRecurrence = uncompletedTask.getRecurrence(); Recurrence newRecurrence = oldRecurrence.getRecurrenceWithOneFrequencyLess(); if (newRecurrence == null) { this.uncompletedRemainingRecurringTask = null; } else { Deadline newDeadline = uncompletedTask.getDeadline(); Period newPeriod = uncompletedTask.getPeriod(); if (newDeadline.hasDeadline()) { newDeadline = new Deadline( oldRecurrence.getNextDateAfterRecurrence(newDeadline.getDeadline())); } if (newPeriod.hasPeriod()) { newPeriod = new Period( oldRecurrence.getNextDateAfterRecurrence(newPeriod.getStartTime()), oldRecurrence.getNextDateAfterRecurrence(newPeriod.getEndTime())); } this.uncompletedRemainingRecurringTask = new Task(uncompletedTask.getName(), new Complete(false), newDeadline, newPeriod, newRecurrence, uncompletedTask.getTags()); } } public Task getCompletedTask() { return completedTask; } public Task getUncompletedRemainingRecurringTask() { return uncompletedRemainingRecurringTask; } }
3,371
0.638386
0.638386
92
35.641304
26.266022
99
false
false
0
0
0
0
0
0
0.5
false
false
8
3c4e93cbf86f4aabbde81f0f7247c4c5102efafe
5,540,507,819,088
3538cd92e51d26e8ac3652ac2cbb2c2aabf31daf
/src/main/java/com/tdd/app/infrastructure/FakeEmailService.java
9a4937008f0ee198ed07a5661e20555e2be0f154
[]
no_license
konzinov/birthday-greeting-kata
https://github.com/konzinov/birthday-greeting-kata
8b9f012720a811611785c7c8003b86062d2af022
f2005dab1535b824c8944ff7b714ddf0724e6906
refs/heads/master
2023-06-11T04:28:41.786000
2021-07-04T16:41:50
2021-07-04T16:41:50
382,898,320
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tdd.app.infrastructure; import com.tdd.app.domain.EmailService; import com.tdd.app.domain.Employee; import com.tdd.app.domain.Mail; public class FakeEmailService implements EmailService { public Mail sendMail(Employee employee) { return new Mail(employee.email, String.format("Happy birthday, dear %s!", employee.firstName), "Happy birthday!"); } }
UTF-8
Java
379
java
FakeEmailService.java
Java
[]
null
[]
package com.tdd.app.infrastructure; import com.tdd.app.domain.EmailService; import com.tdd.app.domain.Employee; import com.tdd.app.domain.Mail; public class FakeEmailService implements EmailService { public Mail sendMail(Employee employee) { return new Mail(employee.email, String.format("Happy birthday, dear %s!", employee.firstName), "Happy birthday!"); } }
379
0.754617
0.754617
11
33.454544
33.818672
122
false
false
0
0
0
0
0
0
0.818182
false
false
8
53a46261fb5c34082b44300fb3dcd823965f9a5a
18,038,862,668,238
2f1163b77d320376807e707a8ecac031050f7180
/src/com/hoticket/action/GeoLocatorAction.java
59c938a282b8d5026d0a76fe5f977979f4294c30
[]
no_license
Long317/aspen
https://github.com/Long317/aspen
d8608b51bba25ba03fa7e6ddc10a1ffa373fcacf
890a64e0c182c3842ba930c7daf6c048d936fc4f
refs/heads/master
2020-12-25T04:28:24.033000
2016-03-06T20:15:22
2016-03-06T20:15:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hoticket.action; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import static com.hoticket.util.Constants.*; import java.net.URL; import java.util.ArrayList; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import com.hoticket.dao.TheatreDAO; import com.hoticket.modal.Theatre; import com.hoticket.util.AddressConverter; import com.hoticket.util.Methods; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class GeoLocatorAction extends ActionSupport { private String clientIP; private InputStream inputStream; /** * */ private static final long serialVersionUID = 1L; /** * geoLocator calculate the distance and get closest theatre from clinet */ @SuppressWarnings("unchecked") public String execute() { try { System.out.println(clientIP); //get session object @SuppressWarnings("rawtypes") Map session = (Map) ActionContext.getContext().get("session"); //create remote URL URL url = new URL(GEOLocator_URL+clientIP); //get writer for the url response BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String inputLine; //store url content to the result String result = ""; while ((inputLine = in.readLine()) != null) { result += inputLine; } //parse the json result JSONParser parser = new JSONParser(); JSONObject addressinfo =(JSONObject) parser.parse(result); String addr = addressinfo.get("as").toString(); String city = addressinfo.get("city").toString(); String state = addressinfo.get("region").toString(); String zip = (String) addressinfo.get("zip"); //create double[] to store lat and lon for client double [] geoData = new double[2]; geoData[0] = (double) addressinfo.get("lat"); geoData[1] = (double) addressinfo.get("lon"); session.put("clientGeodata", geoData); //store user address String address = addr+" "+city+" "+state+" "+zip; session.put("clientAddress", address); ArrayList<Theatre> theatres ; //if get theatres from db if not exits in context if (ActionContext.getContext().get("theatres")==null){ theatres = (ArrayList<Theatre>) TheatreDAO.getInstance().getTheatre(); }else{ //get theatres from Context if it exits theatres= (ArrayList<Theatre>)ActionContext.getContext().get("theatres"); ActionContext.getContext().put("theatres", theatres); } //store distances for same state theatre ArrayList<Double> distances = new ArrayList<Double>(); //store same state theatre ArrayList<Theatre> stateTheatres = new ArrayList<Theatre>(); for (int i=0;i<theatres.size();i++){ //only check same state //if (theatres.get(i).getState().contains(state.trim())){ stateTheatres.add(theatres.get(i)); double[] theatreGeo = new double[]{theatres.get(i).getLatitude(),theatres.get(i).getLongitude()}; distances.add(AddressConverter.calculateDistance(geoData, theatreGeo)); // } } //store top MAX_THEATRE number closest theatres to the session ArrayList<Theatre> closeTheatres = new ArrayList<Theatre>(); int number = stateTheatres.size()>=MAX_THEATRE?MAX_THEATRE:stateTheatres.size(); for (int i=0;i<number;i++){ System.out.println(stateTheatres.get(Methods.minIndex(distances)).getName()); closeTheatres.add(stateTheatres.get(Methods.minIndex(distances))); distances.set(Methods.minIndex(distances), 1000000.0); } session.put("closeTheatres", closeTheatres); //return to user with JSON String for closeTheatres JSONArray theatresJSON = new JSONArray(); for (int i=0;i<closeTheatres.size();i++){ JSONObject theatreJSON = new JSONObject(); theatreJSON.put("name", closeTheatres.get(i).getName()); theatreJSON.put("addr", closeTheatres.get(i).getAddress()); theatreJSON.put("id", closeTheatres.get(i).getId()); theatresJSON.add(theatreJSON); } //add user info JSONObject theatreJSON = new JSONObject(); theatreJSON.put("zip", zip); theatreJSON.put("ip", clientIP); theatresJSON.add(theatreJSON); //return JSON String to the client inputStream = new ByteArrayInputStream( theatresJSON.toJSONString().getBytes("UTF-8")); //update user_geo_status to ok session.put("user_geo_status", "ok"); //replace popular cities with theatre info String[] theatreInfo = new String[closeTheatres.size()*2]; for (int i=0, j=0;i<closeTheatres.size();i++){ theatreInfo[j]=closeTheatres.get(i).getName(); theatreInfo[j+1]=closeTheatres.get(i).getAddress(); j=j+2; } session.put("popular_cities", theatreInfo); session.put("default_theatre", closeTheatres.get(0)); System.out.println(closeTheatres.get(0).getName()); return SUCCESS; } catch (Exception e) { e.printStackTrace(); return ERROR; } } /** * user decline to use his geo location data * @return */ @SuppressWarnings("unchecked") public String decline() { @SuppressWarnings("rawtypes") Map session = (Map) ActionContext.getContext().get("session"); session.put("user_geo_status", "decline"); return SUCCESS; } public String getClientIP() { return clientIP; } public void setClientIP(String clientIP) { this.clientIP = clientIP; } public InputStream getInputStream() { return inputStream; } }
UTF-8
Java
6,194
java
GeoLocatorAction.java
Java
[]
null
[]
package com.hoticket.action; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import static com.hoticket.util.Constants.*; import java.net.URL; import java.util.ArrayList; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import com.hoticket.dao.TheatreDAO; import com.hoticket.modal.Theatre; import com.hoticket.util.AddressConverter; import com.hoticket.util.Methods; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class GeoLocatorAction extends ActionSupport { private String clientIP; private InputStream inputStream; /** * */ private static final long serialVersionUID = 1L; /** * geoLocator calculate the distance and get closest theatre from clinet */ @SuppressWarnings("unchecked") public String execute() { try { System.out.println(clientIP); //get session object @SuppressWarnings("rawtypes") Map session = (Map) ActionContext.getContext().get("session"); //create remote URL URL url = new URL(GEOLocator_URL+clientIP); //get writer for the url response BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String inputLine; //store url content to the result String result = ""; while ((inputLine = in.readLine()) != null) { result += inputLine; } //parse the json result JSONParser parser = new JSONParser(); JSONObject addressinfo =(JSONObject) parser.parse(result); String addr = addressinfo.get("as").toString(); String city = addressinfo.get("city").toString(); String state = addressinfo.get("region").toString(); String zip = (String) addressinfo.get("zip"); //create double[] to store lat and lon for client double [] geoData = new double[2]; geoData[0] = (double) addressinfo.get("lat"); geoData[1] = (double) addressinfo.get("lon"); session.put("clientGeodata", geoData); //store user address String address = addr+" "+city+" "+state+" "+zip; session.put("clientAddress", address); ArrayList<Theatre> theatres ; //if get theatres from db if not exits in context if (ActionContext.getContext().get("theatres")==null){ theatres = (ArrayList<Theatre>) TheatreDAO.getInstance().getTheatre(); }else{ //get theatres from Context if it exits theatres= (ArrayList<Theatre>)ActionContext.getContext().get("theatres"); ActionContext.getContext().put("theatres", theatres); } //store distances for same state theatre ArrayList<Double> distances = new ArrayList<Double>(); //store same state theatre ArrayList<Theatre> stateTheatres = new ArrayList<Theatre>(); for (int i=0;i<theatres.size();i++){ //only check same state //if (theatres.get(i).getState().contains(state.trim())){ stateTheatres.add(theatres.get(i)); double[] theatreGeo = new double[]{theatres.get(i).getLatitude(),theatres.get(i).getLongitude()}; distances.add(AddressConverter.calculateDistance(geoData, theatreGeo)); // } } //store top MAX_THEATRE number closest theatres to the session ArrayList<Theatre> closeTheatres = new ArrayList<Theatre>(); int number = stateTheatres.size()>=MAX_THEATRE?MAX_THEATRE:stateTheatres.size(); for (int i=0;i<number;i++){ System.out.println(stateTheatres.get(Methods.minIndex(distances)).getName()); closeTheatres.add(stateTheatres.get(Methods.minIndex(distances))); distances.set(Methods.minIndex(distances), 1000000.0); } session.put("closeTheatres", closeTheatres); //return to user with JSON String for closeTheatres JSONArray theatresJSON = new JSONArray(); for (int i=0;i<closeTheatres.size();i++){ JSONObject theatreJSON = new JSONObject(); theatreJSON.put("name", closeTheatres.get(i).getName()); theatreJSON.put("addr", closeTheatres.get(i).getAddress()); theatreJSON.put("id", closeTheatres.get(i).getId()); theatresJSON.add(theatreJSON); } //add user info JSONObject theatreJSON = new JSONObject(); theatreJSON.put("zip", zip); theatreJSON.put("ip", clientIP); theatresJSON.add(theatreJSON); //return JSON String to the client inputStream = new ByteArrayInputStream( theatresJSON.toJSONString().getBytes("UTF-8")); //update user_geo_status to ok session.put("user_geo_status", "ok"); //replace popular cities with theatre info String[] theatreInfo = new String[closeTheatres.size()*2]; for (int i=0, j=0;i<closeTheatres.size();i++){ theatreInfo[j]=closeTheatres.get(i).getName(); theatreInfo[j+1]=closeTheatres.get(i).getAddress(); j=j+2; } session.put("popular_cities", theatreInfo); session.put("default_theatre", closeTheatres.get(0)); System.out.println(closeTheatres.get(0).getName()); return SUCCESS; } catch (Exception e) { e.printStackTrace(); return ERROR; } } /** * user decline to use his geo location data * @return */ @SuppressWarnings("unchecked") public String decline() { @SuppressWarnings("rawtypes") Map session = (Map) ActionContext.getContext().get("session"); session.put("user_geo_status", "decline"); return SUCCESS; } public String getClientIP() { return clientIP; } public void setClientIP(String clientIP) { this.clientIP = clientIP; } public InputStream getInputStream() { return inputStream; } }
6,194
0.624798
0.620762
171
34.222221
23.70229
108
false
false
0
0
0
0
0
0
1.754386
false
false
8
d06cbc4a0140a5f6f305edc51fe373406baace1a
9,079,560,915,952
eee1279089a53785b0c723c040e72df19265b96b
/conveyor-core/src/test/java/com/aegisql/conveyor/demo/ThreadPool.java
cadafc8dfca6c2917dd218ec733c9aa0487c9ab3
[ "Apache-2.0" ]
permissive
aegisql/conveyor
https://github.com/aegisql/conveyor
b7df6b6a56612628a7dab8c421ecda3c9d0062a5
1ce6de85747593180aca54b24612b41936315f8b
refs/heads/master
2023-08-31T10:20:53.050000
2023-08-28T16:05:46
2023-08-28T16:05:46
45,225,736
17
1
NOASSERTION
false
2023-09-14T20:26:46
2015-10-30T03:03:10
2023-02-28T00:17:33
2023-09-14T20:26:45
8,813
17
1
0
Java
false
false
/* * COPYRIGHT (C) AEGIS DATA SOLUTIONS, LLC, 2015 */ package com.aegisql.conveyor.demo; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadPool { private final ExecutorService pool; public ThreadPool() { pool = Executors.newFixedThreadPool(3); } public ThreadPool(int n) { pool = Executors.newFixedThreadPool(n); } public Future<?> runAsynchWithDelay(long delay, Runnable runnable) { return pool.submit(()->{ try { Thread.sleep(delay); } catch (Exception e) {} runnable.run(); } ); } public Future<?> runAsynchWithRandomDelay(int bound, Runnable runnable) { Random r = new Random(); return runAsynchWithDelay(r.nextInt(bound)+1,runnable); } public Future<?> runAsynchWithRandomDelay(Runnable runnable) { return runAsynchWithRandomDelay(100,runnable); } public Future<?> runAsynch(Runnable runnable) { return pool.submit(runnable); } public void shutdown() { pool.shutdown(); } }
UTF-8
Java
1,058
java
ThreadPool.java
Java
[]
null
[]
/* * COPYRIGHT (C) AEGIS DATA SOLUTIONS, LLC, 2015 */ package com.aegisql.conveyor.demo; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadPool { private final ExecutorService pool; public ThreadPool() { pool = Executors.newFixedThreadPool(3); } public ThreadPool(int n) { pool = Executors.newFixedThreadPool(n); } public Future<?> runAsynchWithDelay(long delay, Runnable runnable) { return pool.submit(()->{ try { Thread.sleep(delay); } catch (Exception e) {} runnable.run(); } ); } public Future<?> runAsynchWithRandomDelay(int bound, Runnable runnable) { Random r = new Random(); return runAsynchWithDelay(r.nextInt(bound)+1,runnable); } public Future<?> runAsynchWithRandomDelay(Runnable runnable) { return runAsynchWithRandomDelay(100,runnable); } public Future<?> runAsynch(Runnable runnable) { return pool.submit(runnable); } public void shutdown() { pool.shutdown(); } }
1,058
0.718336
0.70983
50
20.16
20.935482
74
false
false
0
0
0
0
0
0
1.46
false
false
8
32c7879ea458e47cdb8f5f0961f0dabb508266f9
23,356,032,213,701
06c7b9e97bb74470ef0a869814ac48d7ce649f40
/src/no/systema/overview/ufortolledeoppdrag/util/jfreechart/manager/IJFreeChartDimension.java
dbd9bbe57b3ad011ec239ad1dbd96a5091b8a4b5
[]
no_license
SystemaAS/espedsgoverview
https://github.com/SystemaAS/espedsgoverview
b3e238afa7bd92d39686683835198b96fffa4d8a
3c46259bb7efa52126c7d5a844eb8f09a9818682
refs/heads/master
2022-02-02T07:16:28.828000
2022-01-09T15:20:20
2022-01-09T15:20:20
128,624,800
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package no.systema.overview.ufortolledeoppdrag.util.jfreechart.manager; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import no.systema.overview.ufortolledeoppdrag.model.jsonjackson.JsonTopicRecord; import no.systema.overview.ufortolledeoppdrag.model.jsonjackson.JsonTopicRecordDiagramChart; /** * This is the interface for all jFree charts special implementations * (Daily, every 2 days, every 3 days or other) * * The standard implementation will produce jfree chart per day (daily basis) * * @author oscardelatorre * @date Sep 8, 2013 * * */ public interface IJFreeChartDimension { public void buildChart(Collection<JsonTopicRecord> ufortList, Collection<JsonTopicRecordDiagramChart> chartList); public void setCategoryMap(Map<Integer, Integer> value); public Map<Integer, Integer> getCategoryMap(); //chart dimensions public Collection<JsonTopicRecordDiagramChart>getChartList(); //total number of categories public int getTotalNumberOfCategories(); //domain limit values (lower and upper) public void setLowerLimit(int value); public int getLowerLimit(); public void setUpperLimit(int value); public int getUpperLimit(); public void setIntervalLength(int value); public int getIntervalLength(); //color limits public void setGreenLimit(int value); public int getGreenLimit(); public void setYellowLimit(int value); public int getYellowLimit(); public void setRedLimit(int value); public int getRedLimit(); public void setGrayLimit(int value); public int getGrayLimit(); //color lists public void addToGreenList (int value); public List<Integer>getGreenList (); public void addToYellowList (int value); public List<Integer>getYellowList (); public void addToRedList (int value); public List<Integer>getRedList (); public void addToGrayList (int value); public List<Integer>getGrayList (); }
UTF-8
Java
1,932
java
IJFreeChartDimension.java
Java
[ { "context": "e jfree chart per day (daily basis)\n * \n * @author oscardelatorre\n * @date Sep 8, 2013\n * \n *\n */\npublic interface ", "end": 596, "score": 0.9975494146347046, "start": 582, "tag": "USERNAME", "value": "oscardelatorre" } ]
null
[]
/** * */ package no.systema.overview.ufortolledeoppdrag.util.jfreechart.manager; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import no.systema.overview.ufortolledeoppdrag.model.jsonjackson.JsonTopicRecord; import no.systema.overview.ufortolledeoppdrag.model.jsonjackson.JsonTopicRecordDiagramChart; /** * This is the interface for all jFree charts special implementations * (Daily, every 2 days, every 3 days or other) * * The standard implementation will produce jfree chart per day (daily basis) * * @author oscardelatorre * @date Sep 8, 2013 * * */ public interface IJFreeChartDimension { public void buildChart(Collection<JsonTopicRecord> ufortList, Collection<JsonTopicRecordDiagramChart> chartList); public void setCategoryMap(Map<Integer, Integer> value); public Map<Integer, Integer> getCategoryMap(); //chart dimensions public Collection<JsonTopicRecordDiagramChart>getChartList(); //total number of categories public int getTotalNumberOfCategories(); //domain limit values (lower and upper) public void setLowerLimit(int value); public int getLowerLimit(); public void setUpperLimit(int value); public int getUpperLimit(); public void setIntervalLength(int value); public int getIntervalLength(); //color limits public void setGreenLimit(int value); public int getGreenLimit(); public void setYellowLimit(int value); public int getYellowLimit(); public void setRedLimit(int value); public int getRedLimit(); public void setGrayLimit(int value); public int getGrayLimit(); //color lists public void addToGreenList (int value); public List<Integer>getGreenList (); public void addToYellowList (int value); public List<Integer>getYellowList (); public void addToRedList (int value); public List<Integer>getRedList (); public void addToGrayList (int value); public List<Integer>getGrayList (); }
1,932
0.774327
0.770704
70
26.6
24.793663
114
false
false
0
0
0
0
0
0
1.157143
false
false
8
2250380b5cc9aa049d78b4753393fd4dc4d42929
15,831,249,469,862
1a6381883508c4aa36b650fab575a0ea500d4351
/common-message/src/main/java/com/motor/common/message/MessageContainer.java
7921125d7a710e2a804686868c2fda091957d280
[]
no_license
StrawSoul/motor-common
https://github.com/StrawSoul/motor-common
e7cf93bd41665417a6165e082618c8b960b9e21e
dc0614ac2fd83af421aabdaa93ed128a2e8361c6
refs/heads/master
2022-12-07T21:56:09.143000
2020-09-06T09:16:42
2020-09-06T09:16:42
288,946,792
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.motor.common.message; /** * @author zlj * */ public interface MessageContainer { /** * 获取消息模块 * @param name * @return */ MessageModule module(String name); /** * 消息接收器 * @param module * @return */ MessageReceiver getReceiver(String module); /** * 创建交换机 * @param exchangeName */ void createExchange(String exchangeName); void createQueue(String name); void createQueueBind(String queueName, String exchangeName, String routingKey); /** * 消息发送器 * @param module * @return */ MessageSender getSender(String module); }
UTF-8
Java
700
java
MessageContainer.java
Java
[ { "context": "package com.motor.common.message;\n\n/**\n * @author zlj\n *\n */\npublic interface MessageContainer {\n\n /", "end": 53, "score": 0.9995778799057007, "start": 50, "tag": "USERNAME", "value": "zlj" } ]
null
[]
package com.motor.common.message; /** * @author zlj * */ public interface MessageContainer { /** * 获取消息模块 * @param name * @return */ MessageModule module(String name); /** * 消息接收器 * @param module * @return */ MessageReceiver getReceiver(String module); /** * 创建交换机 * @param exchangeName */ void createExchange(String exchangeName); void createQueue(String name); void createQueueBind(String queueName, String exchangeName, String routingKey); /** * 消息发送器 * @param module * @return */ MessageSender getSender(String module); }
700
0.585106
0.585106
40
15.45
17.38958
83
false
false
0
0
0
0
0
0
0.225
false
false
2
8f7c773def4566869b3e2b92e23eff2372d70770
26,130,581,070,903
f0b965a8fe08580a1e94ba2db991191912014229
/app/src/main/java/com/example/note/cookhelper/view/recept_create/recipe_steps/view/fragment/iRecipeStepsViewer.java
2078118074d434300d956f204a7cacc6fed4f614
[]
no_license
IvanGalitskiy/CookHelper
https://github.com/IvanGalitskiy/CookHelper
386307b828d08e9dc67b5e664989134da2432054
3c54681431d9cc3f69bf028d8df9358107b74e5e
refs/heads/master
2018-02-08T19:45:21.070000
2017-01-30T07:53:35
2017-01-30T07:53:35
80,402,677
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.note.cookhelper.view.recept_create.recipe_steps.view.fragment; /** * Created by NOTE on 02.08.2016. */ public interface iRecipeStepsViewer { }
UTF-8
Java
167
java
iRecipeStepsViewer.java
Java
[ { "context": "ate.recipe_steps.view.fragment;\n\n/**\n * Created by NOTE on 02.08.2016.\n */\npublic interface iRecipeStepsV", "end": 106, "score": 0.5517789721488953, "start": 102, "tag": "USERNAME", "value": "NOTE" } ]
null
[]
package com.example.note.cookhelper.view.recept_create.recipe_steps.view.fragment; /** * Created by NOTE on 02.08.2016. */ public interface iRecipeStepsViewer { }
167
0.754491
0.706587
8
19.875
27.479254
82
false
false
0
0
0
0
0
0
0.125
false
false
2
09bd8ca06f7c8846acd2096c8358c46a479928cc
14,310,831,064,280
fb01c8151db35a31fa5985f970b9894099a82dfd
/archer-wfms/src/main/java/com/ylink/wfms/sysmng/cfgSysRegistry/service/Impl/CfgSysRegistryServiceImpl.java
3cc662b6bb8e0f7b4c0f702d8fa3a6c5ef9a92ec
[]
no_license
Zhang-dandan/Archer
https://github.com/Zhang-dandan/Archer
9785f3b55e23a9d33d0391104c9df9e290377581
3b9df999f95e4ebd34e54b9f540ddefb4a324c40
refs/heads/master
2021-01-20T12:48:55.444000
2017-08-29T01:30:15
2017-08-29T01:30:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ylink.wfms.sysmng.cfgSysRegistry.service.Impl; import com.ylink.wfms.sysmng.cfgSysRegistry.service.CfgSysRegistryService; import com.ylink.wfms.sysmng.cfgSysRegistry.entity.CfgSysRegistry; import com.ylink.wfms.sysmng.cfgSysRegistry.entity.CfgSysRegistryExample; import org.archer.common.mybatis.service.AbstractBaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * CfgSysRegistry模块 Service实现 * Created by Archer on 2017-08-07 09:55:13. */ @Service @Transactional public class CfgSysRegistryServiceImpl extends AbstractBaseService<CfgSysRegistry,CfgSysRegistryExample> implements CfgSysRegistryService { private static Logger logger = LoggerFactory.getLogger(CfgSysRegistryServiceImpl.class); }
UTF-8
Java
863
java
CfgSysRegistryServiceImpl.java
Java
[ { "context": "al;\n\n/**\n* CfgSysRegistry模块 Service实现\n* Created by Archer on 2017-08-07 09:55:13.\n*/\n@Service\n@Transactiona", "end": 562, "score": 0.7048431634902954, "start": 556, "tag": "NAME", "value": "Archer" } ]
null
[]
package com.ylink.wfms.sysmng.cfgSysRegistry.service.Impl; import com.ylink.wfms.sysmng.cfgSysRegistry.service.CfgSysRegistryService; import com.ylink.wfms.sysmng.cfgSysRegistry.entity.CfgSysRegistry; import com.ylink.wfms.sysmng.cfgSysRegistry.entity.CfgSysRegistryExample; import org.archer.common.mybatis.service.AbstractBaseService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * CfgSysRegistry模块 Service实现 * Created by Archer on 2017-08-07 09:55:13. */ @Service @Transactional public class CfgSysRegistryServiceImpl extends AbstractBaseService<CfgSysRegistry,CfgSysRegistryExample> implements CfgSysRegistryService { private static Logger logger = LoggerFactory.getLogger(CfgSysRegistryServiceImpl.class); }
863
0.842105
0.823392
27
30.666666
36.298149
140
false
false
0
0
0
0
0
0
0.407407
false
false
2
7a82ad57156ed21d0ef1c175d3aad9ba7ea86ad7
6,828,998,020,516
8e4e95497ce842b00d9d2d37077f6cd8379d3054
/src/main/java/com/ai/eis/common/DataGrid.java
9b1f6f639e988f49771cadd9c89e42edbd5d380d
[]
no_license
MHZH-EIS/fjt
https://github.com/MHZH-EIS/fjt
6ea358c940b78684753f12037e612dbf612d7fa9
36c49b0eb07f54280eec76d063b0eb60908416a4
refs/heads/master
2022-08-20T21:53:38.904000
2022-07-25T08:09:33
2022-07-25T08:09:33
166,506,772
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ai.eis.common; import org.springframework.data.domain.Page; public final class DataGrid<T> { private Long total; private Iterable<T> rows; private Iterable<?> footer; public DataGrid(Iterable<T> rows) { this.rows = rows; } public DataGrid(Long total, Iterable<T> rows) { this.total = total; this.rows = rows; } public Long getTotal() { return total; } public DataGrid(Page<T> page) { this.total = page.getTotalElements(); this.rows = page.getContent(); } public void setTotal(Long total) { this.total = total; } public Iterable<T> getRows() { return rows; } public void setRows(Iterable<T> rows) { this.rows = rows; } public Iterable<?> getFooter() { return footer; } public void setFooter(Iterable<?> footer) { this.footer = footer; } }
UTF-8
Java
807
java
DataGrid.java
Java
[]
null
[]
package com.ai.eis.common; import org.springframework.data.domain.Page; public final class DataGrid<T> { private Long total; private Iterable<T> rows; private Iterable<?> footer; public DataGrid(Iterable<T> rows) { this.rows = rows; } public DataGrid(Long total, Iterable<T> rows) { this.total = total; this.rows = rows; } public Long getTotal() { return total; } public DataGrid(Page<T> page) { this.total = page.getTotalElements(); this.rows = page.getContent(); } public void setTotal(Long total) { this.total = total; } public Iterable<T> getRows() { return rows; } public void setRows(Iterable<T> rows) { this.rows = rows; } public Iterable<?> getFooter() { return footer; } public void setFooter(Iterable<?> footer) { this.footer = footer; } }
807
0.674102
0.674102
50
15.14
15.393518
48
false
false
0
0
0
0
0
0
1.2
false
false
2
5c4e3526f8c1b7e02133a5776dedb4090ac45fed
23,622,320,171,701
02c637f3f8719d9a025ac902002f914d81ce8710
/src/Java/Model/user/Bill.java
068fe192e59028bf00a103bb2bb28dd7aaf502f4
[]
no_license
datism/Electronic-shop
https://github.com/datism/Electronic-shop
e750af131cae3c8823f79aa5bc3b00df590ab7f2
f5d169dec9b986701483b9f53d86aeba6089ba26
refs/heads/master
2023-04-28T11:02:41.694000
2021-05-20T09:14:01
2021-05-20T09:14:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Thanh vien xay dung: An, Dung package Java.Model.user; import java.sql.Date; // hoa don tren database public class Bill { private int userId; private Date date; public int money; public Bill(int userId) { this.userId = userId; long millis = System.currentTimeMillis(); date = new Date(millis); money = 0; } public Bill(int userId, Date date, int money) { this.userId = userId; this.date = date; this.money = money; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public void action(int gia, int soLuong) { this.money += gia * soLuong; } }
UTF-8
Java
997
java
Bill.java
Java
[ { "context": "//Thanh vien xay dung: An, Dung\n\npackage Java.Model.user;\n\nimport java.sql.Date;\n", "end": 31, "score": 0.9982861280441284, "start": 23, "tag": "NAME", "value": "An, Dung" } ]
null
[]
//Thanh vien xay dung: <NAME> package Java.Model.user; import java.sql.Date; // hoa don tren database public class Bill { private int userId; private Date date; public int money; public Bill(int userId) { this.userId = userId; long millis = System.currentTimeMillis(); date = new Date(millis); money = 0; } public Bill(int userId, Date date, int money) { this.userId = userId; this.date = date; this.money = money; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public void action(int gia, int soLuong) { this.money += gia * soLuong; } }
995
0.563691
0.562688
54
17.462963
14.673879
51
false
false
0
0
0
0
0
0
0.425926
false
false
2
399ae688838fb6dc6bcef24be7aa941c3e2a368d
31,533,649,888,284
eabc8d55d7b0db96d7c7913ce6044279b3e08625
/src/main/java/com/vantago/kraftwerke/controllers/AnlageController.java
32979522588dc38bb5a2fffdc113febd9b2dfe32
[]
no_license
geoweber/kraftwerke
https://github.com/geoweber/kraftwerke
2901ae26ffd48ac143ea00d9ca9c1f4816195962
c1c035d92a7d11d71f5b40d34ce1d7b698335e0b
refs/heads/master
2021-05-21T04:32:15.955000
2020-04-06T14:30:30
2020-04-06T14:30:30
252,544,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vantago.kraftwerke.controllers; import com.vantago.kraftwerke.model.Anlage; import com.vantago.kraftwerke.service.AnlageService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @Controller public class AnlageController { private final AnlageService anlageService; public AnlageController(final AnlageService anlageService) { this.anlageService = anlageService; } /** * List of anlagen * * @param model - a holder for model attributes. * @return outcome */ @GetMapping("/anlage") public String anlage(Model model) { List<Anlage> anlagen = anlageService.findAll(); model.addAttribute("anlagen", anlagen); return "anlagen"; } /** * detailed view for selected Anlage * * @param id - id of cart * @param model -a holder for model attributes. * @return outcome */ @GetMapping("/anlage/{id}") public String anlageById(@PathVariable Long id, Model model) throws ObjectNotFoundException { Anlage object = anlageService.findById(id).orElseThrow(() -> new ObjectNotFoundException("Anlage [id" + id + "] not found")); model.addAttribute("anlage", object); return "anlage"; } }
UTF-8
Java
1,426
java
AnlageController.java
Java
[]
null
[]
package com.vantago.kraftwerke.controllers; import com.vantago.kraftwerke.model.Anlage; import com.vantago.kraftwerke.service.AnlageService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; @Controller public class AnlageController { private final AnlageService anlageService; public AnlageController(final AnlageService anlageService) { this.anlageService = anlageService; } /** * List of anlagen * * @param model - a holder for model attributes. * @return outcome */ @GetMapping("/anlage") public String anlage(Model model) { List<Anlage> anlagen = anlageService.findAll(); model.addAttribute("anlagen", anlagen); return "anlagen"; } /** * detailed view for selected Anlage * * @param id - id of cart * @param model -a holder for model attributes. * @return outcome */ @GetMapping("/anlage/{id}") public String anlageById(@PathVariable Long id, Model model) throws ObjectNotFoundException { Anlage object = anlageService.findById(id).orElseThrow(() -> new ObjectNotFoundException("Anlage [id" + id + "] not found")); model.addAttribute("anlage", object); return "anlage"; } }
1,426
0.68864
0.68864
49
28.102041
27.268314
133
false
false
0
0
0
0
0
0
0.387755
false
false
2
60ae2a1c770f7ad6f2aeb5d639ed34bab99bc81e
31,396,210,965,745
68d8a56fc895926b373589da773e1d31b054f95a
/src/filter/UTF8Filter.java
955e30abf6b3bc43755005447f8bd789d041da79
[]
no_license
CODEX-Inc/Codex
https://github.com/CODEX-Inc/Codex
847d3b38b5d8911b267afe5433be4925475ed743
754c06d714e1a45a68c157dc0222bd01cda5d94b
refs/heads/master
2018-05-18T22:42:56.915000
2014-07-21T09:27:30
2014-07-21T09:27:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package filter; 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.http.HttpServletRequest; public class UTF8Filter implements Filter { public UTF8Filter() { super(); } public void init(FilterConfig arg0) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; httpRequest.setCharacterEncoding("UTF-8"); if(chain!=null)chain.doFilter(request,response); } public void destroy() { } }
UTF-8
Java
841
java
UTF8Filter.java
Java
[]
null
[]
package filter; 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.http.HttpServletRequest; public class UTF8Filter implements Filter { public UTF8Filter() { super(); } public void init(FilterConfig arg0) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; httpRequest.setCharacterEncoding("UTF-8"); if(chain!=null)chain.doFilter(request,response); } public void destroy() { } }
841
0.741974
0.737218
33
24.515152
23.895126
74
false
false
0
0
0
0
0
0
0.515152
false
false
2
e4f4beb72e8ceb8405bb876a0a13db2358aa0908
35,038,343,207,461
4899564979231990acdf348723100cd7c33f0051
/src/main/java/rest_api/config/PropertiesConfig.java
1d6a3ada38eae94c6cae451c69c56548e86e15e2
[]
no_license
f39pfce/spring-boot-rest-api
https://github.com/f39pfce/spring-boot-rest-api
1f95279bd951c1933c8001317cae60be18351189
3cbc01a37b59322ebd163ca358920ced44804b17
refs/heads/master
2020-03-27T13:45:22.727000
2018-08-29T16:17:02
2018-08-29T16:17:02
146,626,621
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package rest_api.config; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; /** * See http://www.baeldung.com/configuration-properties-in-spring-boot, this class converts properties such as those * in application.properties into either values, lists or objects - this allows end users to interact with config values * as objects or lists in cases where the config values are related to one another */ @Setter @Getter @Validated @Configuration @ConfigurationProperties(prefix = "application") public class PropertiesConfig { /** * How request logs are stored, must match enum of RequestLogType */ @NotBlank private String requestLogType; /** * If when merchants are saved boarding to First Data occurs */ private boolean firstDataBoardOnSave; /** * If when payments are saved boarding to IPG occurs */ private boolean ipgBoardOnSave; /** * Credentials for First Data boarding */ private FirstDataBoarding firstDataBoarding = new FirstDataBoarding(); /** * Credentials for Bluepay API email */ private BluepayApiEmail bluepayApiEmail = new BluepayApiEmail(); /** * Security settings */ private Security security = new Security(); /** * PayEezy credentials */ private PayeezyGateway payeezyGateway = new PayeezyGateway(); /** * Credentials for First Data boarding */ @Setter @Getter public static class FirstDataBoarding { /** * First Data boarding URL */ @URL @NotBlank private String url; /** * First Data boarding API user name */ @Email @NotBlank private String user; /** * First Data boarding API secret key */ @NotBlank private String secretKey; } /** * Credentials for Bluepay API email */ @Setter @Getter public static class BluepayApiEmail { /** * Host name */ @NotBlank private String host; /** * Port to connect to */ @NotNull private Integer port; /** * Username (email address) */ @NotNull private String username; /** * User's password */ @NotNull private String password; } /** * Security settings */ @Setter @Getter public static class Security { /** * Security type, must match enum of SecurityType */ @NotBlank private String type; /** * The signing key shared between client and server */ @NotBlank private String jwtSigningKey; /** * Number of seconds the OAuth token remains valid */ @NotNull private Integer jwtTokenValidSeconds; } /** * PayEezy API credentials */ @Setter @Getter public static class PayeezyGateway { /** * Boarding API */ @URL @NotBlank private String url; /** * API key - currently using same key for all merchants for testing purposes */ @NotBlank private String apiKey; /** * API secret - tied to apiKey above */ @NotBlank private String apiSecret; /** * API token - tied to apiKey above */ @NotBlank private String token; } }
UTF-8
Java
3,944
java
PropertiesConfig.java
Java
[]
null
[]
package rest_api.config; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.validation.annotation.Validated; import javax.validation.constraints.NotNull; /** * See http://www.baeldung.com/configuration-properties-in-spring-boot, this class converts properties such as those * in application.properties into either values, lists or objects - this allows end users to interact with config values * as objects or lists in cases where the config values are related to one another */ @Setter @Getter @Validated @Configuration @ConfigurationProperties(prefix = "application") public class PropertiesConfig { /** * How request logs are stored, must match enum of RequestLogType */ @NotBlank private String requestLogType; /** * If when merchants are saved boarding to First Data occurs */ private boolean firstDataBoardOnSave; /** * If when payments are saved boarding to IPG occurs */ private boolean ipgBoardOnSave; /** * Credentials for First Data boarding */ private FirstDataBoarding firstDataBoarding = new FirstDataBoarding(); /** * Credentials for Bluepay API email */ private BluepayApiEmail bluepayApiEmail = new BluepayApiEmail(); /** * Security settings */ private Security security = new Security(); /** * PayEezy credentials */ private PayeezyGateway payeezyGateway = new PayeezyGateway(); /** * Credentials for First Data boarding */ @Setter @Getter public static class FirstDataBoarding { /** * First Data boarding URL */ @URL @NotBlank private String url; /** * First Data boarding API user name */ @Email @NotBlank private String user; /** * First Data boarding API secret key */ @NotBlank private String secretKey; } /** * Credentials for Bluepay API email */ @Setter @Getter public static class BluepayApiEmail { /** * Host name */ @NotBlank private String host; /** * Port to connect to */ @NotNull private Integer port; /** * Username (email address) */ @NotNull private String username; /** * User's password */ @NotNull private String password; } /** * Security settings */ @Setter @Getter public static class Security { /** * Security type, must match enum of SecurityType */ @NotBlank private String type; /** * The signing key shared between client and server */ @NotBlank private String jwtSigningKey; /** * Number of seconds the OAuth token remains valid */ @NotNull private Integer jwtTokenValidSeconds; } /** * PayEezy API credentials */ @Setter @Getter public static class PayeezyGateway { /** * Boarding API */ @URL @NotBlank private String url; /** * API key - currently using same key for all merchants for testing purposes */ @NotBlank private String apiKey; /** * API secret - tied to apiKey above */ @NotBlank private String apiSecret; /** * API token - tied to apiKey above */ @NotBlank private String token; } }
3,944
0.592292
0.592292
177
21.282486
21.741661
120
false
false
0
0
0
0
0
0
0.19774
false
false
2
aea3d6153e4cfda0f9b6b020effdb5e302068327
10,599,979,351,979
0e227d310859edaa0502b79e2154b75dc714d257
/quiz/src/quiz/Collection/Quiz20.java
214992bbaa46eddc2cf2c9e1f2dcdab986bd06da
[]
no_license
delilah1004/Kitri_Training1
https://github.com/delilah1004/Kitri_Training1
cee158bdbccd02f2d9511bb3baea737bd25e9c0d
a6e03e83437d82a4866217d89ec125eb6854e4a0
refs/heads/master
2022-09-26T11:21:08.063000
2020-06-09T01:32:30
2020-06-09T01:32:30
270,874,302
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package quiz.Collection; import java.util.HashMap; import java.util.Scanner; public class Quiz20 { public static void main(String[] args) { HashMap<String, String> person = new HashMap<String, String>(); Scanner sc = new Scanner(System.in); String name, phone; for (int i = 0; i < 5; i++) { System.out.print("이름 : "); name = sc.next(); System.out.print("전화번호 : "); phone = sc.next(); person.put(name, phone); System.out.println(); } System.out.print("전화번호를 검색할 이름을 입력하세요 : "); name = sc.next(); System.out.print(name + "의 전화번호는 " + person.get(name) + " 입니다."); sc.close(); } }
UTF-8
Java
700
java
Quiz20.java
Java
[]
null
[]
package quiz.Collection; import java.util.HashMap; import java.util.Scanner; public class Quiz20 { public static void main(String[] args) { HashMap<String, String> person = new HashMap<String, String>(); Scanner sc = new Scanner(System.in); String name, phone; for (int i = 0; i < 5; i++) { System.out.print("이름 : "); name = sc.next(); System.out.print("전화번호 : "); phone = sc.next(); person.put(name, phone); System.out.println(); } System.out.print("전화번호를 검색할 이름을 입력하세요 : "); name = sc.next(); System.out.print(name + "의 전화번호는 " + person.get(name) + " 입니다."); sc.close(); } }
700
0.605016
0.598746
31
19.612904
18.085241
67
false
false
0
0
0
0
0
0
2.419355
false
false
2
23341d45a9ea61a824231ef4ad93aff3556cab97
28,647,431,882,930
cb9cd96f194544a7398b93186185fb1885683cbb
/producer-service-interface/src/main/java/app/producer/api/producer/ProducerCreatedRequest.java
48173e2967d970364b8c8697c1829fde11d999d5
[]
no_license
Faramita2/homework-project
https://github.com/Faramita2/homework-project
adadee425630d11a479d7b8ef06e8ceeeb7e362b
4d812f9f3545ee52cff53dc658d151402bcf170b
refs/heads/master
2022-11-09T21:11:04.115000
2020-06-21T05:03:02
2020-06-21T05:03:02
271,200,072
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.producer.api.producer; import core.framework.api.json.Property; /** * @author zoo */ public class ProducerCreatedRequest { @Property(name = "desc") public String desc; }
UTF-8
Java
194
java
ProducerCreatedRequest.java
Java
[ { "context": " core.framework.api.json.Property;\n\n/**\n * @author zoo\n */\npublic class ProducerCreatedRequest {\n @Pr", "end": 96, "score": 0.9991438984870911, "start": 93, "tag": "USERNAME", "value": "zoo" } ]
null
[]
package app.producer.api.producer; import core.framework.api.json.Property; /** * @author zoo */ public class ProducerCreatedRequest { @Property(name = "desc") public String desc; }
194
0.706186
0.706186
11
16.636364
15.399366
40
false
false
0
0
0
0
0
0
0.272727
false
false
2
f6f5674e1715ca873ac4ffe2d44d5a38b92537de
20,349,555,063,073
a60475e2f641b551855f6111ef2794d0c3d91e35
/src/main/java/com/expensemanager/expensemanager/mapper/MerchantMapper.java
db10b1c8fb43c20c1deca77556691e6ac7bf59be
[]
no_license
stefansn/jwt-authentication
https://github.com/stefansn/jwt-authentication
84371d07fa91fff53559fd450b279c2fbaf3700b
539663a19f66ae91b8fe823164ebe82f7b638993
refs/heads/master
2020-06-28T21:21:26.242000
2019-08-03T07:22:00
2019-08-03T07:22:00
200,345,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.expensemanager.expensemanager.mapper; import com.expensemanager.expensemanager.dto.MerchantDto; import com.expensemanager.expensemanager.model.Merchant; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface MerchantMapper { MerchantDto toDto(Merchant merchant); Merchant toEntity(MerchantDto merchantDto); }
UTF-8
Java
357
java
MerchantMapper.java
Java
[]
null
[]
package com.expensemanager.expensemanager.mapper; import com.expensemanager.expensemanager.dto.MerchantDto; import com.expensemanager.expensemanager.model.Merchant; import org.mapstruct.Mapper; @Mapper(componentModel = "spring") public interface MerchantMapper { MerchantDto toDto(Merchant merchant); Merchant toEntity(MerchantDto merchantDto); }
357
0.823529
0.823529
11
31.454546
20.938715
57
false
false
0
0
0
0
0
0
0.545455
false
false
2
25272661a51a1f33222faf02e917cd30157761fc
17,763,984,762,245
1b32f5cdfd69752214a8fb4a806a64a62a20de10
/JAVA/student/src/com/testyantra/student/jspiders/React.java
083139e229c7a814edb58d07d781d188123b1896
[]
no_license
karthikmg10/Manthan-ELF-16th-oct-Karthik-MG
https://github.com/karthikmg10/Manthan-ELF-16th-oct-Karthik-MG
2ae4d2af2fa3602283db1e94da62bdaec1229e61
5e2e448d991358921b1350a8708b7177e90d1a40
refs/heads/master
2020-09-16T19:41:44.160000
2019-12-10T03:08:31
2019-12-10T03:08:31
222,646,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.testyantra.student.jspiders; public class React { public void teachReact() { System.out.println("I am teaching React() method"); } }
UTF-8
Java
154
java
React.java
Java
[]
null
[]
package com.testyantra.student.jspiders; public class React { public void teachReact() { System.out.println("I am teaching React() method"); } }
154
0.707792
0.707792
11
13
18.300522
53
false
false
0
0
0
0
0
0
0.545455
false
false
2
7bc180eb6a5de4ba36665f82ab96b6f0a2fa5b89
28,209,345,251,177
ecd4be5d6c9cef9218a57f282abd327cf4321c55
/Simulacao/src/Exercicio1/Impressora.java
7322b2f8ba626b2fd3537faa30f33960993b3661
[]
no_license
C42016/Maxima
https://github.com/C42016/Maxima
0115b978e370375a484077816e11de23453de4f1
c0ac8d40e758cd489aacef787ee5ac481c3bcb85
refs/heads/master
2021-01-23T05:51:21.669000
2017-09-05T13:03:05
2017-09-05T13:03:05
102,479,484
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 Exercicio1; /** * * @author Euridia */ public class Impressora extends Produto { String velocImpressao; public Impressora(String velocImpressao, double numeroSerie, String tipo) { super(numeroSerie, tipo); this.velocImpressao = velocImpressao; } @Override public String ligar(){ return "a impressora esta pronto para receber documentos"; } @Override public String desligar(){ return "a impressora nao esta mais disponivel"; } public String imprimir(){ return "a impressora esta em uso"; } @Override public String toString() { return super.toString() + "velocImpressao=" + velocImpressao; } }
UTF-8
Java
904
java
Impressora.java
Java
[ { "context": "editor.\n */\npackage Exercicio1;\n\n/**\n *\n * @author Euridia\n */\npublic class Impressora extends Produto {\n ", "end": 231, "score": 0.9997068643569946, "start": 224, "tag": "NAME", "value": "Euridia" } ]
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 Exercicio1; /** * * @author Euridia */ public class Impressora extends Produto { String velocImpressao; public Impressora(String velocImpressao, double numeroSerie, String tipo) { super(numeroSerie, tipo); this.velocImpressao = velocImpressao; } @Override public String ligar(){ return "a impressora esta pronto para receber documentos"; } @Override public String desligar(){ return "a impressora nao esta mais disponivel"; } public String imprimir(){ return "a impressora esta em uso"; } @Override public String toString() { return super.toString() + "velocImpressao=" + velocImpressao; } }
904
0.660398
0.659292
40
21.5
23.2379
79
false
false
0
0
0
0
0
0
0.35
false
false
2
f6055575d01ecf0a24950d13c3dd30d8099e14b3
8,504,035,304,780
9764d57b4c83fae1b3d25d65dd3013105e54e93b
/app/src/main/java/com/cloudsource/realmtest/MainActivity.java
993232190aa970efc584876f9a0a1d317278104d
[]
no_license
azumag/realmtest
https://github.com/azumag/realmtest
bac57a6996dd41c19a9b44669db033c7785a45be
5e2c50c275e45934babd6adcb812988d5ad53bdd
refs/heads/master
2016-09-17T10:45:37.159000
2016-08-10T08:40:38
2016-08-10T08:40:38
65,359,706
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cloudsource.realmtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import io.realm.Realm; import io.realm.RealmConfiguration; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // copyBundledRealmFile(this.getResources().openRawResource(R.raw.test), "test"); RealmConfiguration config0 = new RealmConfiguration.Builder(this).assetFile(this, "test.realm") .name("test") .schemaVersion(1) .migration(new Migration()) .build(); // try { // Realm.migrateRealm // (config0, new Migration()); // } catch (FileNotFoundException ignored) { // // If the Realm file doesn't exist, just ignore. // Log.i("mylog", "notfound"); // } Realm realm = Realm.getInstance(config0); showStatus("test"); showStatus(realm); realm.close(); // RealmConfiguration realmconfig = new RealmConfiguration.Builder(this).name("realmtest.realm").build(); // Realm.setDefaultConfiguration(realmconfig); // Realm realm = Realm.getDefaultInstance(); // setContentView(R.layout.activity_main); // realm.close(); } private String realmString(Realm realm) { StringBuilder stringBuilder = new StringBuilder(); for (history_tbl c : realm.where(history_tbl.class).findAll()) { stringBuilder.append(c.toString()).append("\n"); } return (stringBuilder.length() == 0) ? "<data was deleted>" : stringBuilder.toString(); } private void showStatus(Realm realm) { showStatus(realmString(realm)); } private void showStatus(String txt) { Log.i("mylog", txt); } private String copyBundledRealmFile(InputStream inputStream, String outFileName) { try { File file = new File(this.getFilesDir(), outFileName); FileOutputStream outputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bytesRead); } outputStream.close(); return file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } return null; } }
UTF-8
Java
2,674
java
MainActivity.java
Java
[]
null
[]
package com.cloudsource.realmtest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import io.realm.Realm; import io.realm.RealmConfiguration; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // copyBundledRealmFile(this.getResources().openRawResource(R.raw.test), "test"); RealmConfiguration config0 = new RealmConfiguration.Builder(this).assetFile(this, "test.realm") .name("test") .schemaVersion(1) .migration(new Migration()) .build(); // try { // Realm.migrateRealm // (config0, new Migration()); // } catch (FileNotFoundException ignored) { // // If the Realm file doesn't exist, just ignore. // Log.i("mylog", "notfound"); // } Realm realm = Realm.getInstance(config0); showStatus("test"); showStatus(realm); realm.close(); // RealmConfiguration realmconfig = new RealmConfiguration.Builder(this).name("realmtest.realm").build(); // Realm.setDefaultConfiguration(realmconfig); // Realm realm = Realm.getDefaultInstance(); // setContentView(R.layout.activity_main); // realm.close(); } private String realmString(Realm realm) { StringBuilder stringBuilder = new StringBuilder(); for (history_tbl c : realm.where(history_tbl.class).findAll()) { stringBuilder.append(c.toString()).append("\n"); } return (stringBuilder.length() == 0) ? "<data was deleted>" : stringBuilder.toString(); } private void showStatus(Realm realm) { showStatus(realmString(realm)); } private void showStatus(String txt) { Log.i("mylog", txt); } private String copyBundledRealmFile(InputStream inputStream, String outFileName) { try { File file = new File(this.getFilesDir(), outFileName); FileOutputStream outputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, bytesRead); } outputStream.close(); return file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } return null; } }
2,674
0.621915
0.617427
88
29.386364
26.459846
112
false
false
0
0
0
0
0
0
0.556818
false
false
2
4a3575c5ceb93077973878b80db6e312a1c614b3
27,315,992,046,917
7fa9cb70213c51095ef4ceaa2624c63ba0455f07
/Codeup/src/Ex1095_2.java
c2e2253df551cfa441e6efd4fc6dc41e5135f828
[]
no_license
kkyu8925/java-study
https://github.com/kkyu8925/java-study
79edfd735fa3cb369f6884d8a0aa531b1828b49d
f4459c3fa5c93142859bb026e294084df8365a17
refs/heads/master
2023-04-15T02:09:14.272000
2021-07-08T16:40:23
2021-07-08T16:40:23
262,197,924
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Scanner; public class Ex1095_2 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int[] a = new int[23]; int b = s.nextInt(); for (int i = 0; i < b; i++) { int num = s.nextInt(); a[num - 1]++; } for (int j = 0; j < 23; j++) { if (a[j] > 0) { System.out.println(j + 1); break; } } } }
UTF-8
Java
393
java
Ex1095_2.java
Java
[]
null
[]
import java.util.Scanner; public class Ex1095_2 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int[] a = new int[23]; int b = s.nextInt(); for (int i = 0; i < b; i++) { int num = s.nextInt(); a[num - 1]++; } for (int j = 0; j < 23; j++) { if (a[j] > 0) { System.out.println(j + 1); break; } } } }
393
0.480916
0.445293
24
14.458333
13.656437
41
false
false
0
0
0
0
0
0
2
false
false
2
c15b5f065a2a80517ce3998cbef15ae4a31506ae
27,315,992,049,090
243382af0fa4e4a3b0e79ada5a4f2cef8ab7b1aa
/njhw/src/com/cosmosource/app/utils/Constant.java
be70f5fbda05bea8a10019bddd13ddb784c028de
[]
no_license
cataclyzh/njhw
https://github.com/cataclyzh/njhw
c77ad5c01ae5e7a5c417dcee9bde1d338e1ad291
852951f6267f69ed121ad2c0ca7dcd84786a79e0
refs/heads/master
2021-01-21T04:41:57.260000
2016-03-31T06:15:47
2016-03-31T06:15:47
54,610,882
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cosmosource.app.utils; /** * * @description: app 常量配置 * @author herb * @date May 14, 2013 11:19:03 AM */ public class Constant { /*内容管理栏目*/ //失物招领 public static final long CMS_LOST_AND_FOUND = 1; //ip电话帮助 public static final long CMS_IP_HELP = 3; //保洁部ID public static final long ORG_CLEANING_ID = 219; //巡更部ID public static final long ORG_PATROL_ID = 215; //维修部ID public static final long ORG_REPAIR_ID = 220; }
UTF-8
Java
513
java
Constant.java
Java
[ { "context": "ls;\r\n/**\r\n * \r\n* @description: app 常量配置\r\n* @author herb\r\n* @date May 14, 2013 11:19:03 AM\r\n */\r\npublic cl", "end": 86, "score": 0.9911335706710815, "start": 82, "tag": "USERNAME", "value": "herb" } ]
null
[]
package com.cosmosource.app.utils; /** * * @description: app 常量配置 * @author herb * @date May 14, 2013 11:19:03 AM */ public class Constant { /*内容管理栏目*/ //失物招领 public static final long CMS_LOST_AND_FOUND = 1; //ip电话帮助 public static final long CMS_IP_HELP = 3; //保洁部ID public static final long ORG_CLEANING_ID = 219; //巡更部ID public static final long ORG_PATROL_ID = 215; //维修部ID public static final long ORG_REPAIR_ID = 220; }
513
0.660131
0.610022
20
20.950001
17.139063
49
false
false
0
0
0
0
0
0
0.9
false
false
2
7fbfade54c4afcabc2d15395c6ab347f9eba74ad
18,691,697,684,408
e7e506cac9c690babd1750650a7990455ac91a7c
/src/main/java/String_DataStructures/SubstringwithConcatenationofAllWords.java
9c645e38503898bd657441733a46460fd06035be
[]
no_license
Venkata09/JavaWorks
https://github.com/Venkata09/JavaWorks
408fa1400e7d0788c4802463650f7002df780618
5469e825f9404b7cb85586fca64caf79eec6065f
refs/heads/master
2020-03-03T23:56:37.729000
2019-12-04T12:54:40
2019-12-04T12:54:40
95,312,401
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package String_DataStructures; import java.util.ArrayList; import java.util.HashMap; /** * Created by vdokku on 8/18/2017. */ /* You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: S: “barfoothefoobarman” L: [“foo”, “bar”] You should return the indices: [0,9]. (order does not matter). */ public class SubstringwithConcatenationofAllWords { public ArrayList<Integer> findSubString_1(String S, String[] L) { ArrayList<Integer> res = new ArrayList<Integer>(); if (L[0].length() > S.length()) return res; HashMap<String, Integer> visited = new HashMap<String, Integer>(); for (int i = 0; i < L.length; i++) { if (visited.containsKey(L[i])) visited.put(L[i], visited.get(L[i]) + 1); else visited.put(L[i], 1); } //only check start = 0 ~ L.length for (int i = 0; i <= S.length() - L.length * L[0].length(); i++) { HashMap<String, Integer> curr = new HashMap<String, Integer>(visited); //divide the substring in to L[0].length strings and compare for (int j = 0; j < L.length * L[0].length(); j += L[0].length()) { // this step is important, keep searching until find an unmatched array or fisish searching and put in the final result if (!check(curr, S.substring(i + j, i + j + L[0].length()))) break; if (j == L.length * L[0].length() - L[0].length()) { res.add(i); break; } } } return res; } /* Just scan word by word, but can stop at S.length – m*n. also the checking can be done using a hashmap. This is like finding a substring with all characters, but using String instead of characters */ public ArrayList<Integer> findSubstring(String S, String[] L) { ArrayList<Integer> res = new ArrayList<Integer>(); //build map HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < L.length; i++) { if (map.containsKey(L[i])) { map.put(L[i], map.get(L[i]) + 1); } else { map.put(L[i], 1); } } int len = L[0].length() * L.length; for (int i = 0; i <= S.length() - len; i++) { if (exist(S.substring(i, i + len), map, L[0].length())) { res.add(i); } } return res; } public boolean exist(String s, HashMap<String, Integer> map, int wordLen) { HashMap<String, Integer> visited = new HashMap<String, Integer>(map); for (int i = 0; i <= s.length() - wordLen; i += wordLen) { String tmp = s.substring(i, i + wordLen); if (!check(visited, tmp)) return false; } return true; } public boolean check(HashMap<String, Integer> visited, String s) { if (visited.containsKey(s)) if (visited.get(s) != 0) { visited.put(s, visited.get(s) - 1); return true; } return false; } }
UTF-8
Java
3,400
java
SubstringwithConcatenationofAllWords.java
Java
[ { "context": "List;\nimport java.util.HashMap;\n\n/**\n * Created by vdokku on 8/18/2017.\n */\n\n/*\n\n\nYou are given a string, S", "end": 111, "score": 0.9996280670166016, "start": 105, "tag": "USERNAME", "value": "vdokku" } ]
null
[]
package String_DataStructures; import java.util.ArrayList; import java.util.HashMap; /** * Created by vdokku on 8/18/2017. */ /* You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: S: “barfoothefoobarman” L: [“foo”, “bar”] You should return the indices: [0,9]. (order does not matter). */ public class SubstringwithConcatenationofAllWords { public ArrayList<Integer> findSubString_1(String S, String[] L) { ArrayList<Integer> res = new ArrayList<Integer>(); if (L[0].length() > S.length()) return res; HashMap<String, Integer> visited = new HashMap<String, Integer>(); for (int i = 0; i < L.length; i++) { if (visited.containsKey(L[i])) visited.put(L[i], visited.get(L[i]) + 1); else visited.put(L[i], 1); } //only check start = 0 ~ L.length for (int i = 0; i <= S.length() - L.length * L[0].length(); i++) { HashMap<String, Integer> curr = new HashMap<String, Integer>(visited); //divide the substring in to L[0].length strings and compare for (int j = 0; j < L.length * L[0].length(); j += L[0].length()) { // this step is important, keep searching until find an unmatched array or fisish searching and put in the final result if (!check(curr, S.substring(i + j, i + j + L[0].length()))) break; if (j == L.length * L[0].length() - L[0].length()) { res.add(i); break; } } } return res; } /* Just scan word by word, but can stop at S.length – m*n. also the checking can be done using a hashmap. This is like finding a substring with all characters, but using String instead of characters */ public ArrayList<Integer> findSubstring(String S, String[] L) { ArrayList<Integer> res = new ArrayList<Integer>(); //build map HashMap<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < L.length; i++) { if (map.containsKey(L[i])) { map.put(L[i], map.get(L[i]) + 1); } else { map.put(L[i], 1); } } int len = L[0].length() * L.length; for (int i = 0; i <= S.length() - len; i++) { if (exist(S.substring(i, i + len), map, L[0].length())) { res.add(i); } } return res; } public boolean exist(String s, HashMap<String, Integer> map, int wordLen) { HashMap<String, Integer> visited = new HashMap<String, Integer>(map); for (int i = 0; i <= s.length() - wordLen; i += wordLen) { String tmp = s.substring(i, i + wordLen); if (!check(visited, tmp)) return false; } return true; } public boolean check(HashMap<String, Integer> visited, String s) { if (visited.containsKey(s)) if (visited.get(s) != 0) { visited.put(s, visited.get(s) - 1); return true; } return false; } }
3,400
0.533077
0.523331
113
28.964602
28.841627
135
false
false
0
0
0
0
0
0
0.672566
false
false
2
2f8a31dba6a742abe2b8aa76c159ada253d2a01b
3,865,470,595,689
46772468cf1e9116a334b1cf95f38c8b6f24bfb0
/src/by/it/kuzmichaa/jd01_03/Runner.java
5a114c169500507ee0b6f58fbd677a512a34e0bb
[]
no_license
ilyashpakovski/JD2019-12-03
https://github.com/ilyashpakovski/JD2019-12-03
3f8b0d0d73103bc1a925fd18dcae4850149da45e
80efcd87697ec00370305eacb5ee6f0f37dd14a0
refs/heads/master
2020-11-25T07:30:37.036000
2020-03-04T18:22:06
2020-03-04T18:22:06
228,557,550
1
2
null
true
2019-12-17T07:23:07
2019-12-17T07:23:06
2019-12-16T21:57:00
2019-12-16T21:56:58
328
0
0
0
null
false
false
package by.it.kuzmichaa.jd01_03; import java.util.Scanner; public class Runner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); double[] array = InOut.getArray(str); InOut.printArray(array); InOut.printArray(array, "V", 2); System.out.println(Helper.findMin(array)); System.out.println(Helper.findMax(array)); Helper.sort(array); for (double arr : array) System.out.print(arr + " "); System.out.println(); double [][] matrix = { {1, 2, 3}, {3, 2, 0}, {1, 5, 3}, }; double [] vector = {5, 3, 2}; Helper.mul(matrix, vector); } }
UTF-8
Java
771
java
Runner.java
Java
[]
null
[]
package by.it.kuzmichaa.jd01_03; import java.util.Scanner; public class Runner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); double[] array = InOut.getArray(str); InOut.printArray(array); InOut.printArray(array, "V", 2); System.out.println(Helper.findMin(array)); System.out.println(Helper.findMax(array)); Helper.sort(array); for (double arr : array) System.out.print(arr + " "); System.out.println(); double [][] matrix = { {1, 2, 3}, {3, 2, 0}, {1, 5, 3}, }; double [] vector = {5, 3, 2}; Helper.mul(matrix, vector); } }
771
0.53048
0.508431
30
24.700001
18.540316
61
false
false
0
0
0
0
0
0
0.966667
false
false
2
54bac051926be0ce0fe655411702028af64c706a
395,136,997,728
6d16a049b01d2c23451efa32f218b26191964f75
/src/cn/digitalpublishing/service/impl/CrRightServiceImpl.java
bb030c5be6be87e621e9b96c1efac58d84b8f286
[]
no_license
yxxcrtd/Copyright
https://github.com/yxxcrtd/Copyright
04e738cf8696dbf4cec505f86d5c87ae5eb45570
30f96afc5e78d870c5a941c2e295034d9e7c60ed
refs/heads/master
2020-05-31T21:30:58.502000
2019-06-06T02:23:34
2019-06-06T02:23:34
190,499,705
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.digitalpublishing.service.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.google.common.base.Strings; import cn.com.daxtech.framework.bean.HqlBean; import cn.com.daxtech.framework.exception.CcsException; import cn.com.daxtech.framework.util.hql.HqlBeanCacheUtil; import cn.digitalpublishing.constants.DicConstants; import cn.digitalpublishing.po.CrRight; import cn.digitalpublishing.service.CrContractService; import cn.digitalpublishing.service.CrLicenseTypeService; import cn.digitalpublishing.service.CrRightService; import cn.digitalpublishing.util.DicCache; public class CrRightServiceImpl extends BaseServiceImpl implements CrRightService { @Autowired @Qualifier("crLicenseTypeService") protected CrLicenseTypeService crLicenseTypeService; // @Autowired // @Qualifier("proposalService") // protected PProposalService proposalService; @Autowired @Qualifier("crContractService") protected CrContractService crContractService; @Override public void edit(CrRight crRight, Map<String, Object> dic) throws Exception { dic.put("RightContractStatus", DicCache.getDicData(DicConstants.RIGHT_CONTRACT_STATUS)); dic.put("RightExclusiveFlag", DicCache.getDicData(DicConstants.RIGHT_EXCLUSIVE_FLAG)); dic.put("LicenceStartType", DicCache.getDicData(DicConstants.LICENCE_START_TYPE)); dic.put("SettlePeriod", DicCache.getDicData(DicConstants.SETTLE_PERIOD)); Map<String, Object> condition = new HashMap<String, Object>(); dic.put("licenseType", crLicenseTypeService.getList(condition)); // 授权类型 //dic.put("proposal", proposalService.getPProposalList(condition, "")); // 策划 if (Strings.isNullOrEmpty(crRight.getRlicenseId())) { condition.put("licenseEndOn", new Date()); } dic.put("contract", crContractService.getList(condition, "")); // 合同 condition.clear(); } @Override public void insert(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().insert(crRight); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.insertCrRight.error", e); } } @Override public void update(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().update(crRight, CrRight.class.getName(), crRight.getRlicenseId(), null); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.updateCrRight.error", e); } } @Override public void delete(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().delete(CrRight.class.getName(), crRight.getRlicenseId()); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.deleteCrRight.error", e); } } @Override public List<CrRight> getList(Map<String, Object> condition) throws Exception { List<CrRight> list = null; HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getList"); try { list = daoFacade.getCrRightDao().getList(condition, "", hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightList.error", e); } return list; } @Override public List<CrRight> getPagingList(Map<String, Object> condition, String sort, Integer pageCount, Integer countStart) throws Exception { List<CrRight> list = null; HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getPagingList"); try { list = daoFacade.getCrRightDao().getPagingList(condition, sort, pageCount, countStart, hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightPagingList.error", e); } return list; } @Override public Integer getCount(Map<String, Object> condition) throws Exception { Integer num = 0; try { HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getCount"); num = daoFacade.getCrRightDao().getCount(condition, hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightCount.error", e); } return num; } @Override public CrRight get(CrRight crRight) throws Exception { try { crRight = daoFacade.getCrRightDao().get(CrRight.class.getName(), crRight.getRlicenseId()); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRight.error", e); } return crRight; } }
UTF-8
Java
5,117
java
CrRightServiceImpl.java
Java
[]
null
[]
package cn.digitalpublishing.service.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.google.common.base.Strings; import cn.com.daxtech.framework.bean.HqlBean; import cn.com.daxtech.framework.exception.CcsException; import cn.com.daxtech.framework.util.hql.HqlBeanCacheUtil; import cn.digitalpublishing.constants.DicConstants; import cn.digitalpublishing.po.CrRight; import cn.digitalpublishing.service.CrContractService; import cn.digitalpublishing.service.CrLicenseTypeService; import cn.digitalpublishing.service.CrRightService; import cn.digitalpublishing.util.DicCache; public class CrRightServiceImpl extends BaseServiceImpl implements CrRightService { @Autowired @Qualifier("crLicenseTypeService") protected CrLicenseTypeService crLicenseTypeService; // @Autowired // @Qualifier("proposalService") // protected PProposalService proposalService; @Autowired @Qualifier("crContractService") protected CrContractService crContractService; @Override public void edit(CrRight crRight, Map<String, Object> dic) throws Exception { dic.put("RightContractStatus", DicCache.getDicData(DicConstants.RIGHT_CONTRACT_STATUS)); dic.put("RightExclusiveFlag", DicCache.getDicData(DicConstants.RIGHT_EXCLUSIVE_FLAG)); dic.put("LicenceStartType", DicCache.getDicData(DicConstants.LICENCE_START_TYPE)); dic.put("SettlePeriod", DicCache.getDicData(DicConstants.SETTLE_PERIOD)); Map<String, Object> condition = new HashMap<String, Object>(); dic.put("licenseType", crLicenseTypeService.getList(condition)); // 授权类型 //dic.put("proposal", proposalService.getPProposalList(condition, "")); // 策划 if (Strings.isNullOrEmpty(crRight.getRlicenseId())) { condition.put("licenseEndOn", new Date()); } dic.put("contract", crContractService.getList(condition, "")); // 合同 condition.clear(); } @Override public void insert(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().insert(crRight); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.insertCrRight.error", e); } } @Override public void update(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().update(crRight, CrRight.class.getName(), crRight.getRlicenseId(), null); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.updateCrRight.error", e); } } @Override public void delete(CrRight crRight) throws Exception { try { daoFacade.getCrRightDao().delete(CrRight.class.getName(), crRight.getRlicenseId()); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.deleteCrRight.error", e); } } @Override public List<CrRight> getList(Map<String, Object> condition) throws Exception { List<CrRight> list = null; HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getList"); try { list = daoFacade.getCrRightDao().getList(condition, "", hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightList.error", e); } return list; } @Override public List<CrRight> getPagingList(Map<String, Object> condition, String sort, Integer pageCount, Integer countStart) throws Exception { List<CrRight> list = null; HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getPagingList"); try { list = daoFacade.getCrRightDao().getPagingList(condition, sort, pageCount, countStart, hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightPagingList.error", e); } return list; } @Override public Integer getCount(Map<String, Object> condition) throws Exception { Integer num = 0; try { HqlBean hqlBean = HqlBeanCacheUtil.gethqlBeanCache() .get("cn.digitalpublishing.dao.CrRightDao") .get("getCount"); num = daoFacade.getCrRightDao().getCount(condition, hqlBean); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRightCount.error", e); } return num; } @Override public CrRight get(CrRight crRight) throws Exception { try { crRight = daoFacade.getCrRightDao().get(CrRight.class.getName(), crRight.getRlicenseId()); } catch (Exception e) { throw new CcsException((e instanceof CcsException) ? ((CcsException) e).getPrompt() : "crRightService.info.getCrRight.error", e); } return crRight; } }
5,117
0.728681
0.728485
132
36.659092
37.263565
142
false
false
0
0
0
0
0
0
2.106061
false
false
2
3ae46ab4baee16a1187a2e59900b0aa1c4f4d694
20,710,332,322,895
29a1f3cd6348e6c14177d92ce3b32decc8242ae2
/com.nokia.tools.editing.ui/src/com/nokia/tools/editing/ui/part/EditingAdapter.java
0fb94bd9de92194f6561e9db5a4e2560c842e557
[]
no_license
Symbian9/carbideui
https://github.com/Symbian9/carbideui
36e550128a5b69518799932c096dab6e04cd49f7
a067bd24b5ff0bfc506d0569ebd3b87ef098c279
refs/heads/master
2021-01-11T06:04:29.203000
2015-06-20T08:56:44
2015-06-20T08:56:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ package com.nokia.tools.editing.ui.part; import org.eclipse.emf.common.notify.Notification; import org.eclipse.gef.EditPart; import org.eclipse.swt.widgets.Display; import com.nokia.tools.editing.core.TypedAdapter; import com.nokia.tools.editing.ui.Activator; public class EditingAdapter extends TypedAdapter { private EditPart part; public EditingAdapter(EditPart part) { this.part = part; } /* * (non-Javadoc) * * @see org.eclipse.emf.common.notify.Adapter#notifyChanged(org.eclipse.emf.common.notify.Notification) */ public void notifyChanged(Notification notification) { if (Notification.REMOVING_ADAPTER == notification.getEventType()) { return; } if (part != null) { if (Display.getCurrent() != null) { try { part.refresh(); } catch (Exception e) { Activator.error(e); } } else { // both visuals and children Display.getDefault().asyncExec(new Runnable() { public void run() { if (part != null) { try { part.refresh(); } catch (Exception e) { Activator.error(e); } } } }); } } } /** * @return the part */ public EditPart getPart() { return part; } }
UTF-8
Java
1,715
java
EditingAdapter.java
Java
[]
null
[]
/* * Copyright (c) 2006-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ package com.nokia.tools.editing.ui.part; import org.eclipse.emf.common.notify.Notification; import org.eclipse.gef.EditPart; import org.eclipse.swt.widgets.Display; import com.nokia.tools.editing.core.TypedAdapter; import com.nokia.tools.editing.ui.Activator; public class EditingAdapter extends TypedAdapter { private EditPart part; public EditingAdapter(EditPart part) { this.part = part; } /* * (non-Javadoc) * * @see org.eclipse.emf.common.notify.Adapter#notifyChanged(org.eclipse.emf.common.notify.Notification) */ public void notifyChanged(Notification notification) { if (Notification.REMOVING_ADAPTER == notification.getEventType()) { return; } if (part != null) { if (Display.getCurrent() != null) { try { part.refresh(); } catch (Exception e) { Activator.error(e); } } else { // both visuals and children Display.getDefault().asyncExec(new Runnable() { public void run() { if (part != null) { try { part.refresh(); } catch (Exception e) { Activator.error(e); } } } }); } } } /** * @return the part */ public EditPart getPart() { return part; } }
1,715
0.643149
0.636152
72
21.819445
22.048763
104
false
false
0
0
0
0
0
0
2.055556
false
false
2
01e6ca594429683f6f82a3e12b560a1455dd13f0
13,451,837,581,976
048fcebb3ef3920ec110006a43bade0618e690d7
/src/test/java/com/teste/AssertTest.java
56c4297666dfec88f880152b78121aa96d2e5147
[]
no_license
cfilipeandrade/teste-unitarios-java
https://github.com/cfilipeandrade/teste-unitarios-java
10a238aec93255fc819710e9ca840fdea32bc0ca
449358430f21af2e7d69e0cdc3e9837a5fecd2e5
refs/heads/main
2023-04-03T10:37:53.996000
2021-04-12T23:37:44
2021-04-12T23:37:44
357,368,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.teste; import org.junit.Test; import static org.junit.Assert.*; public class AssertTest { @Test public void testAssertArrayEquals() { byte[] esperado = "teste".getBytes(); byte[] atual = "teste".getBytes(); assertArrayEquals(esperado, atual); } @Test public void testAssertStringEquals() { assertEquals("text","text"); } @Test public void testAssertBoolean() { assertFalse(false); }; @Test public void testAssertObjectNotNull() { assertNotNull(new Object()) ; } @Test public void testAssertObjectIsNull() { assertNull(null); } @Test public void testAssertIsSame() { Integer aNumber = Integer.valueOf(763); assertSame(aNumber,aNumber); } }
UTF-8
Java
803
java
AssertTest.java
Java
[]
null
[]
package com.teste; import org.junit.Test; import static org.junit.Assert.*; public class AssertTest { @Test public void testAssertArrayEquals() { byte[] esperado = "teste".getBytes(); byte[] atual = "teste".getBytes(); assertArrayEquals(esperado, atual); } @Test public void testAssertStringEquals() { assertEquals("text","text"); } @Test public void testAssertBoolean() { assertFalse(false); }; @Test public void testAssertObjectNotNull() { assertNotNull(new Object()) ; } @Test public void testAssertObjectIsNull() { assertNull(null); } @Test public void testAssertIsSame() { Integer aNumber = Integer.valueOf(763); assertSame(aNumber,aNumber); } }
803
0.608966
0.60523
40
19.075001
16.956396
47
false
false
0
0
0
0
0
0
0.4
false
false
2
26335f46c5a0f911cd59fb8ce9cfefe77036b89e
18,442,589,582,827
4b8f5372a0ecf1b4e2b318acd2f3155e8f9a8e8d
/src/main/java/com/imp/wingedbeacons/WingedBeacons.java
3d0b6ee2977e71b938beeec8691f2aa3d24f374f
[]
no_license
itsimp/WingedBeacons
https://github.com/itsimp/WingedBeacons
b455d137ab16d28d1e10ef53b71f1a940c3add71
6ae1039b7de9aca83ce7ad329c89860a1de970f6
refs/heads/master
2023-06-11T09:39:40.540000
2021-07-06T15:18:30
2021-07-06T15:18:30
383,508,856
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.imp.wingedbeacons; import com.imp.wingedbeacons.effect.FlightEffect; import com.imp.wingedbeacons.event.AdvancementEventHandler; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.advancement.AdvancementProgress; import net.minecraft.network.PacketByteBuf; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; public class WingedBeacons implements ModInitializer { public static final String MODID = "wingedbeacons"; public static final FlightEffect FLIGHT_EFFECT = new FlightEffect(); public static final Identifier ADVANCEMENT_C2S_PACKET = new Identifier(MODID, "advancement_c2s_packet"); public static final Identifier ADVANCEMENT_S2C_PACKET = new Identifier(MODID, "advancement_s2c_packet"); @Override public void onInitialize() { /* Load Config */ WingedBeaconsConfig.loadConfig(); /* Register Status Effects */ Registry.register(Registry.STATUS_EFFECT, new Identifier(MODID, "flight"), FLIGHT_EFFECT); /* Networking */ ServerPlayNetworking.registerGlobalReceiver(ADVANCEMENT_C2S_PACKET, ((server, player, handler, buf, responseSender) -> { AdvancementProgress prog = player.getAdvancementTracker().getProgress(server.getAdvancementLoader().get(new Identifier(WingedBeaconsConfig.INSTANCE.advancementRequired))); PacketByteBuf buff = PacketByteBufs.create(); if (prog.isDone()) { buff.writeBoolean(true); } else { buff.writeBoolean(false); } ServerPlayNetworking.send(player, ADVANCEMENT_S2C_PACKET, buff); })); } }
UTF-8
Java
1,730
java
WingedBeacons.java
Java
[]
null
[]
package com.imp.wingedbeacons; import com.imp.wingedbeacons.effect.FlightEffect; import com.imp.wingedbeacons.event.AdvancementEventHandler; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.advancement.AdvancementProgress; import net.minecraft.network.PacketByteBuf; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; public class WingedBeacons implements ModInitializer { public static final String MODID = "wingedbeacons"; public static final FlightEffect FLIGHT_EFFECT = new FlightEffect(); public static final Identifier ADVANCEMENT_C2S_PACKET = new Identifier(MODID, "advancement_c2s_packet"); public static final Identifier ADVANCEMENT_S2C_PACKET = new Identifier(MODID, "advancement_s2c_packet"); @Override public void onInitialize() { /* Load Config */ WingedBeaconsConfig.loadConfig(); /* Register Status Effects */ Registry.register(Registry.STATUS_EFFECT, new Identifier(MODID, "flight"), FLIGHT_EFFECT); /* Networking */ ServerPlayNetworking.registerGlobalReceiver(ADVANCEMENT_C2S_PACKET, ((server, player, handler, buf, responseSender) -> { AdvancementProgress prog = player.getAdvancementTracker().getProgress(server.getAdvancementLoader().get(new Identifier(WingedBeaconsConfig.INSTANCE.advancementRequired))); PacketByteBuf buff = PacketByteBufs.create(); if (prog.isDone()) { buff.writeBoolean(true); } else { buff.writeBoolean(false); } ServerPlayNetworking.send(player, ADVANCEMENT_S2C_PACKET, buff); })); } }
1,730
0.790751
0.785549
43
39.232559
38.081207
174
false
false
0
0
0
0
0
0
1.906977
false
false
2
b16dea3009435d901073dd76af10b3bd5d6825e0
15,187,004,375,931
d3da48d64ec094d1e20b724ee0e58ff51b691530
/src/main/java/model/entretien/Entretien.java
378df2a087f83dd2ade34ba4688382ea5a608b79
[]
no_license
Bastien91580/dddEntretien
https://github.com/Bastien91580/dddEntretien
e08c139f6357234d20a05555aafb37613addc835
ccf3fdfde89c6db59a3d0d5cb662aba2c2476c5d
refs/heads/master
2020-05-15T12:52:27.745000
2019-04-19T14:58:46
2019-04-19T14:58:46
182,280,937
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model.entretien; import model.candidat.Candidat; import java.util.Date; public class Entretien { private EntretienID id; private enum Status {EN_ATTENTE, CONFIRME, ANNULE} private Status currentStatus; private String annulationReason; private Creneau creneau; private String recruteur; private Candidat candidat; public Entretien(String recruteur, Candidat candidat, Date startDate, int duree) { this.id = new EntretienID(); this.currentStatus = Status.EN_ATTENTE; this.creneau = new Creneau(startDate, duree); this.recruteur = recruteur; this.candidat = candidat; } public EntretienID getId() { return id; } public Status getCurrentStatus() { return currentStatus; } public String getAnnulationReason() { return annulationReason; } public String getStatus() { return currentStatus.toString(); } public Creneau getCreneau() { return creneau; } public String getRecruteur() { return recruteur; } public Candidat getCandidat() { return candidat; } public void confirmer() { this.currentStatus = Status.CONFIRME; } public void annuler(String reason) { this.currentStatus = Status.ANNULE; annulationReason = reason; } }
UTF-8
Java
1,367
java
Entretien.java
Java
[]
null
[]
package model.entretien; import model.candidat.Candidat; import java.util.Date; public class Entretien { private EntretienID id; private enum Status {EN_ATTENTE, CONFIRME, ANNULE} private Status currentStatus; private String annulationReason; private Creneau creneau; private String recruteur; private Candidat candidat; public Entretien(String recruteur, Candidat candidat, Date startDate, int duree) { this.id = new EntretienID(); this.currentStatus = Status.EN_ATTENTE; this.creneau = new Creneau(startDate, duree); this.recruteur = recruteur; this.candidat = candidat; } public EntretienID getId() { return id; } public Status getCurrentStatus() { return currentStatus; } public String getAnnulationReason() { return annulationReason; } public String getStatus() { return currentStatus.toString(); } public Creneau getCreneau() { return creneau; } public String getRecruteur() { return recruteur; } public Candidat getCandidat() { return candidat; } public void confirmer() { this.currentStatus = Status.CONFIRME; } public void annuler(String reason) { this.currentStatus = Status.ANNULE; annulationReason = reason; } }
1,367
0.647403
0.647403
62
21.048388
18.634365
86
false
false
0
0
0
0
0
0
0.483871
false
false
2
742753e0cd2897a863fe15e8c53bbae59a6f01f2
7,791,070,739,109
7b93d88966fa4d6e93274ab077d93ba85c26cc17
/src/main/java/com/yanda/entity/generated/AttachmentInfo.java
62879f28cba4ce80148a4fb96d17bd6e226b0c60
[]
no_license
luchuanTeam/yanda
https://github.com/luchuanTeam/yanda
f67f4fedc25a9482b5339f3f94bed9e06d529ca9
49bd592f4fc89bef32c4f6826049ecd1aac13c87
refs/heads/master
2021-05-01T13:07:00.958000
2018-07-26T14:16:02
2018-07-26T14:16:02
121,070,799
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yanda.entity.generated; import java.io.Serializable; import java.util.Date; import javax.persistence.*; @Table(name = "t_attachment_info") public class AttachmentInfo implements Serializable { /** * 附件ID */ @Id @Column(name = "appendix_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long appendixId; /** * 附件上传时的名字 */ @Column(name = "old_filename") private String oldFilename; /** * 新生成的附件名 */ @Column(name = "new_filename") private String newFilename; /** * 附件后缀 */ @Column(name = "file_ext") private String fileExt; /** * 附件文件夹路径 */ @Column(name = "file_path") private String filePath; /** * 附件类型 10.图片 20.视频 30.其他 */ @Column(name = "file_type") private Integer fileType; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 音视频附件的总时长 */ private Long duration; private static final long serialVersionUID = 1L; public AttachmentInfo(Long appendixId, String oldFilename, String newFilename, String fileExt, String filePath, Integer fileType, Date createTime, Long duration) { this.appendixId = appendixId; this.oldFilename = oldFilename; this.newFilename = newFilename; this.fileExt = fileExt; this.filePath = filePath; this.fileType = fileType; this.createTime = createTime; this.duration = duration; } public AttachmentInfo() { super(); } /** * 获取附件ID * * @return appendix_id - 附件ID */ public Long getAppendixId() { return appendixId; } /** * 设置附件ID * * @param appendixId 附件ID */ public void setAppendixId(Long appendixId) { this.appendixId = appendixId; } /** * 获取附件上传时的名字 * * @return old_filename - 附件上传时的名字 */ public String getOldFilename() { return oldFilename; } /** * 设置附件上传时的名字 * * @param oldFilename 附件上传时的名字 */ public void setOldFilename(String oldFilename) { this.oldFilename = oldFilename == null ? null : oldFilename.trim(); } /** * 获取新生成的附件名 * * @return new_filename - 新生成的附件名 */ public String getNewFilename() { return newFilename; } /** * 设置新生成的附件名 * * @param newFilename 新生成的附件名 */ public void setNewFilename(String newFilename) { this.newFilename = newFilename == null ? null : newFilename.trim(); } /** * 获取附件后缀 * * @return file_ext - 附件后缀 */ public String getFileExt() { return fileExt; } /** * 设置附件后缀 * * @param fileExt 附件后缀 */ public void setFileExt(String fileExt) { this.fileExt = fileExt == null ? null : fileExt.trim(); } /** * 获取附件文件夹路径 * * @return file_path - 附件文件夹路径 */ public String getFilePath() { return filePath; } /** * 设置附件文件夹路径 * * @param filePath 附件文件夹路径 */ public void setFilePath(String filePath) { this.filePath = filePath == null ? null : filePath.trim(); } /** * 获取附件类型 10.图片 20.视频 30.其他 * * @return file_type - 附件类型 10.图片 20.视频 30.其他 */ public Integer getFileType() { return fileType; } /** * 设置附件类型 10.图片 20.视频 30.其他 * * @param fileType 附件类型 10.图片 20.视频 30.其他 */ public void setFileType(Integer fileType) { this.fileType = fileType; } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取音视频附件的总时长 * * @return duration - 音视频附件的总时长 */ public Long getDuration() { return duration; } /** * 设置音视频附件的总时长 * * @param duration 音视频附件的总时长 */ public void setDuration(Long duration) { this.duration = duration; } public enum Col { appendixId("appendix_id"), oldFilename("old_filename"), newFilename("new_filename"), fileExt("file_ext"), filePath("file_path"), fileType("file_type"), createTime("create_time"), duration("duration"); private final String column; public String value() { return this.column; } public String getValue() { return this.column; } Col(String column) { this.column = column; } public String desc() { return this.column + " DESC"; } public String asc() { return this.column + " ASC"; } } }
UTF-8
Java
5,511
java
AttachmentInfo.java
Java
[]
null
[]
package com.yanda.entity.generated; import java.io.Serializable; import java.util.Date; import javax.persistence.*; @Table(name = "t_attachment_info") public class AttachmentInfo implements Serializable { /** * 附件ID */ @Id @Column(name = "appendix_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long appendixId; /** * 附件上传时的名字 */ @Column(name = "old_filename") private String oldFilename; /** * 新生成的附件名 */ @Column(name = "new_filename") private String newFilename; /** * 附件后缀 */ @Column(name = "file_ext") private String fileExt; /** * 附件文件夹路径 */ @Column(name = "file_path") private String filePath; /** * 附件类型 10.图片 20.视频 30.其他 */ @Column(name = "file_type") private Integer fileType; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 音视频附件的总时长 */ private Long duration; private static final long serialVersionUID = 1L; public AttachmentInfo(Long appendixId, String oldFilename, String newFilename, String fileExt, String filePath, Integer fileType, Date createTime, Long duration) { this.appendixId = appendixId; this.oldFilename = oldFilename; this.newFilename = newFilename; this.fileExt = fileExt; this.filePath = filePath; this.fileType = fileType; this.createTime = createTime; this.duration = duration; } public AttachmentInfo() { super(); } /** * 获取附件ID * * @return appendix_id - 附件ID */ public Long getAppendixId() { return appendixId; } /** * 设置附件ID * * @param appendixId 附件ID */ public void setAppendixId(Long appendixId) { this.appendixId = appendixId; } /** * 获取附件上传时的名字 * * @return old_filename - 附件上传时的名字 */ public String getOldFilename() { return oldFilename; } /** * 设置附件上传时的名字 * * @param oldFilename 附件上传时的名字 */ public void setOldFilename(String oldFilename) { this.oldFilename = oldFilename == null ? null : oldFilename.trim(); } /** * 获取新生成的附件名 * * @return new_filename - 新生成的附件名 */ public String getNewFilename() { return newFilename; } /** * 设置新生成的附件名 * * @param newFilename 新生成的附件名 */ public void setNewFilename(String newFilename) { this.newFilename = newFilename == null ? null : newFilename.trim(); } /** * 获取附件后缀 * * @return file_ext - 附件后缀 */ public String getFileExt() { return fileExt; } /** * 设置附件后缀 * * @param fileExt 附件后缀 */ public void setFileExt(String fileExt) { this.fileExt = fileExt == null ? null : fileExt.trim(); } /** * 获取附件文件夹路径 * * @return file_path - 附件文件夹路径 */ public String getFilePath() { return filePath; } /** * 设置附件文件夹路径 * * @param filePath 附件文件夹路径 */ public void setFilePath(String filePath) { this.filePath = filePath == null ? null : filePath.trim(); } /** * 获取附件类型 10.图片 20.视频 30.其他 * * @return file_type - 附件类型 10.图片 20.视频 30.其他 */ public Integer getFileType() { return fileType; } /** * 设置附件类型 10.图片 20.视频 30.其他 * * @param fileType 附件类型 10.图片 20.视频 30.其他 */ public void setFileType(Integer fileType) { this.fileType = fileType; } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取音视频附件的总时长 * * @return duration - 音视频附件的总时长 */ public Long getDuration() { return duration; } /** * 设置音视频附件的总时长 * * @param duration 音视频附件的总时长 */ public void setDuration(Long duration) { this.duration = duration; } public enum Col { appendixId("appendix_id"), oldFilename("old_filename"), newFilename("new_filename"), fileExt("file_ext"), filePath("file_path"), fileType("file_type"), createTime("create_time"), duration("duration"); private final String column; public String value() { return this.column; } public String getValue() { return this.column; } Col(String column) { this.column = column; } public String desc() { return this.column + " DESC"; } public String asc() { return this.column + " ASC"; } } }
5,511
0.54203
0.53575
251
18.673307
18.546507
167
false
false
0
0
0
0
0
0
0.23506
false
false
2
e09f09f7b127fea0e0fb17b89e750e692fca3752
29,695,403,905,028
7eb4bbed6600d29a98bb7088df78bbcaca29aaf4
/mg-common/src/main/java/com/mg/api/common/constant/SystemSettings.java
ed787cc5228838d9219698df5c09f400aa65db1b
[]
no_license
ichunming/mg-api
https://github.com/ichunming/mg-api
d2b056d4ceac54a8dd7219607dc1aa1c2e1cf472
43ee7c1fb378661b9e3783b380150895724d0d7f
refs/heads/master
2020-06-18T18:06:44.747000
2017-02-27T02:11:41
2017-02-27T02:11:41
74,749,670
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mg.api.common.constant; import java.io.File; public class SystemSettings { // 开发模式 public static boolean DEBUG_MODE = true; // 临时目录 public static final String TEMP_DIR = "temp" + File.separator; // 默认头像 public static final String DEFAULT_PORTRAIT = ""; // 手机注册支持 public static boolean MOBIL_REG_SUPPORT = true; // 邮箱注册支持 public static boolean EMAIL_REG_SUPPORT = true; }
UTF-8
Java
451
java
SystemSettings.java
Java
[]
null
[]
package com.mg.api.common.constant; import java.io.File; public class SystemSettings { // 开发模式 public static boolean DEBUG_MODE = true; // 临时目录 public static final String TEMP_DIR = "temp" + File.separator; // 默认头像 public static final String DEFAULT_PORTRAIT = ""; // 手机注册支持 public static boolean MOBIL_REG_SUPPORT = true; // 邮箱注册支持 public static boolean EMAIL_REG_SUPPORT = true; }
451
0.712159
0.712159
20
19.15
20.355036
63
false
false
0
0
0
0
0
0
1.05
false
false
2
da78c88fa813876bab3d101a609181e92d7b7131
29,695,403,904,909
82ea4519e49973757a8f117b2147fbdd24ce56ef
/src/mvc/model/appliances/Washer.java
f30570f0dd8bd11427edb0c75f22b666c3f5951c
[]
no_license
jooomer/tasks.1-18.JavaST.OOP_ElectricalAppliances
https://github.com/jooomer/tasks.1-18.JavaST.OOP_ElectricalAppliances
c0fdb2e8ccd3be67ffaa11b6b4f8678a50b5e86b
e67c8dc4e48a0d39f700491deb8b7ce912eb3c5f
refs/heads/master
2021-01-22T02:39:51.809000
2014-10-25T18:43:11
2014-10-25T18:43:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package mvc.model.appliances; /** * @author Sergey * */ public class Washer extends Appliance { private int modesNumber; // field is not used for this task }
UTF-8
Java
180
java
Washer.java
Java
[ { "context": "\n */\npackage mvc.model.appliances;\n\n/**\n * @author Sergey\n *\n */\npublic class Washer extends Appliance {\n\tp", "end": 64, "score": 0.999603271484375, "start": 58, "tag": "NAME", "value": "Sergey" } ]
null
[]
/** * */ package mvc.model.appliances; /** * @author Sergey * */ public class Washer extends Appliance { private int modesNumber; // field is not used for this task }
180
0.644444
0.644444
12
14
19.523491
65
false
false
0
0
0
0
0
0
0.75
false
false
2
884c98164f97c1a87330ad1a1d2484fefcecf766
29,506,425,330,063
66bceb8e86ec495cb4c1d7c6eb4e2da7935fb658
/apps/onework-tools/onework-tools-webapi/src/main/java/com/onework/tools/generator/controller/DatabaseDbController.java
a535e149a7219c378b7e54149f26c268869c1c50
[]
no_license
zhongkai1010/OneWork
https://github.com/zhongkai1010/OneWork
cfac8202b5420b1d2172fc39713edb65b356d9a0
f02e399ce94a10f92c55a799f25d0b02b7fbae8f
refs/heads/master
2022-01-11T20:07:53.946000
2021-12-31T09:24:11
2021-12-31T09:24:23
35,706,407
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.onework.tools.generator.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.onework.tools.common.web.AbstractCrudController; import com.onework.tools.generator.entity.DatabaseDb; /** * <p> * 前端控制器 * </p> * * @author 钟凯 * @since 2021-12-18 */ @RestController @RequestMapping("/databaseDb") public class DatabaseDbController extends AbstractCrudController<DatabaseDb> { }
UTF-8
Java
504
java
DatabaseDbController.java
Java
[ { "context": "aseDb;\n\n/**\n * <p>\n * 前端控制器\n * </p>\n *\n * @author 钟凯\n * @since 2021-12-18\n */\n@RestController\n@Request", "end": 335, "score": 0.9006415009498596, "start": 333, "tag": "NAME", "value": "钟凯" } ]
null
[]
package com.onework.tools.generator.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.onework.tools.common.web.AbstractCrudController; import com.onework.tools.generator.entity.DatabaseDb; /** * <p> * 前端控制器 * </p> * * @author 钟凯 * @since 2021-12-18 */ @RestController @RequestMapping("/databaseDb") public class DatabaseDbController extends AbstractCrudController<DatabaseDb> { }
504
0.785714
0.769388
21
22.333334
25.506924
78
false
false
0
0
0
0
0
0
0.238095
false
false
2
1582a16ac7a0f488602c266b724209ee8b484b30
19,954,418,075,975
bc8e9cd6b3968841f0b234a569d569a47fa9612e
/src/main/java/com/wang/so/love/control/web/controller/SoLoveAreaController.java
aa332015c8d44b57f570e2d4785237bb93d7cab6
[]
no_license
hejiawang/soLove-control-web
https://github.com/hejiawang/soLove-control-web
6002f53a623a8a67b7721c7d82f702b33534792d
de6293965371507e78a90c1ca3f9bdb44c915933
refs/heads/master
2020-06-13T04:27:18.634000
2017-01-12T02:44:15
2017-01-12T02:44:15
75,448,326
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wang.so.love.control.web.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.wang.core.ServiceResult; import com.wang.so.love.service.entity.SoLoveAreaEntity; import com.wang.so.love.service.param.SoLoveAreaParam; import com.wang.so.love.service.service.SoLoveAreaService; /** * 地区controller * * @author HeJiawang * @date 2016.12.08 */ @Controller @RequestMapping(value = "/area") public class SoLoveAreaController extends BaseController { /** * logger */ private static final Logger logger = LoggerFactory.getLogger(SoLoveAreaController.class); /** * soLoveAreaService */ @Autowired private SoLoveAreaService soLoveAreaService; /** * 根据父级地址获取子地址集合 * * @param parentID 地址父ID * @return 地址信息集合 */ @RequestMapping(value = "/list", method = {RequestMethod.GET}) @ResponseBody public ServiceResult<List<SoLoveAreaEntity>> getAreaListByParentID( HttpServletRequest request, Integer parentID ){ ServiceResult<List<SoLoveAreaEntity>> result = new ServiceResult<List<SoLoveAreaEntity>>(); try{ if( parentID == null ) parentID = 1001; result = soLoveAreaService.getAreaListByParentID(parentID); }catch( Exception e ){ logger.error("异常发生在"+this.getClass().getName()+"类的getAreaListByParentID方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 分页获取地区信息 * * @param param 查询信息 * @param start 分页信息 * @param length 分页信息 * @param draw 分页信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/page",method=RequestMethod.GET) @ResponseBody public Map<String,Object> pageArea( SoLoveAreaParam param, Integer start,Integer length, Integer draw ){ Map<String,Object> result =null; try { result = soLoveAreaService.pageAera(param, start, length, draw).getResult(); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的pageArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 删除地区 * @param areaID 地区ID * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/erase",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> earseArea( Integer areaID ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.deleteArea(areaID); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的earseArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 新增地区 * * @param area 地区信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/raise",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> raiseArea( SoLoveAreaParam area ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.raiseArea(area); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的raiseArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 修改地区 * * @param area 地区信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/modify",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> modifyArea( SoLoveAreaParam area ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.modifyArea(area); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的modifyArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 获取地区树 * * @param id 父地区ID * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/trees",method = RequestMethod.POST,produces="text/plain;charset=UTF-8") public @ResponseBody String getAreaTreeData(Integer id){ StringBuffer sb = new StringBuffer(); try { if(id == null){ id=1000; } List<SoLoveAreaParam> list = soLoveAreaService.getAreaTreeData(id).getResult();//areaData SoLoveAreaParam area ; sb.append("["); for (int i = 0; i < list.size(); i++) { area = list.get(i); if(i==(list.size()-1)){ if(area.getIsParent()>0){ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\",isParent:true}"); }else{ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\"}"); } }else{ if(area.getIsParent()>0){ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\",isParent:true},"); }else{ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\"},"); } } } sb.append("]"); logger.debug("area树JSON====="+sb.toString()); } catch (Exception e) { logger.info("异常发生在"+this.getClass().getName()+"类的getAreaTreeData方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return sb.toString(); } }
UTF-8
Java
5,924
java
SoLoveAreaController.java
Java
[ { "context": "aService;\r\n\r\n/**\r\n * 地区controller\r\n * \r\n * @author HeJiawang\r\n * @date 2016.12.08\r\n */\r\n@Controller\r\n@Reques", "end": 775, "score": 0.9985199570655823, "start": 766, "tag": "NAME", "value": "HeJiawang" }, { "context": "* @param draw 分页信息\r\n\t * @ret...
null
[]
package com.wang.so.love.control.web.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.wang.core.ServiceResult; import com.wang.so.love.service.entity.SoLoveAreaEntity; import com.wang.so.love.service.param.SoLoveAreaParam; import com.wang.so.love.service.service.SoLoveAreaService; /** * 地区controller * * @author HeJiawang * @date 2016.12.08 */ @Controller @RequestMapping(value = "/area") public class SoLoveAreaController extends BaseController { /** * logger */ private static final Logger logger = LoggerFactory.getLogger(SoLoveAreaController.class); /** * soLoveAreaService */ @Autowired private SoLoveAreaService soLoveAreaService; /** * 根据父级地址获取子地址集合 * * @param parentID 地址父ID * @return 地址信息集合 */ @RequestMapping(value = "/list", method = {RequestMethod.GET}) @ResponseBody public ServiceResult<List<SoLoveAreaEntity>> getAreaListByParentID( HttpServletRequest request, Integer parentID ){ ServiceResult<List<SoLoveAreaEntity>> result = new ServiceResult<List<SoLoveAreaEntity>>(); try{ if( parentID == null ) parentID = 1001; result = soLoveAreaService.getAreaListByParentID(parentID); }catch( Exception e ){ logger.error("异常发生在"+this.getClass().getName()+"类的getAreaListByParentID方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 分页获取地区信息 * * @param param 查询信息 * @param start 分页信息 * @param length 分页信息 * @param draw 分页信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/page",method=RequestMethod.GET) @ResponseBody public Map<String,Object> pageArea( SoLoveAreaParam param, Integer start,Integer length, Integer draw ){ Map<String,Object> result =null; try { result = soLoveAreaService.pageAera(param, start, length, draw).getResult(); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的pageArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 删除地区 * @param areaID 地区ID * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/erase",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> earseArea( Integer areaID ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.deleteArea(areaID); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的earseArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 新增地区 * * @param area 地区信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/raise",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> raiseArea( SoLoveAreaParam area ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.raiseArea(area); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的raiseArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 修改地区 * * @param area 地区信息 * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/modify",method=RequestMethod.POST) @ResponseBody public ServiceResult<Void> modifyArea( SoLoveAreaParam area ){ ServiceResult<Void> result = new ServiceResult<Void>(); try { result = soLoveAreaService.modifyArea(area); } catch (Exception e) { logger.error("异常发生在"+this.getClass().getName()+"类的modifyArea方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return result; } /** * 获取地区树 * * @param id 父地区ID * @return * * @author HeJiawang * @date 2016.12.29 */ @RequestMapping(value="/trees",method = RequestMethod.POST,produces="text/plain;charset=UTF-8") public @ResponseBody String getAreaTreeData(Integer id){ StringBuffer sb = new StringBuffer(); try { if(id == null){ id=1000; } List<SoLoveAreaParam> list = soLoveAreaService.getAreaTreeData(id).getResult();//areaData SoLoveAreaParam area ; sb.append("["); for (int i = 0; i < list.size(); i++) { area = list.get(i); if(i==(list.size()-1)){ if(area.getIsParent()>0){ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\",isParent:true}"); }else{ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\"}"); } }else{ if(area.getIsParent()>0){ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\",isParent:true},"); }else{ sb.append("{id:"+area.getAreaID()+",name:\""+area.getShortName()+"\",garade:\""+area.getAreaLevel()+"\"},"); } } } sb.append("]"); logger.debug("area树JSON====="+sb.toString()); } catch (Exception e) { logger.info("异常发生在"+this.getClass().getName()+"类的getAreaTreeData方法,异常原因是:"+e.getMessage(), e.fillInStackTrace()); } return sb.toString(); } }
5,924
0.660746
0.649444
189
27.492064
31.347788
129
false
false
0
0
0
0
0
0
2.021164
false
false
2
668f761924fdae9e167b6b82d2c0ec101fd41876
19,954,418,077,511
3615d53dad1953707a777019d82a601a1378f35f
/src/main/java/cn/baizhi/util/OssUtil.java
c832cc5d55310fd49e6771e05a639860e134ec67
[]
no_license
a373581025/yingxue_heguangyu
https://github.com/a373581025/yingxue_heguangyu
027b392ffbc09d756513ea9c9fac7df92767309f
4e2ff4cfdc30d4e767066a4a481a7d7e93032886
refs/heads/master
2023-07-15T10:54:45.641000
2021-08-30T01:01:12
2021-08-30T01:01:12
401,072,374
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.baizhi.util; import cn.baizhi.config.AliYunConfig; import com.aliyun.oss.HttpMethod; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GeneratePresignedUrlRequest; import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.PutObjectRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; public class OssUtil { private static final Logger log = LoggerFactory.getLogger(OssUtil.class); //上传(字节数组上传) public static void uploadByBytes(MultipartFile file, String fileName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 创建PutObjectRequest对象。 // 依次填写Bucket名称(例如examplebucket)、Object完整路径(例如exampledir/exampleobject.txt)和本地文件的完整路径。Object完整路径中不能包含Bucket名称。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。 PutObjectRequest putObjectRequest = null; try { putObjectRequest = new PutObjectRequest("2021updown", fileName, new ByteArrayInputStream(file.getBytes())); } catch (IOException e) { e.printStackTrace(); } // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传文件。 ossClient.putObject(putObjectRequest); // 关闭OSSClient。 ossClient.shutdown(); } //删除上传文件 public static void removeById(String objectName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; String bucketName = AliYunConfig.BUCKETNAME; //存储空间名 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。 ossClient.deleteObject(bucketName, objectName); // 关闭OSSClient。 log.debug("1"); ossClient.shutdown(); } //视频截帧 public static void video(String fileName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; //存储空间名 // 填写视频文件的完整路径。若视频文件不在Bucket根目录,需携带文件访问路径,例如examplefolder/videotest.mp4。 String objectName = fileName; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 创建PutObjectRequest对象。 // 依次填写Bucket名称(例如examplebucket)、Object完整路径(例如exampledir/exampleobject.txt)和本地文件的完整路径。Object完整路径中不能包含Bucket名称。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。 // 使用精确时间模式截取视频50s处的内容,输出为JPG格式的图片,宽度为800,高度为600。 String style = "video/snapshot,t_2000,f_jpg,w_800,h_600"; // 指定过期时间为10分钟。 Date expiration = new Date(new Date().getTime() + (1000 * 60 * 10)); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest("2021updown", objectName, HttpMethod.GET); req.setExpiration(expiration); req.setProcess(style); URL signedUrl = ossClient.generatePresignedUrl(req); InputStream inputStream = null; try { // 填写网络流地址。 inputStream = new URL(signedUrl.toString()).openStream(); } catch (Exception e) { e.printStackTrace(); } String[] split = fileName.split("\\."); // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。 ossClient.putObject("2021updown", split[0] + ".jpg", inputStream); // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 关闭OSSClient。 log.debug("2"); ossClient.shutdown(); } //文件下载 public static void download(String fileName){ // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; String bucketName = AliYunConfig.BUCKETNAME; //存储空间名 String objectName = fileName; //文件名 String localFile="D:\\abc\\"+objectName; //下载本地地址 地址加保存名字 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFile)); // 关闭OSSClient。 ossClient.shutdown(); } }
UTF-8
Java
7,809
java
OssUtil.java
Java
[ { "context": "nfig.ACCESSKEYID;\n String accessKeySecret = AliYunConfig.ACCESSKEYSECRET;\n String bucketNa", "end": 5617, "score": 0.8374806046485901, "start": 5614, "tag": "KEY", "value": "Ali" } ]
null
[]
package cn.baizhi.util; import cn.baizhi.config.AliYunConfig; import com.aliyun.oss.HttpMethod; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GeneratePresignedUrlRequest; import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.PutObjectRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; public class OssUtil { private static final Logger log = LoggerFactory.getLogger(OssUtil.class); //上传(字节数组上传) public static void uploadByBytes(MultipartFile file, String fileName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 创建PutObjectRequest对象。 // 依次填写Bucket名称(例如examplebucket)、Object完整路径(例如exampledir/exampleobject.txt)和本地文件的完整路径。Object完整路径中不能包含Bucket名称。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。 PutObjectRequest putObjectRequest = null; try { putObjectRequest = new PutObjectRequest("2021updown", fileName, new ByteArrayInputStream(file.getBytes())); } catch (IOException e) { e.printStackTrace(); } // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传文件。 ossClient.putObject(putObjectRequest); // 关闭OSSClient。 ossClient.shutdown(); } //删除上传文件 public static void removeById(String objectName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; String bucketName = AliYunConfig.BUCKETNAME; //存储空间名 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。 ossClient.deleteObject(bucketName, objectName); // 关闭OSSClient。 log.debug("1"); ossClient.shutdown(); } //视频截帧 public static void video(String fileName) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; //存储空间名 // 填写视频文件的完整路径。若视频文件不在Bucket根目录,需携带文件访问路径,例如examplefolder/videotest.mp4。 String objectName = fileName; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 创建PutObjectRequest对象。 // 依次填写Bucket名称(例如examplebucket)、Object完整路径(例如exampledir/exampleobject.txt)和本地文件的完整路径。Object完整路径中不能包含Bucket名称。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。 // 使用精确时间模式截取视频50s处的内容,输出为JPG格式的图片,宽度为800,高度为600。 String style = "video/snapshot,t_2000,f_jpg,w_800,h_600"; // 指定过期时间为10分钟。 Date expiration = new Date(new Date().getTime() + (1000 * 60 * 10)); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest("2021updown", objectName, HttpMethod.GET); req.setExpiration(expiration); req.setProcess(style); URL signedUrl = ossClient.generatePresignedUrl(req); InputStream inputStream = null; try { // 填写网络流地址。 inputStream = new URL(signedUrl.toString()).openStream(); } catch (Exception e) { e.printStackTrace(); } String[] split = fileName.split("\\."); // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。 ossClient.putObject("2021updown", split[0] + ".jpg", inputStream); // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 关闭OSSClient。 log.debug("2"); ossClient.shutdown(); } //文件下载 public static void download(String fileName){ // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 String endpoint = AliYunConfig.ENDPOINT; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = AliYunConfig.ACCESSKEYID; String accessKeySecret = AliYunConfig.ACCESSKEYSECRET; String bucketName = AliYunConfig.BUCKETNAME; //存储空间名 String objectName = fileName; //文件名 String localFile="D:\\abc\\"+objectName; //下载本地地址 地址加保存名字 // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。 ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFile)); // 关闭OSSClient。 ossClient.shutdown(); } }
7,809
0.703854
0.695723
153
39.189541
32.684418
119
false
false
0
0
0
0
0
0
0.614379
false
false
2
48ac0c09f683dd0316ba43444664b53a3884f970
16,131,897,228,961
decc8bc04a765940b5e781ebbcad62d10a9d0a73
/PROGRAMACION_DAM_1/UD3_ESTRUCTURAS_PROGRAMACION/Ejercicios/Ejerc11_Columnas.java
228a48eda3fc03b274595920e410904066caeb17
[]
no_license
tonibruna/Programacion_DAM1
https://github.com/tonibruna/Programacion_DAM1
2e9b6e37e140c26516f3249538b4c85b174f2eb8
c1226061e724154dfb13227a65c14d4930aa6d2c
refs/heads/master
2020-04-08T08:55:56.847000
2018-11-26T16:35:24
2018-11-26T16:35:24
159,200,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Ejercicios; import java.util.Scanner; public class Ejerc11_Columnas {/*Escribe un programa que muestre en tres columnas, el cuadrado y el cubo de los 5 primeros números enteros a partir de uno que se introduce por teclado.*/ public static void main(String[] args) { Scanner teclado= new Scanner(System.in); System.out.println("Introduce un numero:"); int numeroIntroducido; numeroIntroducido=teclado.nextInt(); for (int i=numeroIntroducido; i<numeroIntroducido+5; i++) { System.out.printf("%4d %6d %8d\n", i, i * i, i * i * i); } } }
ISO-8859-1
Java
611
java
Ejerc11_Columnas.java
Java
[]
null
[]
package Ejercicios; import java.util.Scanner; public class Ejerc11_Columnas {/*Escribe un programa que muestre en tres columnas, el cuadrado y el cubo de los 5 primeros números enteros a partir de uno que se introduce por teclado.*/ public static void main(String[] args) { Scanner teclado= new Scanner(System.in); System.out.println("Introduce un numero:"); int numeroIntroducido; numeroIntroducido=teclado.nextInt(); for (int i=numeroIntroducido; i<numeroIntroducido+5; i++) { System.out.printf("%4d %6d %8d\n", i, i * i, i * i * i); } } }
611
0.662295
0.65082
23
24.52174
32.170563
139
false
false
0
0
0
0
0
0
2.086957
false
false
2
6903d2ea4f6ef773d356c8639af5ec9983ab8988
8,684,423,935,861
81effe1dde07ef14131c0ff32c438b8e925c0916
/src/ApolloRescue/ApolloLoader.java
a25174998ec861e6b16c82cba1cbb3062d7f653a
[ "BSD-3-Clause" ]
permissive
elliotleee/Apollo-lab
https://github.com/elliotleee/Apollo-lab
14723603ea382056011ca6907e1f57fd3f9774e8
a5b020128b368dda75daa6fbd4e16c002c59893b
refs/heads/master
2020-04-25T06:36:27.556000
2019-02-25T21:22:36
2019-02-25T21:22:36
172,586,663
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package ApolloRescue; import ApolloRescue.tactics.SampleTacticsAmbulanceCentre; import ApolloRescue.tactics.SampleTacticsAmbulanceTeam; import ApolloRescue.tactics.SampleTacticsFireBrigade; import ApolloRescue.tactics.SampleTacticsFireStation; import ApolloRescue.tactics.SampleTacticsPoliceForce; import ApolloRescue.tactics.SampleTacticsPoliceOffice; import adf.component.AbstractLoader; import adf.component.tactics.TacticsAmbulanceTeam; import adf.component.tactics.TacticsFireBrigade; import adf.component.tactics.TacticsPoliceForce; import adf.component.tactics.TacticsAmbulanceCentre; import adf.component.tactics.TacticsFireStation; import adf.component.tactics.TacticsPoliceOffice; /** * 实验2 */ public class ApolloLoader extends AbstractLoader { @Override public String getTeamName() { return "ApolloRescue"; } @Override public TacticsAmbulanceTeam getTacticsAmbulanceTeam() { return new SampleTacticsAmbulanceTeam(); } @Override public TacticsFireBrigade getTacticsFireBrigade() { return new SampleTacticsFireBrigade(); } @Override public TacticsPoliceForce getTacticsPoliceForce() { return new SampleTacticsPoliceForce(); } @Override public TacticsAmbulanceCentre getTacticsAmbulanceCentre() { return new SampleTacticsAmbulanceCentre(); } @Override public TacticsFireStation getTacticsFireStation() { return new SampleTacticsFireStation(); } @Override public TacticsPoliceOffice getTacticsPoliceOffice() { return new SampleTacticsPoliceOffice(); } }
UTF-8
Java
1,615
java
ApolloLoader.java
Java
[]
null
[]
package ApolloRescue; import ApolloRescue.tactics.SampleTacticsAmbulanceCentre; import ApolloRescue.tactics.SampleTacticsAmbulanceTeam; import ApolloRescue.tactics.SampleTacticsFireBrigade; import ApolloRescue.tactics.SampleTacticsFireStation; import ApolloRescue.tactics.SampleTacticsPoliceForce; import ApolloRescue.tactics.SampleTacticsPoliceOffice; import adf.component.AbstractLoader; import adf.component.tactics.TacticsAmbulanceTeam; import adf.component.tactics.TacticsFireBrigade; import adf.component.tactics.TacticsPoliceForce; import adf.component.tactics.TacticsAmbulanceCentre; import adf.component.tactics.TacticsFireStation; import adf.component.tactics.TacticsPoliceOffice; /** * 实验2 */ public class ApolloLoader extends AbstractLoader { @Override public String getTeamName() { return "ApolloRescue"; } @Override public TacticsAmbulanceTeam getTacticsAmbulanceTeam() { return new SampleTacticsAmbulanceTeam(); } @Override public TacticsFireBrigade getTacticsFireBrigade() { return new SampleTacticsFireBrigade(); } @Override public TacticsPoliceForce getTacticsPoliceForce() { return new SampleTacticsPoliceForce(); } @Override public TacticsAmbulanceCentre getTacticsAmbulanceCentre() { return new SampleTacticsAmbulanceCentre(); } @Override public TacticsFireStation getTacticsFireStation() { return new SampleTacticsFireStation(); } @Override public TacticsPoliceOffice getTacticsPoliceOffice() { return new SampleTacticsPoliceOffice(); } }
1,615
0.775916
0.775295
55
28.290909
22.917776
63
false
false
0
0
0
0
0
0
0.381818
false
false
2
ace68955a18d3f4977aacbdb9049c504390edaad
8,684,423,937,085
d277581f275c1485546bfeb3c3bbf3132e7a8226
/annotationsdemo/src/main/java/com/azadibogolubov/annotationsdemo/repository/BasicModelRepository.java
93ae7b4272fa49f10593eeae8c46e189d19bea21
[]
no_license
azadibogolubov/video_tutorials
https://github.com/azadibogolubov/video_tutorials
ec5c272f8f8f927bc99f34110bdb035b53fa06a2
240928ae68b9c93ed73fb8a2effa881d84a917a5
refs/heads/master
2020-03-18T00:41:43.064000
2018-05-20T00:32:28
2018-05-20T23:32:45
134,107,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.azadibogolubov.annotationsdemo.repository; import com.azadibogolubov.annotationsdemo.model.BasicModel; import org.springframework.stereotype.Repository; import org.springframework.data.mongodb.repository.MongoRepository; @Repository public interface BasicModelRepository extends MongoRepository<BasicModel, String> { BasicModel findByModelId(String id); }
UTF-8
Java
374
java
BasicModelRepository.java
Java
[]
null
[]
package com.azadibogolubov.annotationsdemo.repository; import com.azadibogolubov.annotationsdemo.model.BasicModel; import org.springframework.stereotype.Repository; import org.springframework.data.mongodb.repository.MongoRepository; @Repository public interface BasicModelRepository extends MongoRepository<BasicModel, String> { BasicModel findByModelId(String id); }
374
0.855615
0.855615
10
36.400002
29.408163
83
false
false
0
0
0
0
0
0
0.6
false
false
2
edf6bfea6ae52d27a318e6b88c005e111be81762
17,386,027,665,587
aee5bbd73b2d0aec072bbf32405b7f073ef8bf14
/app/src/main/java/digitalgarden/mecsek/diary/DailyAdapter.java
3ed0fff987ff8bd161c746c7113938b297701bc2
[]
no_license
Palmodroid/Mecsek2
https://github.com/Palmodroid/Mecsek2
ddc7318557a62b4ca437e812bf49f9de021a84c4
47e9ed79a095595336c8c76f2b9eb2d8b8fc647d
refs/heads/master
2020-08-30T23:40:01.368000
2020-04-29T06:35:07
2020-04-29T06:35:07
218,523,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package digitalgarden.mecsek.diary; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import digitalgarden.mecsek.scribe.Scribe; public class DailyAdapter extends FragmentStatePagerAdapter { private static int NUM_DAYS = 167880; public DailyAdapter(FragmentManager fragmentManager ) { super(fragmentManager); } // Returns total number of pages @Override public int getCount() { return NUM_DAYS; } // Returns the fragment to display for that page @Override public Fragment getItem(int position) { // position == daysSinceEpoch return DailyListFragment.newInstance( position ); //null; } // Returns the page title for the top indicator @Override public CharSequence getPageTitle(int position) { return ">" + position + "<"; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { super.destroyItem(container, position, object); /* for ( Fragment f : fm.getFragments()) { Scribe.debug("Fragment: " + f.getTag()); } Scribe.debug("Item destroyed: " + position); */ } }
UTF-8
Java
1,449
java
DailyAdapter.java
Java
[]
null
[]
package digitalgarden.mecsek.diary; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import digitalgarden.mecsek.scribe.Scribe; public class DailyAdapter extends FragmentStatePagerAdapter { private static int NUM_DAYS = 167880; public DailyAdapter(FragmentManager fragmentManager ) { super(fragmentManager); } // Returns total number of pages @Override public int getCount() { return NUM_DAYS; } // Returns the fragment to display for that page @Override public Fragment getItem(int position) { // position == daysSinceEpoch return DailyListFragment.newInstance( position ); //null; } // Returns the page title for the top indicator @Override public CharSequence getPageTitle(int position) { return ">" + position + "<"; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { super.destroyItem(container, position, object); /* for ( Fragment f : fm.getFragments()) { Scribe.debug("Fragment: " + f.getTag()); } Scribe.debug("Item destroyed: " + position); */ } }
1,449
0.636301
0.63009
57
24.421053
22.256044
95
false
false
0
0
0
0
0
0
0.350877
false
false
2
3ab97e58953ee4b505658b5aeba761c887bf8d8e
28,381,143,905,238
69e0a67d6f26b6b6fc7fdcfdf20b6b1bf6b334b7
/persistence/src/main/java/com/dudu/persistence/switchmessage/SwitchMessageService.java
5ba182147c05f0e065b4d0b0accf8c43497852ec
[]
no_license
angcyo/DuDuHome
https://github.com/angcyo/DuDuHome
16190941b63a69076a35b315cdf0e9b3c8116e76
bed918a0421fa133ef00ecd9543d24b1ab650c69
HEAD
2016-08-12T04:54:30.455000
2016-03-02T12:11:58
2016-03-02T12:14:26
53,309,368
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dudu.persistence.switchmessage; import rx.Observable; /** * Created by Administrator on 2016/2/20. */ public interface SwitchMessageService { public Observable<SwitchMessage> findSwitch(String Key); public Observable<SwitchMessage> saveSwitch(SwitchMessage message); }
UTF-8
Java
308
java
SwitchMessageService.java
Java
[]
null
[]
package com.dudu.persistence.switchmessage; import rx.Observable; /** * Created by Administrator on 2016/2/20. */ public interface SwitchMessageService { public Observable<SwitchMessage> findSwitch(String Key); public Observable<SwitchMessage> saveSwitch(SwitchMessage message); }
308
0.743506
0.720779
13
21.692308
24.860796
71
false
false
0
0
0
0
0
0
0.307692
false
false
2
316fad47b9398e71b3c896b249e24881e1123d61
34,531,537,067,157
24437a71852951c6cce739c390a648514b537967
/src/main/java/com/zhku/bean/MyCourseScheme.java
cf011ea55fac0c25c0ea06a0f38e0170531628cf
[ "MIT" ]
permissive
londist/zhkuas_ssm_maven
https://github.com/londist/zhkuas_ssm_maven
e252e59bb1f9c87551f1fc793760b2a7d5a9a815
8e86c619218ad5ada2a7e3c11e3449b1ffd79930
refs/heads/master
2019-01-20T17:05:18.023000
2017-05-01T14:28:49
2017-05-01T14:28:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhku.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.zhku.utils.ServiceUtils; public class MyCourseScheme implements Serializable { /** * */ private static final long serialVersionUID = 4221922186050787945L; private Integer id; private Term term; private String cNo; private String displayValue; private String formValue; private Integer uid; private Course course; private String orderNum; private String schoolTime; public String getcNo() { return cNo; } public void setcNo(String cNo) { this.cNo = cNo; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } public String getFormValue() { return formValue; } public void setFormValue(String formValue) { this.formValue = formValue; } /** * @return the course */ public Course getCourse() { return course; } /** * @param course the course to set */ public void setCourse(Course course) { this.course = course; } /** * @return the orderNum */ public String getOrderNum() { return orderNum; } /** * @param orderNum the orderNum to set */ public void setOrderNum(String orderNum) { this.orderNum = orderNum; } public String getSchoolTime() { return schoolTime; } public void setSchoolTime(String schoolTime) { this.schoolTime = schoolTime; } public List<TimeWapper> getCourseTimeList() { String timeStr =this.getSchoolTime().replaceAll("&nbsp;", ""); String timeItems[]=timeStr.split("<br>"); List<TimeWapper> timeList =new ArrayList<TimeWapper>(); for(int i=0;i<timeItems.length;++i){ if(timeItems[i]==null||timeItems[i].equals("")) continue; List<Integer> periodList =new ArrayList<Integer>(); List<Integer> sectionList =new ArrayList<Integer>(); int indexWeek=timeItems[i].indexOf("周"); int week=ServiceUtils.getNumOfWeek((timeItems[i].substring(indexWeek+1,indexWeek+2))); String periodStr =timeItems[i].substring(0,indexWeek); String portionsOfPeriod[] =periodStr.split(","); //周 for(String portion:portionsOfPeriod){ String period[] =portion.split("-"); if(period.length>=2){ for(int j=Integer.valueOf(period[0]);j<=Integer.valueOf(period[1]);++j){ periodList.add(j); } }else{ periodList.add(Integer.valueOf(period[0])); } } //节 String sectionStr =timeItems[i].substring(indexWeek+3,timeItems[i].indexOf("节")); String sections[] =sectionStr.split("-"); for(int k=Integer.valueOf(sections[0]);k<=Integer.valueOf(sections[1]);++k){ sectionList.add(k); } TimeWapper timeWipper =new TimeWapper(periodList, sectionList, week); timeList.add(timeWipper); } return timeList; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Term getTerm() { return term; } public void setTerm(Term term) { this.term = term; } }
UTF-8
Java
3,083
java
MyCourseScheme.java
Java
[]
null
[]
package com.zhku.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.zhku.utils.ServiceUtils; public class MyCourseScheme implements Serializable { /** * */ private static final long serialVersionUID = 4221922186050787945L; private Integer id; private Term term; private String cNo; private String displayValue; private String formValue; private Integer uid; private Course course; private String orderNum; private String schoolTime; public String getcNo() { return cNo; } public void setcNo(String cNo) { this.cNo = cNo; } public String getDisplayValue() { return displayValue; } public void setDisplayValue(String displayValue) { this.displayValue = displayValue; } public String getFormValue() { return formValue; } public void setFormValue(String formValue) { this.formValue = formValue; } /** * @return the course */ public Course getCourse() { return course; } /** * @param course the course to set */ public void setCourse(Course course) { this.course = course; } /** * @return the orderNum */ public String getOrderNum() { return orderNum; } /** * @param orderNum the orderNum to set */ public void setOrderNum(String orderNum) { this.orderNum = orderNum; } public String getSchoolTime() { return schoolTime; } public void setSchoolTime(String schoolTime) { this.schoolTime = schoolTime; } public List<TimeWapper> getCourseTimeList() { String timeStr =this.getSchoolTime().replaceAll("&nbsp;", ""); String timeItems[]=timeStr.split("<br>"); List<TimeWapper> timeList =new ArrayList<TimeWapper>(); for(int i=0;i<timeItems.length;++i){ if(timeItems[i]==null||timeItems[i].equals("")) continue; List<Integer> periodList =new ArrayList<Integer>(); List<Integer> sectionList =new ArrayList<Integer>(); int indexWeek=timeItems[i].indexOf("周"); int week=ServiceUtils.getNumOfWeek((timeItems[i].substring(indexWeek+1,indexWeek+2))); String periodStr =timeItems[i].substring(0,indexWeek); String portionsOfPeriod[] =periodStr.split(","); //周 for(String portion:portionsOfPeriod){ String period[] =portion.split("-"); if(period.length>=2){ for(int j=Integer.valueOf(period[0]);j<=Integer.valueOf(period[1]);++j){ periodList.add(j); } }else{ periodList.add(Integer.valueOf(period[0])); } } //节 String sectionStr =timeItems[i].substring(indexWeek+3,timeItems[i].indexOf("节")); String sections[] =sectionStr.split("-"); for(int k=Integer.valueOf(sections[0]);k<=Integer.valueOf(sections[1]);++k){ sectionList.add(k); } TimeWapper timeWipper =new TimeWapper(periodList, sectionList, week); timeList.add(timeWipper); } return timeList; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Term getTerm() { return term; } public void setTerm(Term term) { this.term = term; } }
3,083
0.691707
0.681951
129
22.83721
20.70606
89
false
false
0
0
0
0
0
0
2.131783
false
false
2
7fd3fbe3f72323a4acb9181e0a52ea647c4d1989
34,565,896,805,696
295d46b5559afd122ace148998dbd6c6460235f8
/src/main/java/com/learning/fun/CamelIntegration/processor/MyGenericProcessor.java
cde600a245c0db08dde3e4fe1c94045552dac2ea
[]
no_license
vikas2453/CamelIntegration
https://github.com/vikas2453/CamelIntegration
d8d464e41ec8f19187bf05b3fcdb9125f060e804
5e88484e7e63570971259a86735a36db52129de5
refs/heads/master
2020-07-25T17:49:00.944000
2019-09-24T00:05:44
2019-09-24T00:05:44
208,343,684
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.learning.fun.CamelIntegration.processor; import java.util.LinkedHashMap; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.springframework.context.annotation.Configuration; import com.google.gson.Gson; import com.learning.fun.CamelIntegration.model.ProcessorModel; import lombok.extern.slf4j.Slf4j; @Configuration @Slf4j public class MyGenericProcessor implements Processor { Gson gson = new Gson(); @Override public void process(Exchange exchange) throws Exception { String defaultBodyMap= exchange.getIn().getBody(String.class); LinkedHashMap<String, String> modelObj= exchange.getIn().getBody(LinkedHashMap.class); log.info("Received defaultBodyMap: "+defaultBodyMap); log.info("modelObj: "+modelObj); Class<MyAbstractProcessor> myAbstractProcessorClass= (Class<MyAbstractProcessor>)Class.forName("com.learning.fun.CamelIntegration.processor."+modelObj.get("processorName")); MyAbstractProcessor myAbstractProcessor = myAbstractProcessorClass.getConstructor().newInstance(); myAbstractProcessor.setPayloadString(modelObj.get("payload")); myAbstractProcessor.execute(); } /*private ProcessorModel getModel(String json) { String [] splitted=json.split("="); ProcessorModel modelObj = new ProcessorModel(); modelObj.setId(Integer.parseInt(splitted[1].split(",")[0])); modelObj.setProcessorName(splitted[2].split(",")[0]); int lastIndex=splitted[3].length()-1; String payload=splitted[3].substring(0, lastIndex); modelObj.setPayload(payload); return modelObj; }*/ }
UTF-8
Java
1,658
java
MyGenericProcessor.java
Java
[]
null
[]
package com.learning.fun.CamelIntegration.processor; import java.util.LinkedHashMap; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.springframework.context.annotation.Configuration; import com.google.gson.Gson; import com.learning.fun.CamelIntegration.model.ProcessorModel; import lombok.extern.slf4j.Slf4j; @Configuration @Slf4j public class MyGenericProcessor implements Processor { Gson gson = new Gson(); @Override public void process(Exchange exchange) throws Exception { String defaultBodyMap= exchange.getIn().getBody(String.class); LinkedHashMap<String, String> modelObj= exchange.getIn().getBody(LinkedHashMap.class); log.info("Received defaultBodyMap: "+defaultBodyMap); log.info("modelObj: "+modelObj); Class<MyAbstractProcessor> myAbstractProcessorClass= (Class<MyAbstractProcessor>)Class.forName("com.learning.fun.CamelIntegration.processor."+modelObj.get("processorName")); MyAbstractProcessor myAbstractProcessor = myAbstractProcessorClass.getConstructor().newInstance(); myAbstractProcessor.setPayloadString(modelObj.get("payload")); myAbstractProcessor.execute(); } /*private ProcessorModel getModel(String json) { String [] splitted=json.split("="); ProcessorModel modelObj = new ProcessorModel(); modelObj.setId(Integer.parseInt(splitted[1].split(",")[0])); modelObj.setProcessorName(splitted[2].split(",")[0]); int lastIndex=splitted[3].length()-1; String payload=splitted[3].substring(0, lastIndex); modelObj.setPayload(payload); return modelObj; }*/ }
1,658
0.745476
0.738842
55
28.145454
32.961918
175
false
false
0
0
0
0
0
0
1.527273
false
false
2
b3609be015d8d25443a8775fdb6e59ae8f314b46
32,349,693,710,151
cd2ebe5229eac876318f9117cd2e5888ce34972f
/Sample_Works/Java_Projects/JavaFX Platformer/src/main/java/stickman/model/State/SaveGame.java
7d578881dd4563f87f8c32fd59f77d2bf9f5668c
[]
no_license
BrantHird/sample_works
https://github.com/BrantHird/sample_works
f15ab1e3fa597c8afbc6bb0f90857c49ceccc64e
6a1c45ba0279b7eaea99eb4f7cc800ebf8773036
refs/heads/master
2022-12-30T13:13:08.376000
2020-10-16T09:00:15
2020-10-16T09:00:15
302,593,930
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package stickman.model.State; import stickman.model.GameEngine; import stickman.model.config.ConfigParser; import stickman.model.levels.Level; import stickman.model.levels.ScoreKeeper; public class SaveGame { private Level savedGame; private ScoreKeeper savedScore ; private long time; private ConfigParser configuration; private int levelTracker; public SaveGame(Level level, ScoreKeeper score, long timeSinceStart, ConfigParser levelConfig, int levelTrack){ savedGame = level ; savedScore = score ; time = timeSinceStart; configuration = levelConfig; levelTracker = levelTrack; } public Level getSavedGame(){ return savedGame; } public ScoreKeeper getSavedScore(){ return savedScore; } public long getTimeSinceStart(){ return time;} public ConfigParser getLevelConfiguration(){return configuration;} public int getLevelNumber(){return levelTracker;} }
UTF-8
Java
1,024
java
SaveGame.java
Java
[]
null
[]
package stickman.model.State; import stickman.model.GameEngine; import stickman.model.config.ConfigParser; import stickman.model.levels.Level; import stickman.model.levels.ScoreKeeper; public class SaveGame { private Level savedGame; private ScoreKeeper savedScore ; private long time; private ConfigParser configuration; private int levelTracker; public SaveGame(Level level, ScoreKeeper score, long timeSinceStart, ConfigParser levelConfig, int levelTrack){ savedGame = level ; savedScore = score ; time = timeSinceStart; configuration = levelConfig; levelTracker = levelTrack; } public Level getSavedGame(){ return savedGame; } public ScoreKeeper getSavedScore(){ return savedScore; } public long getTimeSinceStart(){ return time;} public ConfigParser getLevelConfiguration(){return configuration;} public int getLevelNumber(){return levelTracker;} }
1,024
0.68457
0.68457
43
21.813953
23.533504
115
false
false
0
0
0
0
0
0
0.55814
false
false
2
7bc617678c89c879bfd4bc5300b4f7da48b25b12
19,928,648,270,535
9f8cc3deecef3ad1692ccf8c16b755570bf2eac0
/app/src/main/java/com/man_jou/projectbrain/fragment/UserTodosFragment.java
be7a43f2e634f32af56722e2ae2c310fcfa7ad5c
[]
no_license
evakung56412/project-brain
https://github.com/evakung56412/project-brain
fc84d1ec71f1f4790908305d240081ec1c1d70dc
33f0ccb2142aca9f9602bd554c0617efd1d2e106
refs/heads/master
2022-11-24T06:49:26.020000
2020-07-31T05:19:56
2020-07-31T05:19:56
276,097,771
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.man_jou.projectbrain.fragment; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.man_jou.projectbrain.R; import com.man_jou.projectbrain.adapter.UserTodosAdapter; import com.man_jou.projectbrain.callback.ApiCallback; import com.man_jou.projectbrain.callback.IdeaCallback; import com.man_jou.projectbrain.model.Idea; import com.man_jou.projectbrain.rest.GetTaskJson; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.ArrayList; import java.util.Collections; public class UserTodosFragment extends Fragment implements ApiCallback<String>, IdeaCallback { private TextView empTodoTV; private RecyclerView recyclerTodos; private UserTodosAdapter adapter; private String username; private ArrayList<Idea> ideaArrayList; public UserTodosFragment getFragment() { return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { username = getArguments().getString("username"); return inflater.inflate(R.layout.fragment_user_todos, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); empTodoTV = view.findViewById(R.id.empTodoTV); ideaArrayList = new ArrayList<>(); adapter = new UserTodosAdapter(getActivity(), ideaArrayList, this); recyclerTodos = view.findViewById(R.id.recyclerTodos); recyclerTodos.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerTodos.setAdapter(adapter); String request = "http://10.0.2.2:8080/brain/" + username + "/todos"; new GetTaskJson<>(String.class, getFragment()).execute(request); } /* ApiCallback<String> */ @Override public void postResult(ResponseEntity<String> responseEntity) {} @Override public void getResult(ResponseEntity<String> responseEntity) { if (responseEntity.getStatusCode() == HttpStatus.OK) { String response = responseEntity.getBody().substring(1, responseEntity.getBody().length()-1); if (!response.equals("")) { parseResponse(response); empTodoTV.setVisibility(View.GONE); } else { empTodoTV.setVisibility(View.VISIBLE); } } else { Log.i("Get User Todos Failed", responseEntity.getStatusCode().toString()); } } public void parseResponse(String response) { response = response.replaceAll("[{}\"]", ""); int ideaDataLength = 10; String[] pairs = response.split(","); for (int i = 0; i < pairs.length; i += ideaDataLength) { Idea idea = new Idea(); for (int j = i; j < i + ideaDataLength; j++) { String[] keyValue = pairs[j].split(":"); if (keyValue[0].equals("id")) { idea.setId(Long.valueOf(keyValue[1])); } else if (keyValue[0].equals("citeId")) { idea.setCiteId(keyValue[1]); } else if (keyValue[0].equals("title")) { idea.setTitle(keyValue[1]); } else if (keyValue[0].equals("context")) { idea.setContext(keyValue[1]); } else if (keyValue[0].equals("content")) { idea.setContent(keyValue[1]); } } ideaArrayList.add(idea); } Collections.sort(ideaArrayList, Collections.reverseOrder()); adapter.notifyDataSetChanged(); } /* ApiCallback<String> */ @Override public void deleteItem(int position, Object object) { //TODO: delete todo } @Override public void directToOriginal(Object object) { Idea idea = (Idea) object; Bundle bundle = new Bundle(); bundle.putString("citeId", idea.getCiteId()); OriginalIdeaFragment fragment = new OriginalIdeaFragment(); fragment.setArguments(bundle); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, fragment) .addToBackStack(fragment.getClass().getName()).commit(); } }
UTF-8
Java
4,922
java
UserTodosFragment.java
Java
[ { "context": "e) {\n username = getArguments().getString(\"username\");\n return inflater.inflate(R.layout.fragm", "end": 1563, "score": 0.9628573656082153, "start": 1555, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.man_jou.projectbrain.fragment; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.man_jou.projectbrain.R; import com.man_jou.projectbrain.adapter.UserTodosAdapter; import com.man_jou.projectbrain.callback.ApiCallback; import com.man_jou.projectbrain.callback.IdeaCallback; import com.man_jou.projectbrain.model.Idea; import com.man_jou.projectbrain.rest.GetTaskJson; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.ArrayList; import java.util.Collections; public class UserTodosFragment extends Fragment implements ApiCallback<String>, IdeaCallback { private TextView empTodoTV; private RecyclerView recyclerTodos; private UserTodosAdapter adapter; private String username; private ArrayList<Idea> ideaArrayList; public UserTodosFragment getFragment() { return this; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { username = getArguments().getString("username"); return inflater.inflate(R.layout.fragment_user_todos, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); empTodoTV = view.findViewById(R.id.empTodoTV); ideaArrayList = new ArrayList<>(); adapter = new UserTodosAdapter(getActivity(), ideaArrayList, this); recyclerTodos = view.findViewById(R.id.recyclerTodos); recyclerTodos.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerTodos.setAdapter(adapter); String request = "http://10.0.2.2:8080/brain/" + username + "/todos"; new GetTaskJson<>(String.class, getFragment()).execute(request); } /* ApiCallback<String> */ @Override public void postResult(ResponseEntity<String> responseEntity) {} @Override public void getResult(ResponseEntity<String> responseEntity) { if (responseEntity.getStatusCode() == HttpStatus.OK) { String response = responseEntity.getBody().substring(1, responseEntity.getBody().length()-1); if (!response.equals("")) { parseResponse(response); empTodoTV.setVisibility(View.GONE); } else { empTodoTV.setVisibility(View.VISIBLE); } } else { Log.i("Get User Todos Failed", responseEntity.getStatusCode().toString()); } } public void parseResponse(String response) { response = response.replaceAll("[{}\"]", ""); int ideaDataLength = 10; String[] pairs = response.split(","); for (int i = 0; i < pairs.length; i += ideaDataLength) { Idea idea = new Idea(); for (int j = i; j < i + ideaDataLength; j++) { String[] keyValue = pairs[j].split(":"); if (keyValue[0].equals("id")) { idea.setId(Long.valueOf(keyValue[1])); } else if (keyValue[0].equals("citeId")) { idea.setCiteId(keyValue[1]); } else if (keyValue[0].equals("title")) { idea.setTitle(keyValue[1]); } else if (keyValue[0].equals("context")) { idea.setContext(keyValue[1]); } else if (keyValue[0].equals("content")) { idea.setContent(keyValue[1]); } } ideaArrayList.add(idea); } Collections.sort(ideaArrayList, Collections.reverseOrder()); adapter.notifyDataSetChanged(); } /* ApiCallback<String> */ @Override public void deleteItem(int position, Object object) { //TODO: delete todo } @Override public void directToOriginal(Object object) { Idea idea = (Idea) object; Bundle bundle = new Bundle(); bundle.putString("citeId", idea.getCiteId()); OriginalIdeaFragment fragment = new OriginalIdeaFragment(); fragment.setArguments(bundle); getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, fragment) .addToBackStack(fragment.getClass().getName()).commit(); } }
4,922
0.634498
0.629622
152
31.388159
26.268866
105
false
false
0
0
0
0
0
0
0.565789
false
false
2
94bacc63f53f7c14e1e7440c634cc5af40118fb6
34,531,537,073,770
ebc880d070e15180b3636c2c309969e9806d4829
/src/test/java/advent2017/AdventDay3Test.java
54c1918931f4bc9ff547ebf41efe2f5cb73724e1
[]
no_license
recreational-snacker/advent
https://github.com/recreational-snacker/advent
0d5fcb5d2052cd8f8416dc061485d626f3ce022a
7a497ee13a8bfe51359549617031c4f92ce5a1af
refs/heads/master
2022-12-16T15:50:20.479000
2022-12-05T08:23:02
2022-12-05T08:23:02
75,391,398
0
0
null
false
2021-12-02T09:10:34
2016-12-02T11:51:50
2021-12-02T09:09:33
2021-12-02T09:10:33
438
0
0
0
Java
false
false
package advent2017; import org.junit.Assert; import org.junit.Test; import java.util.*; public class AdventDay3Test { Integer input = 265149; @Test public void test() { List<Integer> spiral = new ArrayList<>(); spiral.add(1); for (int i = 1; ; i++) { Integer corner = spiral.get(spiral.size() - 1) + (8 * i); if (corner > input) { spiral.add(corner); break; } else { spiral.add(corner); } } Integer ringStart = spiral.get(spiral.size() - 2); Integer noInRow = (spiral.size() - 1) * 2; Integer rowStart = ringStart; Integer rowEnd = rowStart + noInRow; while (rowEnd < input) { rowStart = rowEnd; rowEnd = rowStart + noInRow; } Integer distanceTo1 = Math.abs(input - (rowEnd - (noInRow / 2))) + spiral.size() - 1; System.out.println("Distance to 1: " + distanceTo1); Assert.assertEquals(438, distanceTo1.intValue()); } private Map<String, Integer> values = new HashMap<>(); private List<String> coordinates = new ArrayList<>(); Integer value = 0; @Test public void testPart2() { coordinates.add("0,0"); values.put("0,0", 1); for (int ring = 1; ; ring++) { int noInRow = (8 * ring) / 4; processCoords(1, 0); for (int j = 0; j < noInRow - 1; j++) { processCoords(0, 1); } for (int j = 0; j < noInRow; j++) { processCoords(-1, 0); } for (int j = 0; j < noInRow; j++) { processCoords(0, -1); } for (int j = 0; j < noInRow; j++) { processCoords(1, 0); } if (value != 0) { break; } } System.out.println(value); Assert.assertEquals(266330, value.intValue()); } private void processCoords(int dx, int dy) { List<String> coords; int x; int y; coords = Arrays.asList(coordinates.get(coordinates.size() - 1).split(",")); x = Integer.valueOf(coords.get(0)) + dx; y = Integer.valueOf(coords.get(1)) + dy; calculateValue(x, y); } private void calculateValue(int x, int y) { Integer sumValue = 0; //north int nx = x; int ny = y + 1; sumValue = sumValue + findValue(nx, ny); //nw int nwx = x - 1; int nwy = y + 1; sumValue = sumValue + findValue(nwx, nwy); //w int wx = x - 1; int wy = y; sumValue = sumValue + findValue(wx, wy); //sw int swx = x - 1; int swy = y - 1; sumValue = sumValue + findValue(swx, swy); //s int sx = x; int sy = y - 1; sumValue = sumValue + findValue(sx, sy); //se int sex = x + 1; int sey = y - 1; sumValue = sumValue + findValue(sex, sey); //e int ex = x + 1; int ey = y; sumValue = sumValue + findValue(ex, ey); //ne int nex = x + 1; int ney = y + 1; sumValue = sumValue + findValue(nex, ney); values.put(x + "," + y, sumValue); coordinates.add(x + "," + y); if (value == 0 && sumValue > input) { value = sumValue; } } private int findValue(int x, int y) { String coord = x + "," + y; Integer nv = values.get(coord); if (nv == null) { nv = 0; } return nv; } }
UTF-8
Java
3,657
java
AdventDay3Test.java
Java
[]
null
[]
package advent2017; import org.junit.Assert; import org.junit.Test; import java.util.*; public class AdventDay3Test { Integer input = 265149; @Test public void test() { List<Integer> spiral = new ArrayList<>(); spiral.add(1); for (int i = 1; ; i++) { Integer corner = spiral.get(spiral.size() - 1) + (8 * i); if (corner > input) { spiral.add(corner); break; } else { spiral.add(corner); } } Integer ringStart = spiral.get(spiral.size() - 2); Integer noInRow = (spiral.size() - 1) * 2; Integer rowStart = ringStart; Integer rowEnd = rowStart + noInRow; while (rowEnd < input) { rowStart = rowEnd; rowEnd = rowStart + noInRow; } Integer distanceTo1 = Math.abs(input - (rowEnd - (noInRow / 2))) + spiral.size() - 1; System.out.println("Distance to 1: " + distanceTo1); Assert.assertEquals(438, distanceTo1.intValue()); } private Map<String, Integer> values = new HashMap<>(); private List<String> coordinates = new ArrayList<>(); Integer value = 0; @Test public void testPart2() { coordinates.add("0,0"); values.put("0,0", 1); for (int ring = 1; ; ring++) { int noInRow = (8 * ring) / 4; processCoords(1, 0); for (int j = 0; j < noInRow - 1; j++) { processCoords(0, 1); } for (int j = 0; j < noInRow; j++) { processCoords(-1, 0); } for (int j = 0; j < noInRow; j++) { processCoords(0, -1); } for (int j = 0; j < noInRow; j++) { processCoords(1, 0); } if (value != 0) { break; } } System.out.println(value); Assert.assertEquals(266330, value.intValue()); } private void processCoords(int dx, int dy) { List<String> coords; int x; int y; coords = Arrays.asList(coordinates.get(coordinates.size() - 1).split(",")); x = Integer.valueOf(coords.get(0)) + dx; y = Integer.valueOf(coords.get(1)) + dy; calculateValue(x, y); } private void calculateValue(int x, int y) { Integer sumValue = 0; //north int nx = x; int ny = y + 1; sumValue = sumValue + findValue(nx, ny); //nw int nwx = x - 1; int nwy = y + 1; sumValue = sumValue + findValue(nwx, nwy); //w int wx = x - 1; int wy = y; sumValue = sumValue + findValue(wx, wy); //sw int swx = x - 1; int swy = y - 1; sumValue = sumValue + findValue(swx, swy); //s int sx = x; int sy = y - 1; sumValue = sumValue + findValue(sx, sy); //se int sex = x + 1; int sey = y - 1; sumValue = sumValue + findValue(sex, sey); //e int ex = x + 1; int ey = y; sumValue = sumValue + findValue(ex, ey); //ne int nex = x + 1; int ney = y + 1; sumValue = sumValue + findValue(nex, ney); values.put(x + "," + y, sumValue); coordinates.add(x + "," + y); if (value == 0 && sumValue > input) { value = sumValue; } } private int findValue(int x, int y) { String coord = x + "," + y; Integer nv = values.get(coord); if (nv == null) { nv = 0; } return nv; } }
3,657
0.466229
0.445174
128
27.570313
18.247295
93
false
false
0
0
0
0
0
0
0.882813
false
false
2
ed4efae11c895ca352deff1aa3e4666612b7d922
25,761,213,860,930
7488b5f1fc5a80d07032ee1dc2bc97286fc1140d
/collatex/src/main/java/eu/interedition/collatex/dekker/Tuple.java
40b9baca44ea7e3b92ca0f0a2830466b73145cd8
[ "Apache-2.0" ]
permissive
MikaelHolmstrom/microservices
https://github.com/MikaelHolmstrom/microservices
a0a1bd158d5a74b8c52fb0719337a16b97d61eee
1f9e4f1dcf845c1132e4da04d978256ce6620163
refs/heads/master
2021-01-22T05:20:23.724000
2011-12-20T12:10:43
2011-12-20T12:10:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eu.interedition.collatex.dekker; import com.google.common.base.Function; /** * @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a> */ public class Tuple<T> { public final T left; public final T right; public Tuple(T left, T right) { this.left = left; this.right = right; } }
UTF-8
Java
334
java
Tuple.java
Java
[ { "context": "ref=\"http://gregor.middell.net/\" title=\"Homepage\">Gregor Middell</a>\n */\npublic class Tuple<T> {\n\n public final T", "end": 166, "score": 0.9998879432678223, "start": 152, "tag": "NAME", "value": "Gregor Middell" } ]
null
[]
package eu.interedition.collatex.dekker; import com.google.common.base.Function; /** * @author <a href="http://gregor.middell.net/" title="Homepage"><NAME></a> */ public class Tuple<T> { public final T left; public final T right; public Tuple(T left, T right) { this.left = left; this.right = right; } }
326
0.670659
0.670659
17
18.647058
21.320913
83
false
false
0
0
0
0
0
0
0.411765
false
false
2