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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
67813343436669a757e56d5f40cd86bad2c8b158
| 12,876,311,988,234 |
0c530c1ae29350d0afa3489622fa00e91d062da6
|
/src/com/mpe/financial/model/base/BaseProfitLossReportGroup.java
|
1e385f9b2bd1582fdfe709328ecc189d7267f935
|
[] |
no_license
|
dumpvn/gracoaccounting
|
https://github.com/dumpvn/gracoaccounting
|
62569fd905777d06e03ab82758f2d2088f0dcc56
|
45827fc5eef67b4dc3d5fc9d493c67fc3df51a4c
|
refs/heads/master
| 2021-05-28T14:07:28.574000 | 2015-04-07T20:57:00 | 2015-04-07T20:57:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mpe.financial.model.base;
import java.io.Serializable;
/**
* This is an object that contains data related to the table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table=""
*/
public abstract class BaseProfitLossReportGroup implements Serializable {
public static String REF = "ProfitLossReportGroup";
public static String PROP_NAME = "Name";
public static String PROP_GROUPS = "Groups";
public static String PROP_DEBIT = "Debit";
public static String PROP_AMOUNT = "Amount";
public static String PROP_NUMBER_OF_DIGIT = "NumberOfDigit";
// constructors
public BaseProfitLossReportGroup () {
initialize();
}
/**
* Constructor for primary key
*/
public BaseProfitLossReportGroup (long chartOfAccountId) {
this.setChartOfAccountId(chartOfAccountId);
initialize();
}
protected void initialize () {}
private int hashCode = Integer.MIN_VALUE;
// primary key
private long chartOfAccountId;
// fields
private java.lang.String name;
private java.lang.String groups;
private boolean debit;
private double amount;
private int numberOfDigit;
/**
* Return the unique identifier of this class
* @hibernate.id
* column="ChartOfAccountId"
*/
public long getChartOfAccountId () {
return chartOfAccountId;
}
/**
* Set the unique identifier of this class
* @param chartOfAccountId the new ID
*/
public void setChartOfAccountId (long chartOfAccountId) {
this.chartOfAccountId = chartOfAccountId;
this.hashCode = Integer.MIN_VALUE;
}
/**
* Return the value associated with the column: Name
*/
public java.lang.String getName () {
return name;
}
/**
* Set the value related to the column: Name
* @param name the Name value
*/
public void setName (java.lang.String name) {
this.name = name;
}
/**
* Return the value associated with the column: Groups
*/
public java.lang.String getGroups () {
return groups;
}
/**
* Set the value related to the column: Groups
* @param groups the Groups value
*/
public void setGroups (java.lang.String groups) {
this.groups = groups;
}
/**
* Return the value associated with the column: Debit
*/
public boolean isDebit () {
return debit;
}
/**
* Set the value related to the column: Debit
* @param debit the Debit value
*/
public void setDebit (boolean debit) {
this.debit = debit;
}
/**
* Return the value associated with the column: Amount
*/
public double getAmount () {
return amount;
}
/**
* Set the value related to the column: Amount
* @param amount the Amount value
*/
public void setAmount (double amount) {
this.amount = amount;
}
/**
* Return the value associated with the column: NumberOfDigit
*/
public int getNumberOfDigit () {
return numberOfDigit;
}
/**
* Set the value related to the column: NumberOfDigit
* @param numberOfDigit the NumberOfDigit value
*/
public void setNumberOfDigit (int numberOfDigit) {
this.numberOfDigit = numberOfDigit;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof com.mpe.financial.model.ProfitLossReportGroup)) return false;
else {
com.mpe.financial.model.ProfitLossReportGroup profitLossReportGroup = (com.mpe.financial.model.ProfitLossReportGroup) obj;
return (this.getChartOfAccountId() == profitLossReportGroup.getChartOfAccountId());
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
return (int) this.getChartOfAccountId();
}
return this.hashCode;
}
public String toString () {
return super.toString();
}
}
|
UTF-8
|
Java
| 3,887 |
java
|
BaseProfitLossReportGroup.java
|
Java
|
[] | null |
[] |
package com.mpe.financial.model.base;
import java.io.Serializable;
/**
* This is an object that contains data related to the table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table=""
*/
public abstract class BaseProfitLossReportGroup implements Serializable {
public static String REF = "ProfitLossReportGroup";
public static String PROP_NAME = "Name";
public static String PROP_GROUPS = "Groups";
public static String PROP_DEBIT = "Debit";
public static String PROP_AMOUNT = "Amount";
public static String PROP_NUMBER_OF_DIGIT = "NumberOfDigit";
// constructors
public BaseProfitLossReportGroup () {
initialize();
}
/**
* Constructor for primary key
*/
public BaseProfitLossReportGroup (long chartOfAccountId) {
this.setChartOfAccountId(chartOfAccountId);
initialize();
}
protected void initialize () {}
private int hashCode = Integer.MIN_VALUE;
// primary key
private long chartOfAccountId;
// fields
private java.lang.String name;
private java.lang.String groups;
private boolean debit;
private double amount;
private int numberOfDigit;
/**
* Return the unique identifier of this class
* @hibernate.id
* column="ChartOfAccountId"
*/
public long getChartOfAccountId () {
return chartOfAccountId;
}
/**
* Set the unique identifier of this class
* @param chartOfAccountId the new ID
*/
public void setChartOfAccountId (long chartOfAccountId) {
this.chartOfAccountId = chartOfAccountId;
this.hashCode = Integer.MIN_VALUE;
}
/**
* Return the value associated with the column: Name
*/
public java.lang.String getName () {
return name;
}
/**
* Set the value related to the column: Name
* @param name the Name value
*/
public void setName (java.lang.String name) {
this.name = name;
}
/**
* Return the value associated with the column: Groups
*/
public java.lang.String getGroups () {
return groups;
}
/**
* Set the value related to the column: Groups
* @param groups the Groups value
*/
public void setGroups (java.lang.String groups) {
this.groups = groups;
}
/**
* Return the value associated with the column: Debit
*/
public boolean isDebit () {
return debit;
}
/**
* Set the value related to the column: Debit
* @param debit the Debit value
*/
public void setDebit (boolean debit) {
this.debit = debit;
}
/**
* Return the value associated with the column: Amount
*/
public double getAmount () {
return amount;
}
/**
* Set the value related to the column: Amount
* @param amount the Amount value
*/
public void setAmount (double amount) {
this.amount = amount;
}
/**
* Return the value associated with the column: NumberOfDigit
*/
public int getNumberOfDigit () {
return numberOfDigit;
}
/**
* Set the value related to the column: NumberOfDigit
* @param numberOfDigit the NumberOfDigit value
*/
public void setNumberOfDigit (int numberOfDigit) {
this.numberOfDigit = numberOfDigit;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof com.mpe.financial.model.ProfitLossReportGroup)) return false;
else {
com.mpe.financial.model.ProfitLossReportGroup profitLossReportGroup = (com.mpe.financial.model.ProfitLossReportGroup) obj;
return (this.getChartOfAccountId() == profitLossReportGroup.getChartOfAccountId());
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
return (int) this.getChartOfAccountId();
}
return this.hashCode;
}
public String toString () {
return super.toString();
}
}
| 3,887 | 0.668124 | 0.668124 | 186 | 18.908602 | 22.427595 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.021505 | false | false |
13
|
a7f6ccfba29ff7bdbfcf43af5cddafe25267e190
| 12,876,311,989,393 |
cae6dabddff939c87c04d17871fdc84fbf9e59ec
|
/qt-admin/src/main/java/com/quant/admin/service/impl/OrdersServiceImpl.java
|
8d3e043dbab3582e932fe424e8244b1ad58d17c5
|
[] |
no_license
|
efishcn/quant4j
|
https://github.com/efishcn/quant4j
|
9985e770689d03f091b0e4c82310aa3f67f2c0a1
|
2e9fa5921115bca3f0c95a6fed7ffc59fa47b19f
|
refs/heads/master
| 2023-05-23T09:09:35.976000 | 2021-06-10T09:51:18 | 2021-06-10T09:51:18 | 336,692,990 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.quant.admin.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.quant.admin.dao.OrdersMapper;
import com.quant.common.domain.entity.Orders;
import com.quant.admin.service.OrdersService;
import com.quant.core.api.ApiResult;
import com.quant.common.enums.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Collections;
/**
* <p>
* 服务实现类
* </p>
*
* @author yang
* @since 2019-04-22
*/
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
@Override
public ApiResult getOrderByRobotId(int rid, int page, int limit) {
try {
Wrapper<Orders> ordersWrapper = new EntityWrapper<>();
ordersWrapper.eq("robot_id", rid);
ordersWrapper.orderDesc(Collections.singleton("order_id"));
Orders orders = new Orders();
Page<Orders> ordersPage = orders.selectPage(new Page<>(page, limit), ordersWrapper);
return new ApiResult(Status.SUCCESS, ordersPage);
} catch (Exception e) {
e.printStackTrace();
log.error("查询机器人订单列表失败 {}", e.getMessage());
}
return new ApiResult(Status.ERROR);
}
}
|
UTF-8
|
Java
| 1,457 |
java
|
OrdersServiceImpl.java
|
Java
|
[
{
"context": "ctions;\n\n/**\n * <p>\n * 服务实现类\n * </p>\n *\n * @author yang\n * @since 2019-04-22\n */\n@Slf4j\n@Service\npublic c",
"end": 612,
"score": 0.8043331503868103,
"start": 608,
"tag": "USERNAME",
"value": "yang"
}
] | null |
[] |
package com.quant.admin.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.quant.admin.dao.OrdersMapper;
import com.quant.common.domain.entity.Orders;
import com.quant.admin.service.OrdersService;
import com.quant.core.api.ApiResult;
import com.quant.common.enums.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Collections;
/**
* <p>
* 服务实现类
* </p>
*
* @author yang
* @since 2019-04-22
*/
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
@Override
public ApiResult getOrderByRobotId(int rid, int page, int limit) {
try {
Wrapper<Orders> ordersWrapper = new EntityWrapper<>();
ordersWrapper.eq("robot_id", rid);
ordersWrapper.orderDesc(Collections.singleton("order_id"));
Orders orders = new Orders();
Page<Orders> ordersPage = orders.selectPage(new Page<>(page, limit), ordersWrapper);
return new ApiResult(Status.SUCCESS, ordersPage);
} catch (Exception e) {
e.printStackTrace();
log.error("查询机器人订单列表失败 {}", e.getMessage());
}
return new ApiResult(Status.ERROR);
}
}
| 1,457 | 0.701754 | 0.694035 | 44 | 31.386364 | 26.033384 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681818 | false | false |
13
|
802dcf330c87c2e5880e1a18fb9da700e639d99d
| 12,876,311,988,689 |
ebe5a9cbebaee07f63f6903b03a8cecf4b236326
|
/JiHe/src/SetInterface/LinkedHashSetDemo.java
|
1df99f5af52c2c9c0e1b0ba0a1e40b63df1a5954
|
[] |
no_license
|
GithubRobot01/itheima01
|
https://github.com/GithubRobot01/itheima01
|
cdcb909210c91236a75c9d15a02873de86dcb042
|
3bad1ec2d1ca2d8b9198fcf7dfd5128559124be5
|
refs/heads/master
| 2022-01-18T10:35:40.446000 | 2019-08-08T02:53:11 | 2019-08-08T02:53:11 | 197,952,235 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package SetInterface;
import java.util.HashSet;
import java.util.LinkedHashSet;
/*
java.util.LinkedHashSet集合extends HashSet集合
LinkedHashSet集合特点;底层是一个哈希表(数组+链表/红黑树)+链表:多了一条链表(记录元素的存储顺序),保证元素有序
*/
public class LinkedHashSetDemo {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("def");
set.add("abc");
set.add("ghi");
set.add("abc");
System.out.println(set);//无序
LinkedHashSet<String> link=new LinkedHashSet<>();
link.add("def");
link.add("abc");
link.add("ghi");
link.add("abc");
System.out.println(link);//有序
}
}
|
UTF-8
|
Java
| 757 |
java
|
LinkedHashSetDemo.java
|
Java
|
[] | null |
[] |
package SetInterface;
import java.util.HashSet;
import java.util.LinkedHashSet;
/*
java.util.LinkedHashSet集合extends HashSet集合
LinkedHashSet集合特点;底层是一个哈希表(数组+链表/红黑树)+链表:多了一条链表(记录元素的存储顺序),保证元素有序
*/
public class LinkedHashSetDemo {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("def");
set.add("abc");
set.add("ghi");
set.add("abc");
System.out.println(set);//无序
LinkedHashSet<String> link=new LinkedHashSet<>();
link.add("def");
link.add("abc");
link.add("ghi");
link.add("abc");
System.out.println(link);//有序
}
}
| 757 | 0.613394 | 0.613394 | 24 | 26.375 | 16.570086 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false |
13
|
c9b3f6d4fb8cff779e0dbd33f1026fee3deb35aa
| 21,577,915,722,607 |
3f87df2a878de64eccdcac22bb09b8944ba06fd4
|
/java/testing/junit/udemy/junit5/src/main/java/workshop/java/testing/junit/udemy/junit5/sfgpetclinic/fauxspring/ModelMap.java
|
9c38eeb1d8ce5e8198776cea8f06bd4162017616
|
[] |
no_license
|
juncevich/workshop
|
https://github.com/juncevich/workshop
|
621d1262a616ea4664198338b712898af9e61a76
|
fbaeecfb399be65a315c60d0aa24ecae4067918d
|
refs/heads/master
| 2023-04-30T14:53:43.154000 | 2023-04-15T17:26:53 | 2023-04-15T17:26:53 | 78,441,425 | 0 | 0 | null | false | 2023-03-28T20:52:35 | 2017-01-09T15:27:29 | 2022-01-10T20:51:12 | 2023-03-28T20:52:34 | 100,702 | 0 | 0 | 238 |
JavaScript
| false | false |
package workshop.java.testing.junit.udemy.junit5.sfgpetclinic.fauxspring;
import workshop.java.testing.junit.udemy.junit5.sfgpetclinic.model.Pet;
public interface ModelMap {
void put(String pet, Pet pet1);
}
|
UTF-8
|
Java
| 214 |
java
|
ModelMap.java
|
Java
|
[] | null |
[] |
package workshop.java.testing.junit.udemy.junit5.sfgpetclinic.fauxspring;
import workshop.java.testing.junit.udemy.junit5.sfgpetclinic.model.Pet;
public interface ModelMap {
void put(String pet, Pet pet1);
}
| 214 | 0.799065 | 0.785047 | 7 | 29.571428 | 29.769865 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false |
13
|
f4d93a88f4cebe7946d7d311c10d16f9f0ecf957
| 26,139,170,996,398 |
2a4585bb74ca0bc5decfed0b63555056ee9746a8
|
/src/main/java/Pojo/Bookmarks/TagRankListItem.java
|
883eb4b1c47f837dc647a41fa5ed417189b020ba
|
[] |
no_license
|
adeepakb1/kristal
|
https://github.com/adeepakb1/kristal
|
bec111ac5308e040a1410f16874eb28ac67c253d
|
9e24b6792ec95a25e174ec2cb79ee78e0542e722
|
refs/heads/master
| 2022-07-04T00:52:45.168000 | 2020-02-28T11:47:51 | 2020-02-28T11:47:51 | 243,746,518 | 0 | 0 | null | false | 2022-05-20T21:29:27 | 2020-02-28T11:25:31 | 2020-02-28T11:47:54 | 2022-05-20T21:29:27 | 61 | 0 | 0 | 2 |
Java
| false | false |
package Pojo.Bookmarks;
import java.util.List;
public class TagRankListItem{
private int tagId;
private List<CategoryListItem> categoryList;
private String tagName;
private int tagRank;
public void setTagId(int tagId){
this.tagId = tagId;
}
public int getTagId(){
return tagId;
}
public void setCategoryList(List<CategoryListItem> categoryList){
this.categoryList = categoryList;
}
public List<CategoryListItem> getCategoryList(){
return categoryList;
}
public void setTagName(String tagName){
this.tagName = tagName;
}
public String getTagName(){
return tagName;
}
public void setTagRank(int tagRank){
this.tagRank = tagRank;
}
public int getTagRank(){
return tagRank;
}
@Override
public String toString(){
return
"TagRankListItem{" +
"tagId = '" + tagId + '\'' +
",categoryList = '" + categoryList + '\'' +
",tagName = '" + tagName + '\'' +
",tagRank = '" + tagRank + '\'' +
"}";
}
}
|
UTF-8
|
Java
| 963 |
java
|
TagRankListItem.java
|
Java
|
[] | null |
[] |
package Pojo.Bookmarks;
import java.util.List;
public class TagRankListItem{
private int tagId;
private List<CategoryListItem> categoryList;
private String tagName;
private int tagRank;
public void setTagId(int tagId){
this.tagId = tagId;
}
public int getTagId(){
return tagId;
}
public void setCategoryList(List<CategoryListItem> categoryList){
this.categoryList = categoryList;
}
public List<CategoryListItem> getCategoryList(){
return categoryList;
}
public void setTagName(String tagName){
this.tagName = tagName;
}
public String getTagName(){
return tagName;
}
public void setTagRank(int tagRank){
this.tagRank = tagRank;
}
public int getTagRank(){
return tagRank;
}
@Override
public String toString(){
return
"TagRankListItem{" +
"tagId = '" + tagId + '\'' +
",categoryList = '" + categoryList + '\'' +
",tagName = '" + tagName + '\'' +
",tagRank = '" + tagRank + '\'' +
"}";
}
}
| 963 | 0.668743 | 0.668743 | 53 | 17.188679 | 16.311886 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.471698 | false | false |
13
|
323a5ff4a2517ff2ec7259dc2aedee60a1d0097a
| 14,405,320,335,472 |
3cc927d3ebf2c568194737201e99ef03a6821e4c
|
/src/main/java/com/corejava/java8/stream/terminal/ForEach.java
|
3c4b2d94b99cb3fa8611527de57a871006e9f7e5
|
[] |
no_license
|
gaganichake/CoreJava
|
https://github.com/gaganichake/CoreJava
|
bd81e38725a99a166313f51c22aa97f4385294e2
|
5e53ef2ec772be18cb369ede3cde1b08e07c4a2e
|
refs/heads/master
| 2022-09-09T20:51:47.344000 | 2022-08-25T00:08:39 | 2022-08-25T00:08:39 | 105,833,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.corejava.java8.stream.terminal;
import java.util.Arrays;
import java.util.List;
/*
* Terminal Operation:
*
* forEach: The forEach method is used to iterate through every element of the stream.
*/
public class ForEach {
public static void main(String[] args) {
List<Integer> number = Arrays.asList(2,3,4,5);
number.forEach(System.out::print);
number.stream().map(x->x*x).forEach(System.out::println);
}
}
|
UTF-8
|
Java
| 440 |
java
|
ForEach.java
|
Java
|
[] | null |
[] |
package com.corejava.java8.stream.terminal;
import java.util.Arrays;
import java.util.List;
/*
* Terminal Operation:
*
* forEach: The forEach method is used to iterate through every element of the stream.
*/
public class ForEach {
public static void main(String[] args) {
List<Integer> number = Arrays.asList(2,3,4,5);
number.forEach(System.out::print);
number.stream().map(x->x*x).forEach(System.out::println);
}
}
| 440 | 0.702273 | 0.690909 | 22 | 19 | 23.479198 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.954545 | false | false |
13
|
d27a6fc091b7b42937a45624beef5a76278d74b9
| 2,164,663,553,857 |
9718adac8ce25d291e7f2d9ae8cdcee268792ccc
|
/data-cloud/data-cloud-updater-maven/src/main/java/com/unisound/dcs/dao/api/new_weather/fecther/current/MainNewCurrentWeatherFetcher.java
|
55a8a619e66cb4a7afbf97a0698f1c2fbd5ac3ac
|
[] |
no_license
|
694303720/gitlab
|
https://github.com/694303720/gitlab
|
e826ded7413ee1fa85e7068833a1aa874c4c729d
|
a89fb1bb9e8b814ca5d7602407f2e7260f23102c
|
refs/heads/master
| 2015-09-25T07:05:43.759000 | 2015-07-27T06:47:24 | 2015-07-27T06:47:24 | 39,758,212 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.unisound.dcs.dao.api.new_weather.fecther.current;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.PropertyConfigurator;
import com.unisound.dcs.dao.api.new_weather.IWeatherInfoFetcher;
import com.unisound.dcs.model.weather.AllWeatherInfo;
import com.unisound.dcs.model.weather.WeatherDay;
import com.unisound.dcs.util.PathUtil;
public class MainNewCurrentWeatherFetcher implements IWeatherInfoFetcher {
private List<IWeatherInfoFetcher> fetchers = new ArrayList<>();
private int timeOut = 3000;
private MainNewCurrentWeatherFetcher() {
fetchers.add(new ETouchCurrentWeatherFecher(timeOut));
fetchers.add(new XiaoMiCurrentWeatherFecher(timeOut));
fetchers.add(new Wu1wnlCurrentWeatherFecher(timeOut));
fetchers.add(new ForeignCurrentWeatherFecher(timeOut));
}
// 懒加载线程安全的单利模式
private static class SingletonHolder {
private static final MainNewCurrentWeatherFetcher INSTANCE = new MainNewCurrentWeatherFetcher();
}
public static MainNewCurrentWeatherFetcher getInstance() {
return SingletonHolder.INSTANCE;
}
@Override
public AllWeatherInfo fetch(String cityCode, String cityName) {
for (IWeatherInfoFetcher fetcher : fetchers) {
AllWeatherInfo allWeatherInfo = fetcher.fetch(cityCode, cityName);
if (allWeatherInfo != null)
return allWeatherInfo;
}
return null;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public List<IWeatherInfoFetcher> getFetchers() {
return fetchers;
}
public static void main(String[] args) {
PropertyConfigurator.configure(PathUtil.getWholePath("etc/log4j.properties"));
MainNewCurrentWeatherFetcher wthCurrentWeatherFecher = new MainNewCurrentWeatherFetcher();
// List<String> cityLines =
// TextFileReader.readLines(PathUtil.getWholePath("etc/nono_weather_city.txt"));
// for (String string : cityLines) {
// System.out.println(string);
// AllWeatherInfo allWeatherInfo =
// wthCurrentWeatherFecher.fetch(string.split("\t")[0],
// string.split("\t")[1]);
// System.out.println(allWeatherInfo.currentWeather);
// for (WeatherDay weatherDay :
// allWeatherInfo.weatherForcastInfo.getWeatherDays()) {
// System.out.println(weatherDay);
// }
// }
AllWeatherInfo allWeatherInfo = wthCurrentWeatherFecher.fetch("101340403", "彰化");
System.out.println(allWeatherInfo.currentWeather);
for (WeatherDay weatherDay : allWeatherInfo.weatherForcastInfo.getWeatherDays()) {
System.out.println(weatherDay);
}
}
}
|
UTF-8
|
Java
| 2,589 |
java
|
MainNewCurrentWeatherFetcher.java
|
Java
|
[] | null |
[] |
package com.unisound.dcs.dao.api.new_weather.fecther.current;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.PropertyConfigurator;
import com.unisound.dcs.dao.api.new_weather.IWeatherInfoFetcher;
import com.unisound.dcs.model.weather.AllWeatherInfo;
import com.unisound.dcs.model.weather.WeatherDay;
import com.unisound.dcs.util.PathUtil;
public class MainNewCurrentWeatherFetcher implements IWeatherInfoFetcher {
private List<IWeatherInfoFetcher> fetchers = new ArrayList<>();
private int timeOut = 3000;
private MainNewCurrentWeatherFetcher() {
fetchers.add(new ETouchCurrentWeatherFecher(timeOut));
fetchers.add(new XiaoMiCurrentWeatherFecher(timeOut));
fetchers.add(new Wu1wnlCurrentWeatherFecher(timeOut));
fetchers.add(new ForeignCurrentWeatherFecher(timeOut));
}
// 懒加载线程安全的单利模式
private static class SingletonHolder {
private static final MainNewCurrentWeatherFetcher INSTANCE = new MainNewCurrentWeatherFetcher();
}
public static MainNewCurrentWeatherFetcher getInstance() {
return SingletonHolder.INSTANCE;
}
@Override
public AllWeatherInfo fetch(String cityCode, String cityName) {
for (IWeatherInfoFetcher fetcher : fetchers) {
AllWeatherInfo allWeatherInfo = fetcher.fetch(cityCode, cityName);
if (allWeatherInfo != null)
return allWeatherInfo;
}
return null;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
public List<IWeatherInfoFetcher> getFetchers() {
return fetchers;
}
public static void main(String[] args) {
PropertyConfigurator.configure(PathUtil.getWholePath("etc/log4j.properties"));
MainNewCurrentWeatherFetcher wthCurrentWeatherFecher = new MainNewCurrentWeatherFetcher();
// List<String> cityLines =
// TextFileReader.readLines(PathUtil.getWholePath("etc/nono_weather_city.txt"));
// for (String string : cityLines) {
// System.out.println(string);
// AllWeatherInfo allWeatherInfo =
// wthCurrentWeatherFecher.fetch(string.split("\t")[0],
// string.split("\t")[1]);
// System.out.println(allWeatherInfo.currentWeather);
// for (WeatherDay weatherDay :
// allWeatherInfo.weatherForcastInfo.getWeatherDays()) {
// System.out.println(weatherDay);
// }
// }
AllWeatherInfo allWeatherInfo = wthCurrentWeatherFecher.fetch("101340403", "彰化");
System.out.println(allWeatherInfo.currentWeather);
for (WeatherDay weatherDay : allWeatherInfo.weatherForcastInfo.getWeatherDays()) {
System.out.println(weatherDay);
}
}
}
| 2,589 | 0.750098 | 0.743069 | 75 | 32.146667 | 27.651978 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.68 | false | false |
13
|
7d238abddc4c502c641ad9a48f49ee241b666a4a
| 27,384,711,519,207 |
16d82bb9a7627bcdb9ea0625cc3c7975e0789649
|
/app/src/main/java/ua/naiksoftware/examplesticky/model/Team.java
|
3f6a6caf4a78bd7761b896e2c8ca6ebb51cc87c8
|
[
"Apache-2.0"
] |
permissive
|
NaikSoftware/StickyHeadersAndroid
|
https://github.com/NaikSoftware/StickyHeadersAndroid
|
bf3ff554959d9cfe01a3e304136debc68116f337
|
a1ab25daa5dc52c5c7f0a0fc1d1089fdf6dc91ac
|
refs/heads/master
| 2021-01-12T14:08:33.977000 | 2016-10-02T11:51:23 | 2016-10-02T11:51:23 | 69,757,285 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ua.naiksoftware.examplesticky.model;
import android.support.annotation.DrawableRes;
import ua.naiksoftware.android.adapter.delegate.autobind.DrawableId;
import ua.naiksoftware.android.adapter.delegate.autobind.Text;
import ua.naiksoftware.android.model.BaseModel;
import ua.naiksoftware.android.model.Model;
import ua.naiksoftware.examplesticky.R;
import ua.naiksoftware.examplesticky.decorator.FirstLetterStickyHolder;
/**
* Created by naik on 01.10.16.
*/
public class Team implements BaseModel, FirstLetterStickyHolder.ModelWithName {
@Text(R.id.team_name)
private String name;
@DrawableId(R.id.team_avatar)
@DrawableRes
private int avatar;
private long id;
public Team(long id, String name, int avatar) {
this.id = id;
this.name = name;
this.avatar = avatar;
}
@Override
public long getId() {
return id;
}
@Override
public String getName() {
return name;
}
public int getAvatar() {
return avatar;
}
}
|
UTF-8
|
Java
| 1,038 |
java
|
Team.java
|
Java
|
[
{
"context": "orator.FirstLetterStickyHolder;\n\n/**\n * Created by naik on 01.10.16.\n */\n\npublic class Team implements Ba",
"end": 453,
"score": 0.9995994567871094,
"start": 449,
"tag": "USERNAME",
"value": "naik"
}
] | null |
[] |
package ua.naiksoftware.examplesticky.model;
import android.support.annotation.DrawableRes;
import ua.naiksoftware.android.adapter.delegate.autobind.DrawableId;
import ua.naiksoftware.android.adapter.delegate.autobind.Text;
import ua.naiksoftware.android.model.BaseModel;
import ua.naiksoftware.android.model.Model;
import ua.naiksoftware.examplesticky.R;
import ua.naiksoftware.examplesticky.decorator.FirstLetterStickyHolder;
/**
* Created by naik on 01.10.16.
*/
public class Team implements BaseModel, FirstLetterStickyHolder.ModelWithName {
@Text(R.id.team_name)
private String name;
@DrawableId(R.id.team_avatar)
@DrawableRes
private int avatar;
private long id;
public Team(long id, String name, int avatar) {
this.id = id;
this.name = name;
this.avatar = avatar;
}
@Override
public long getId() {
return id;
}
@Override
public String getName() {
return name;
}
public int getAvatar() {
return avatar;
}
}
| 1,038 | 0.699422 | 0.693642 | 46 | 21.565218 | 21.288548 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false |
13
|
61c845fe26e2c5fc70c41e3a1af07a6d253c61a4
| 25,615,184,988,065 |
85c855c3a2ec3924075cef496cc8eca3254b28bd
|
/openaz-xacml/src/main/java/org/apache/openaz/xacml/std/StdMutableResponse.java
|
743a1ab0b89943cb2cf3eb7102392bba0b339b4d
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
dash-/apache-openaz
|
https://github.com/dash-/apache-openaz
|
340da02d491c617e726b0aa96ae1b62180203c5b
|
7ffda51e6b17e8f25b5629dc0f65c8eea8d9df8b
|
refs/heads/master
| 2022-11-30T16:13:38.373000 | 2015-11-30T13:27:14 | 2015-11-30T13:27:14 | 47,570,303 | 0 | 1 |
Apache-2.0
| false | 2022-11-18T23:02:23 | 2015-12-07T18:12:25 | 2015-12-07T20:26:03 | 2022-11-18T23:02:22 | 98,528 | 0 | 1 | 2 |
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 org.apache.openaz.xacml.std;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.openaz.xacml.api.Response;
import org.apache.openaz.xacml.api.Result;
import org.apache.openaz.xacml.api.Status;
import org.apache.openaz.xacml.util.ListUtil;
/**
* Mutable implementation of the {@link org.apache.openaz.xacml.api.Response} interface.
*/
public class StdMutableResponse implements Response {
private static final List<Result> EMPTY_LIST = Collections.unmodifiableList(new ArrayList<Result>());
private List<Result> results;
/**
* Creates a new <code>StdMutableResponse</code> with no {@link org.apache.openaz.xacml.api.Result}s.
*/
public StdMutableResponse() {
this.results = EMPTY_LIST;
}
/**
* Creates a new <code>StdMutableResponse</code> with a single {@link org.apache.openaz.xacml.api.Result}.
*
* @param resultIn the <code>Result</code> for the new <code>StdMutableResponse</code>.
*/
public StdMutableResponse(Result resultIn) {
if (resultIn != null) {
this.results = new ArrayList<Result>();
this.results.add(resultIn);
} else {
this.results = EMPTY_LIST;
}
}
/**
* Creates a new <code>StdMutableResponse</code> with a copy of the {@link org.apache.openaz.xacml.api.Result}s in
* the given <code>Collection</code>>
*
* @param listResults the <code>Collection</code> of <code>Result</code>s for the new
* <code>StdMutableResponse</code>
*/
public StdMutableResponse(Collection<Result> listResults) {
if (listResults != null && listResults.size() > 0) {
this.results = new ArrayList<Result>();
this.results.addAll(listResults);
} else {
this.results = EMPTY_LIST;
}
}
/**
* Creates a new <code>StdMutableResponse</code> that is a copy of the given
* {@link org.apache.openaz.xacml.api.Response}.
*
* @param copy the <code>Response</code> to copy
*/
public StdMutableResponse(Response copy) {
this(copy.getResults());
}
/**
* Creates a new <code>StdMutableResponse</code> with a single {@link org.apache.openaz.xacml.api.Result}
* defined by the given {@link org.apache.openaz.xacml.api.Status}.
*
* @param status the <code>Status</code> of the <code>Result</code> for the new
* <code>StdMutableResponse</code>.
*/
public StdMutableResponse(Status status) {
this(new StdMutableResult(status));
}
@Override
public Collection<Result> getResults() {
return (this.results == EMPTY_LIST ? this.results : Collections.unmodifiableCollection(this.results));
}
/**
* Adds a {@link org.apache.openaz.xacml.api.Result} to this <code>StdMutableResponse</code>>
*
* @param result the <code>Result</code> to add
*/
public void add(Result result) {
if (this.results == EMPTY_LIST) {
this.results = new ArrayList<Result>();
}
this.results.add(result);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || !(obj instanceof Response)) {
return false;
} else {
Response objResponse = (Response)obj;
return ListUtil.equalsAllowNulls(this.getResults(), objResponse.getResults());
}
}
@Override
public int hashCode() {
int result = 17;
if (getResults() != null) {
result = 31 * result + getResults().hashCode();
}
return result;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("{");
Collection<Result> listResults = this.getResults();
if (listResults.size() > 0) {
stringBuilder.append("results=");
stringBuilder.append(ListUtil.toString(listResults));
}
stringBuilder.append('}');
return stringBuilder.toString();
}
}
|
UTF-8
|
Java
| 4,993 |
java
|
StdMutableResponse.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 org.apache.openaz.xacml.std;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.openaz.xacml.api.Response;
import org.apache.openaz.xacml.api.Result;
import org.apache.openaz.xacml.api.Status;
import org.apache.openaz.xacml.util.ListUtil;
/**
* Mutable implementation of the {@link org.apache.openaz.xacml.api.Response} interface.
*/
public class StdMutableResponse implements Response {
private static final List<Result> EMPTY_LIST = Collections.unmodifiableList(new ArrayList<Result>());
private List<Result> results;
/**
* Creates a new <code>StdMutableResponse</code> with no {@link org.apache.openaz.xacml.api.Result}s.
*/
public StdMutableResponse() {
this.results = EMPTY_LIST;
}
/**
* Creates a new <code>StdMutableResponse</code> with a single {@link org.apache.openaz.xacml.api.Result}.
*
* @param resultIn the <code>Result</code> for the new <code>StdMutableResponse</code>.
*/
public StdMutableResponse(Result resultIn) {
if (resultIn != null) {
this.results = new ArrayList<Result>();
this.results.add(resultIn);
} else {
this.results = EMPTY_LIST;
}
}
/**
* Creates a new <code>StdMutableResponse</code> with a copy of the {@link org.apache.openaz.xacml.api.Result}s in
* the given <code>Collection</code>>
*
* @param listResults the <code>Collection</code> of <code>Result</code>s for the new
* <code>StdMutableResponse</code>
*/
public StdMutableResponse(Collection<Result> listResults) {
if (listResults != null && listResults.size() > 0) {
this.results = new ArrayList<Result>();
this.results.addAll(listResults);
} else {
this.results = EMPTY_LIST;
}
}
/**
* Creates a new <code>StdMutableResponse</code> that is a copy of the given
* {@link org.apache.openaz.xacml.api.Response}.
*
* @param copy the <code>Response</code> to copy
*/
public StdMutableResponse(Response copy) {
this(copy.getResults());
}
/**
* Creates a new <code>StdMutableResponse</code> with a single {@link org.apache.openaz.xacml.api.Result}
* defined by the given {@link org.apache.openaz.xacml.api.Status}.
*
* @param status the <code>Status</code> of the <code>Result</code> for the new
* <code>StdMutableResponse</code>.
*/
public StdMutableResponse(Status status) {
this(new StdMutableResult(status));
}
@Override
public Collection<Result> getResults() {
return (this.results == EMPTY_LIST ? this.results : Collections.unmodifiableCollection(this.results));
}
/**
* Adds a {@link org.apache.openaz.xacml.api.Result} to this <code>StdMutableResponse</code>>
*
* @param result the <code>Result</code> to add
*/
public void add(Result result) {
if (this.results == EMPTY_LIST) {
this.results = new ArrayList<Result>();
}
this.results.add(result);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || !(obj instanceof Response)) {
return false;
} else {
Response objResponse = (Response)obj;
return ListUtil.equalsAllowNulls(this.getResults(), objResponse.getResults());
}
}
@Override
public int hashCode() {
int result = 17;
if (getResults() != null) {
result = 31 * result + getResults().hashCode();
}
return result;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("{");
Collection<Result> listResults = this.getResults();
if (listResults.size() > 0) {
stringBuilder.append("results=");
stringBuilder.append(ListUtil.toString(listResults));
}
stringBuilder.append('}');
return stringBuilder.toString();
}
}
| 4,993 | 0.636291 | 0.634288 | 149 | 32.510067 | 29.462891 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295302 | false | false |
13
|
3c9a222ed09bcab7d78963c8c335ff189ff95919
| 10,574,209,521,740 |
509dfb505ac765bec0ef2ecc905601507995640b
|
/src/main/java/com/sym/wscxfdemo/service/PersenSerivceImpl.java
|
e4a1e8f91aa00e0ecee72b23bcd26b469e0f1edd
|
[] |
no_license
|
suyiming3333/webserviceCXFdemo
|
https://github.com/suyiming3333/webserviceCXFdemo
|
9d25d2bb0af42fb1ae507a93140516bdff41c48f
|
17ad4d39b5a0920a08c3a548d47a6454d47b4e55
|
refs/heads/master
| 2020-04-14T16:39:00.675000 | 2019-01-04T15:25:35 | 2019-01-04T15:25:35 | 163,956,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.sym.wscxfdemo.service;
import com.sym.wscxfdemo.entity.Person;
public class PersenSerivceImpl implements PersonService {
@Override
public Person getPersonByName(String name) {
Person person = Person.builder()
.age(22)
.name(name)
.description("restful webservice")
.build();
return person;
}
@Override
public Person findPersonByName(String name) {
Person person = Person.builder()
.age(22)
.name(name)
.description("restful webservice")
.build();
return person; }
}
|
UTF-8
|
Java
| 664 |
java
|
PersenSerivceImpl.java
|
Java
|
[] | null |
[] |
package com.sym.wscxfdemo.service;
import com.sym.wscxfdemo.entity.Person;
public class PersenSerivceImpl implements PersonService {
@Override
public Person getPersonByName(String name) {
Person person = Person.builder()
.age(22)
.name(name)
.description("restful webservice")
.build();
return person;
}
@Override
public Person findPersonByName(String name) {
Person person = Person.builder()
.age(22)
.name(name)
.description("restful webservice")
.build();
return person; }
}
| 664 | 0.557229 | 0.551205 | 24 | 26.666666 | 17.322111 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
13
|
a2c49e60421f33f93831939098d3a268d032492d
| 32,693,291,088,468 |
4ed75cfad985239e10a4b4ac5dcbc4460e381c5c
|
/src/java/main/com/google/code/jdde/server/DdeServer.java
|
946c9f9d6298b33c593b86802ae0e73a6eb87da8
|
[
"Apache-2.0"
] |
permissive
|
xie790124/googlecode.jdde
|
https://github.com/xie790124/googlecode.jdde
|
51fdc8b20a8a16a030ef5c400cb82e1f3fce3eb8
|
1824a952961941d15fa7e9da94c8742eddb3f93b
|
refs/heads/master
| 2020-12-25T06:33:53.070000 | 2012-02-13T12:56:16 | 2012-02-13T12:56:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* Copyright 2008 Vitor Costa
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.code.jdde.server;
import com.google.code.jdde.ddeml.DdeAPI;
import com.google.code.jdde.ddeml.Pointer;
import com.google.code.jdde.ddeml.constants.DmlError;
import com.google.code.jdde.ddeml.constants.InitializeFlags;
import com.google.code.jdde.ddeml.constants.NameServiceFlags;
import com.google.code.jdde.misc.DdeApplication;
import com.google.code.jdde.server.event.ConnectionListener;
import com.google.code.jdde.server.event.ServerErrorListener;
import com.google.code.jdde.server.event.ServerRegistrationListener;
import com.google.code.jdde.server.event.TransactionListener;
/**
*
* @author Vitor Costa
*/
public class DdeServer extends DdeApplication {
private ConnectionListener connectionListener;
private TransactionListener transactionListener;
private ServerErrorListener errorListener;
private ServerRegistrationListener registrationListener;
public DdeServer() {
this(0);
}
public DdeServer(int initializeFlags) {
initialize(new ServerCallbackImpl(this),
InitializeFlags.APPCLASS_STANDARD |
InitializeFlags.APPCMD_FILTERINITS |
initializeFlags);
}
/* ************************************ *
********* getters and setters **********
* ************************************ */
public void setConnectionListener(ConnectionListener connectionListener) {
this.connectionListener = connectionListener;
}
public ConnectionListener getConnectionListener() {
return connectionListener;
}
public void setTransactionListener(TransactionListener transactionListener) {
this.transactionListener = transactionListener;
}
public TransactionListener getTransactionListener() {
return transactionListener;
}
public void setErrorListener(ServerErrorListener errorListener) {
this.errorListener = errorListener;
}
public ServerErrorListener getErrorListener() {
return errorListener;
}
public void setRegistrationListener(ServerRegistrationListener registrationListener) {
this.registrationListener = registrationListener;
}
public ServerRegistrationListener getRegistrationListener() {
return registrationListener;
}
/* ************************************ *
*********** ddeml api calls ************
* ************************************ */
public void registerService(String service) {
invokeNameService(service, NameServiceFlags.DNS_REGISTER);
}
public void unregisterService(String service) {
invokeNameService(service, NameServiceFlags.DNS_UNREGISTER);
}
public void unregisterAllServices() {
invokeNameService(null, NameServiceFlags.DNS_UNREGISTER);
}
public void turnServiceNameFilteringOn() {
invokeNameService(null, NameServiceFlags.DNS_FILTERON);
}
public void turnServiceNameFilteringOff() {
invokeNameService(null, NameServiceFlags.DNS_FILTEROFF);
}
private void invokeNameService(final String service, final int commands) {
final Pointer<Integer> error = new Pointer<Integer>();
loop.invokeAndWait(new Runnable() {
public void run() {
boolean succeded = DdeAPI.NameService(idInst, service, commands);
if (!succeded) {
error.value = DdeAPI.GetLastError(idInst);
}
}
});
DmlError.throwExceptionIfValidError(error.value);
}
public void postAdvise(final String topic, final String item) {
final Pointer<Integer> error = new Pointer<Integer>();
loop.invokeAndWait(new Runnable() {
public void run() {
boolean succeded = DdeAPI.PostAdvise(idInst, topic, item);
if (!succeded) {
error.value = DdeAPI.GetLastError(idInst);
}
}
});
DmlError.throwExceptionIfValidError(error.value);
}
/* ************************************ *
************ helper methods ************
* ************************************ */
@Override
protected ServerConversation findConversation(int conv) {
return (ServerConversation) super.findConversation(conv);
}
void addConversation(ServerConversation conversation) {
conversations.add(conversation);
}
}
|
UTF-8
|
Java
| 4,589 |
java
|
DdeServer.java
|
Java
|
[
{
"context": "/*\n * Copyright 2008 Vitor Costa\n * \n * Licensed under the Apache License, Version",
"end": 32,
"score": 0.9998651742935181,
"start": 21,
"tag": "NAME",
"value": "Vitor Costa"
},
{
"context": "ver.event.TransactionListener;\n\n/**\n * \n * @author Vitor Costa\n */\npublic class DdeServer extends DdeApplication",
"end": 1229,
"score": 0.9998217821121216,
"start": 1218,
"tag": "NAME",
"value": "Vitor Costa"
}
] | null |
[] |
/*
* Copyright 2008 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.code.jdde.server;
import com.google.code.jdde.ddeml.DdeAPI;
import com.google.code.jdde.ddeml.Pointer;
import com.google.code.jdde.ddeml.constants.DmlError;
import com.google.code.jdde.ddeml.constants.InitializeFlags;
import com.google.code.jdde.ddeml.constants.NameServiceFlags;
import com.google.code.jdde.misc.DdeApplication;
import com.google.code.jdde.server.event.ConnectionListener;
import com.google.code.jdde.server.event.ServerErrorListener;
import com.google.code.jdde.server.event.ServerRegistrationListener;
import com.google.code.jdde.server.event.TransactionListener;
/**
*
* @author <NAME>
*/
public class DdeServer extends DdeApplication {
private ConnectionListener connectionListener;
private TransactionListener transactionListener;
private ServerErrorListener errorListener;
private ServerRegistrationListener registrationListener;
public DdeServer() {
this(0);
}
public DdeServer(int initializeFlags) {
initialize(new ServerCallbackImpl(this),
InitializeFlags.APPCLASS_STANDARD |
InitializeFlags.APPCMD_FILTERINITS |
initializeFlags);
}
/* ************************************ *
********* getters and setters **********
* ************************************ */
public void setConnectionListener(ConnectionListener connectionListener) {
this.connectionListener = connectionListener;
}
public ConnectionListener getConnectionListener() {
return connectionListener;
}
public void setTransactionListener(TransactionListener transactionListener) {
this.transactionListener = transactionListener;
}
public TransactionListener getTransactionListener() {
return transactionListener;
}
public void setErrorListener(ServerErrorListener errorListener) {
this.errorListener = errorListener;
}
public ServerErrorListener getErrorListener() {
return errorListener;
}
public void setRegistrationListener(ServerRegistrationListener registrationListener) {
this.registrationListener = registrationListener;
}
public ServerRegistrationListener getRegistrationListener() {
return registrationListener;
}
/* ************************************ *
*********** ddeml api calls ************
* ************************************ */
public void registerService(String service) {
invokeNameService(service, NameServiceFlags.DNS_REGISTER);
}
public void unregisterService(String service) {
invokeNameService(service, NameServiceFlags.DNS_UNREGISTER);
}
public void unregisterAllServices() {
invokeNameService(null, NameServiceFlags.DNS_UNREGISTER);
}
public void turnServiceNameFilteringOn() {
invokeNameService(null, NameServiceFlags.DNS_FILTERON);
}
public void turnServiceNameFilteringOff() {
invokeNameService(null, NameServiceFlags.DNS_FILTEROFF);
}
private void invokeNameService(final String service, final int commands) {
final Pointer<Integer> error = new Pointer<Integer>();
loop.invokeAndWait(new Runnable() {
public void run() {
boolean succeded = DdeAPI.NameService(idInst, service, commands);
if (!succeded) {
error.value = DdeAPI.GetLastError(idInst);
}
}
});
DmlError.throwExceptionIfValidError(error.value);
}
public void postAdvise(final String topic, final String item) {
final Pointer<Integer> error = new Pointer<Integer>();
loop.invokeAndWait(new Runnable() {
public void run() {
boolean succeded = DdeAPI.PostAdvise(idInst, topic, item);
if (!succeded) {
error.value = DdeAPI.GetLastError(idInst);
}
}
});
DmlError.throwExceptionIfValidError(error.value);
}
/* ************************************ *
************ helper methods ************
* ************************************ */
@Override
protected ServerConversation findConversation(int conv) {
return (ServerConversation) super.findConversation(conv);
}
void addConversation(ServerConversation conversation) {
conversations.add(conversation);
}
}
| 4,579 | 0.713445 | 0.711484 | 157 | 28.2293 | 26.135822 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.656051 | false | false |
13
|
9c1061bafbcf0e4469f2bdc869fda6075a3a34be
| 33,492,155,015,005 |
5d40361f8c3e837bdd14b2bc233bd84d3edebb4c
|
/java/src/main/java/leetcode/TreeNode.java
|
418e50a75d393aaeaf3ce6fbf061d560c3f976f9
|
[] |
no_license
|
kaka2008/kaka2008
|
https://github.com/kaka2008/kaka2008
|
c7ee59a262b0c2a4fe2359de1596596bb27f96c3
|
c3ee0d622bb2bb49f0fa82e47bf78f97f9def49c
|
refs/heads/master
| 2017-12-05T17:25:23.646000 | 2017-06-06T13:59:10 | 2017-06-06T13:59:10 | 2,977,455 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package leetcode;
/**
* 二叉树
*
* @author weizhankui
*
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
@Override
public String toString() {
return printTree(this, new StringBuilder());
}
// 按照中序遍历方式输出二叉树
public String printTree(TreeNode tree, StringBuilder treeContent) {
if (tree == null) {
treeContent.append("null");
} else {
if (tree.left == null && tree.right == null) {
treeContent.append("" + tree.val);
} else {
printTree(tree.left, treeContent);
treeContent.append("" + tree.val);
printTree(tree.right, treeContent);
}
}
return treeContent.toString();
}
}
|
UTF-8
|
Java
| 705 |
java
|
TreeNode.java
|
Java
|
[
{
"context": "package leetcode;\n\n/**\n * 二叉树\n * \n * @author weizhankui\n *\n */\npublic class TreeNode {\n\tint val;\n\tTreeN",
"end": 53,
"score": 0.6003848314285278,
"start": 45,
"tag": "USERNAME",
"value": "weizhank"
},
{
"context": "kage leetcode;\n\n/**\n * 二叉树\n * \n * @author weizhankui\n *\n */\npublic class TreeNode {\n\tint val;\n\tTreeNod",
"end": 55,
"score": 0.5985642075538635,
"start": 53,
"tag": "NAME",
"value": "ui"
}
] | null |
[] |
package leetcode;
/**
* 二叉树
*
* @author weizhankui
*
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
@Override
public String toString() {
return printTree(this, new StringBuilder());
}
// 按照中序遍历方式输出二叉树
public String printTree(TreeNode tree, StringBuilder treeContent) {
if (tree == null) {
treeContent.append("null");
} else {
if (tree.left == null && tree.right == null) {
treeContent.append("" + tree.val);
} else {
printTree(tree.left, treeContent);
treeContent.append("" + tree.val);
printTree(tree.right, treeContent);
}
}
return treeContent.toString();
}
}
| 705 | 0.637444 | 0.637444 | 39 | 16.256411 | 16.595825 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.717949 | false | false |
13
|
c9307ac715bb9067eb66e17f0d77e664ecafa9ac
| 29,867,202,644,138 |
0dda3cc0a6c8046ac1e1691265e341eb35f2f300
|
/journeyArea/src/main/java/com/oneway/journeyarea/util/SensitiveInfo.java
|
51aff5bd6865b7cb4e753fd462b8274b278a45a8
|
[
"Apache-2.0"
] |
permissive
|
journeyArea/way
|
https://github.com/journeyArea/way
|
a19ab4c235e835e3a4c79f65d6bdf18bd93559c8
|
a8964d88fe22047329c6fba305900edbf664d96a
|
refs/heads/master
| 2018-12-21T00:32:09.831000 | 2018-12-19T07:53:58 | 2018-12-19T07:53:58 | 149,250,271 | 0 | 0 |
Apache-2.0
| false | 2018-09-18T08:27:44 | 2018-09-18T07:58:26 | 2018-09-18T08:21:35 | 2018-09-18T08:26:46 | 0 | 0 | 0 | 1 |
Java
| false | null |
package com.oneway.journeyarea.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Title: SensitiveInfo.java
* @Copyright: Copyright (c) 2015
* @Description: <br>
* 敏感信息注解标记 <br>
*/
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SensitiveInfo {
public SensitiveInfoUtils.SensitiveType type() ;
}
|
UTF-8
|
Java
| 638 |
java
|
SensitiveInfo.java
|
Java
|
[] | null |
[] |
package com.oneway.journeyarea.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Title: SensitiveInfo.java
* @Copyright: Copyright (c) 2015
* @Description: <br>
* 敏感信息注解标记 <br>
*/
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SensitiveInfo {
public SensitiveInfoUtils.SensitiveType type() ;
}
| 638 | 0.741158 | 0.734727 | 22 | 26.363636 | 16.397188 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false |
13
|
147f28ba6a8e2c90df4b46ec6aadaedcb1b6c70a
| 10,977,936,409,576 |
ccbd7ba87abcc7f461edad74548be2e40f701588
|
/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/temp/expressions/LogicalFilterExpression.java
|
1a0ffcc1ed34d13a24cf8acf39749b8e49c168ce
|
[
"Apache-2.0"
] |
permissive
|
lihuibng/fdb-record-layer
|
https://github.com/lihuibng/fdb-record-layer
|
62f43b2d2b43aa07d133e360ef5a1d4212163228
|
5c818e5a225dec8e342df770c59cf196915c5c10
|
refs/heads/main
| 2023-04-25T21:49:51.880000 | 2021-05-26T00:58:17 | 2021-05-26T00:58:17 | 373,023,472 | 1 | 0 |
Apache-2.0
| true | 2021-06-02T03:03:46 | 2021-06-02T03:03:45 | 2021-05-26T01:12:30 | 2021-05-26T01:12:28 | 9,397 | 0 | 0 | 0 | null | false | false |
/*
* LogicalFilterExpression.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.record.query.plan.temp.expressions;
import com.apple.foundationdb.annotation.API;
import com.apple.foundationdb.record.query.plan.temp.AliasMap;
import com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier;
import com.apple.foundationdb.record.query.plan.temp.Quantifier;
import com.apple.foundationdb.record.query.plan.temp.RelationalExpression;
import com.apple.foundationdb.record.query.plan.temp.RelationalExpressionWithPredicates;
import com.apple.foundationdb.record.query.plan.temp.explain.Attribute;
import com.apple.foundationdb.record.query.plan.temp.explain.NodeInfo;
import com.apple.foundationdb.record.query.plan.temp.explain.PlannerGraph;
import com.apple.foundationdb.record.query.plan.temp.explain.PlannerGraphRewritable;
import com.apple.foundationdb.record.query.predicates.AndPredicate;
import com.apple.foundationdb.record.query.predicates.QueryPredicate;
import com.apple.foundationdb.record.query.predicates.Value;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
/**
* A relational planner expression that represents an unimplemented filter on the records produced by its inner
* relational planner expression.
* @see com.apple.foundationdb.record.query.plan.plans.RecordQueryFilterPlan for the fallback implementation
*/
@API(API.Status.EXPERIMENTAL)
public class LogicalFilterExpression implements RelationalExpressionWithChildren, RelationalExpressionWithPredicates, PlannerGraphRewritable {
@Nonnull
private final List<QueryPredicate> queryPredicates;
@Nonnull
private final Quantifier inner;
@Nonnull
private final Supplier<List<? extends Value>> resultValuesSupplier;
public LogicalFilterExpression(@Nonnull Iterable<? extends QueryPredicate> queryPredicates,
@Nonnull Quantifier inner) {
this.queryPredicates = ImmutableList.copyOf(queryPredicates);
this.inner = inner;
this.resultValuesSupplier = Suppliers.memoize(inner::getFlowedValues);
}
@Nonnull
@Override
public List<? extends Quantifier> getQuantifiers() {
return ImmutableList.of(inner);
}
@Override
public int getRelationalChildCount() {
return 1;
}
@Nonnull
@Override
public List<QueryPredicate> getPredicates() {
return queryPredicates;
}
@Nonnull
@VisibleForTesting
public Quantifier getInner() {
return inner;
}
@Nonnull
@Override
public Set<CorrelationIdentifier> getCorrelatedToWithoutChildren() {
return queryPredicates.stream()
.flatMap(queryPredicate -> queryPredicate.getCorrelatedTo().stream())
.collect(ImmutableSet.toImmutableSet());
}
@Nonnull
@Override
public LogicalFilterExpression rebase(@Nonnull final AliasMap translationMap) {
// we know the following is correct, just Java doesn't
return (LogicalFilterExpression)RelationalExpressionWithChildren.super.rebase(translationMap);
}
@Nonnull
@Override
public LogicalFilterExpression rebaseWithRebasedQuantifiers(@Nonnull final AliasMap translationMap,
@Nonnull final List<Quantifier> rebasedQuantifiers) {
final ImmutableList<QueryPredicate> rebasedQueryPredicates =
queryPredicates.stream()
.map(queryPredicate -> queryPredicate.rebase(translationMap))
.collect(ImmutableList.toImmutableList());
return new LogicalFilterExpression(rebasedQueryPredicates,
Iterables.getOnlyElement(rebasedQuantifiers));
}
@Nonnull
@Override
public List<? extends Value> getResultValues() {
return resultValuesSupplier.get();
}
@SuppressWarnings("UnstableApiUsage")
@Override
public boolean equalsWithoutChildren(@Nonnull RelationalExpression otherExpression,
@Nonnull final AliasMap equivalencesMap) {
if (this == otherExpression) {
return true;
}
if (getClass() != otherExpression.getClass()) {
return false;
}
final LogicalFilterExpression otherLogicalFilterExpression = (LogicalFilterExpression)otherExpression;
final List<QueryPredicate> otherQueryPredicates = otherLogicalFilterExpression.getPredicates();
if (queryPredicates.size() != otherQueryPredicates.size()) {
return false;
}
return Streams.zip(queryPredicates.stream(), otherQueryPredicates.stream(),
(queryPredicate, otherQueryPredicate) -> queryPredicate.semanticEquals(otherQueryPredicate, equivalencesMap))
.allMatch(isSame -> isSame);
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object other) {
return semanticEquals(other);
}
@Override
public int hashCode() {
return semanticHashCode();
}
@Override
public int hashCodeWithoutChildren() {
return Objects.hash(getPredicates());
}
@Override
@Nonnull
public PlannerGraph rewritePlannerGraph(@Nonnull final List<? extends PlannerGraph> childGraphs) {
return PlannerGraph.fromNodeAndChildGraphs(
new PlannerGraph.LogicalOperatorNodeWithInfo(
this,
NodeInfo.PREDICATE_FILTER_OPERATOR,
ImmutableList.of("WHERE {{pred}}"),
ImmutableMap.of("pred", Attribute.gml(AndPredicate.and(getPredicates()).toString()))),
childGraphs);
}
}
|
UTF-8
|
Java
| 6,837 |
java
|
LogicalFilterExpression.java
|
Java
|
[] | null |
[] |
/*
* LogicalFilterExpression.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.record.query.plan.temp.expressions;
import com.apple.foundationdb.annotation.API;
import com.apple.foundationdb.record.query.plan.temp.AliasMap;
import com.apple.foundationdb.record.query.plan.temp.CorrelationIdentifier;
import com.apple.foundationdb.record.query.plan.temp.Quantifier;
import com.apple.foundationdb.record.query.plan.temp.RelationalExpression;
import com.apple.foundationdb.record.query.plan.temp.RelationalExpressionWithPredicates;
import com.apple.foundationdb.record.query.plan.temp.explain.Attribute;
import com.apple.foundationdb.record.query.plan.temp.explain.NodeInfo;
import com.apple.foundationdb.record.query.plan.temp.explain.PlannerGraph;
import com.apple.foundationdb.record.query.plan.temp.explain.PlannerGraphRewritable;
import com.apple.foundationdb.record.query.predicates.AndPredicate;
import com.apple.foundationdb.record.query.predicates.QueryPredicate;
import com.apple.foundationdb.record.query.predicates.Value;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
/**
* A relational planner expression that represents an unimplemented filter on the records produced by its inner
* relational planner expression.
* @see com.apple.foundationdb.record.query.plan.plans.RecordQueryFilterPlan for the fallback implementation
*/
@API(API.Status.EXPERIMENTAL)
public class LogicalFilterExpression implements RelationalExpressionWithChildren, RelationalExpressionWithPredicates, PlannerGraphRewritable {
@Nonnull
private final List<QueryPredicate> queryPredicates;
@Nonnull
private final Quantifier inner;
@Nonnull
private final Supplier<List<? extends Value>> resultValuesSupplier;
public LogicalFilterExpression(@Nonnull Iterable<? extends QueryPredicate> queryPredicates,
@Nonnull Quantifier inner) {
this.queryPredicates = ImmutableList.copyOf(queryPredicates);
this.inner = inner;
this.resultValuesSupplier = Suppliers.memoize(inner::getFlowedValues);
}
@Nonnull
@Override
public List<? extends Quantifier> getQuantifiers() {
return ImmutableList.of(inner);
}
@Override
public int getRelationalChildCount() {
return 1;
}
@Nonnull
@Override
public List<QueryPredicate> getPredicates() {
return queryPredicates;
}
@Nonnull
@VisibleForTesting
public Quantifier getInner() {
return inner;
}
@Nonnull
@Override
public Set<CorrelationIdentifier> getCorrelatedToWithoutChildren() {
return queryPredicates.stream()
.flatMap(queryPredicate -> queryPredicate.getCorrelatedTo().stream())
.collect(ImmutableSet.toImmutableSet());
}
@Nonnull
@Override
public LogicalFilterExpression rebase(@Nonnull final AliasMap translationMap) {
// we know the following is correct, just Java doesn't
return (LogicalFilterExpression)RelationalExpressionWithChildren.super.rebase(translationMap);
}
@Nonnull
@Override
public LogicalFilterExpression rebaseWithRebasedQuantifiers(@Nonnull final AliasMap translationMap,
@Nonnull final List<Quantifier> rebasedQuantifiers) {
final ImmutableList<QueryPredicate> rebasedQueryPredicates =
queryPredicates.stream()
.map(queryPredicate -> queryPredicate.rebase(translationMap))
.collect(ImmutableList.toImmutableList());
return new LogicalFilterExpression(rebasedQueryPredicates,
Iterables.getOnlyElement(rebasedQuantifiers));
}
@Nonnull
@Override
public List<? extends Value> getResultValues() {
return resultValuesSupplier.get();
}
@SuppressWarnings("UnstableApiUsage")
@Override
public boolean equalsWithoutChildren(@Nonnull RelationalExpression otherExpression,
@Nonnull final AliasMap equivalencesMap) {
if (this == otherExpression) {
return true;
}
if (getClass() != otherExpression.getClass()) {
return false;
}
final LogicalFilterExpression otherLogicalFilterExpression = (LogicalFilterExpression)otherExpression;
final List<QueryPredicate> otherQueryPredicates = otherLogicalFilterExpression.getPredicates();
if (queryPredicates.size() != otherQueryPredicates.size()) {
return false;
}
return Streams.zip(queryPredicates.stream(), otherQueryPredicates.stream(),
(queryPredicate, otherQueryPredicate) -> queryPredicate.semanticEquals(otherQueryPredicate, equivalencesMap))
.allMatch(isSame -> isSame);
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(Object other) {
return semanticEquals(other);
}
@Override
public int hashCode() {
return semanticHashCode();
}
@Override
public int hashCodeWithoutChildren() {
return Objects.hash(getPredicates());
}
@Override
@Nonnull
public PlannerGraph rewritePlannerGraph(@Nonnull final List<? extends PlannerGraph> childGraphs) {
return PlannerGraph.fromNodeAndChildGraphs(
new PlannerGraph.LogicalOperatorNodeWithInfo(
this,
NodeInfo.PREDICATE_FILTER_OPERATOR,
ImmutableList.of("WHERE {{pred}}"),
ImmutableMap.of("pred", Attribute.gml(AndPredicate.and(getPredicates()).toString()))),
childGraphs);
}
}
| 6,837 | 0.712447 | 0.710546 | 175 | 38.068573 | 33.056072 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411429 | false | false |
13
|
b8aef2d26992d8b224d21db5ccd3783f268ef77c
| 30,648,886,675,704 |
e46d1c71442d1ff726e8de034442096813790a74
|
/CISC181.Lab2/src/main/java/pokerBase/Hand.java
|
05ce6c5f3fa83b0a99c8424e7147f5a4df9138db
|
[] |
no_license
|
rleong/Lab2_Former1
|
https://github.com/rleong/Lab2_Former1
|
276eeb823058d218acd82e5e465bd4c8bb6a53f5
|
e0f124643b45ad38501efd88f008b1ad31286c93
|
refs/heads/master
| 2021-01-21T01:06:04.980000 | 2016-03-04T02:35:15 | 2016-03-04T02:35:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pokerBase;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Locale;
import pokerEnums.eHandStrength;
import static java.lang.System.out;
import static java.lang.System.err;
public class Hand {
private ArrayList<Card> CardsInHand;
private ArrayList<Card> BestCardsInHand;
private HandScore HandScore;
private boolean bScored = false;
private boolean Flush;
private boolean Straight;
private boolean Ace;
public Hand() {
}
}
|
UTF-8
|
Java
| 660 |
java
|
Hand.java
|
Java
|
[] | null |
[] |
package pokerBase;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Locale;
import pokerEnums.eHandStrength;
import static java.lang.System.out;
import static java.lang.System.err;
public class Hand {
private ArrayList<Card> CardsInHand;
private ArrayList<Card> BestCardsInHand;
private HandScore HandScore;
private boolean bScored = false;
private boolean Flush;
private boolean Straight;
private boolean Ace;
public Hand() {
}
}
| 660 | 0.75 | 0.75 | 32 | 18.625 | 15.400386 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.96875 | false | false |
13
|
63c6f31cc0d2726c02f95e4b2aa40ffe9472fdae
| 33,517,924,800,435 |
f514811a2d78d8cc95ce3d511638f0a336d96038
|
/main/src/java/枚举/enumTest.java
|
16cf02aea993912597484c6db687501472f42669
|
[] |
no_license
|
NobleYd/JavaIntroduction
|
https://github.com/NobleYd/JavaIntroduction
|
e42f46b07ff79da16157b246312187e064e5b9fa
|
21e231a69de3e11f03566ae500f12f08118e8ec0
|
refs/heads/master
| 2021-01-21T12:30:44.158000 | 2017-10-08T11:32:58 | 2017-10-08T11:32:58 | 102,075,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package 枚举;
public class enumTest {
enum gender {
male, female
}
public static void main(String[] args) {
gender g = gender.female;
System.out.println(g);
System.out.println(g instanceof Object);// true
System.out.println(g instanceof Enum);// true
// 可见,任何一个enum类型都是Enum的子类。
}
}
|
UTF-8
|
Java
| 361 |
java
|
enumTest.java
|
Java
|
[] | null |
[] |
package 枚举;
public class enumTest {
enum gender {
male, female
}
public static void main(String[] args) {
gender g = gender.female;
System.out.println(g);
System.out.println(g instanceof Object);// true
System.out.println(g instanceof Enum);// true
// 可见,任何一个enum类型都是Enum的子类。
}
}
| 361 | 0.633027 | 0.633027 | 22 | 12.863636 | 16.223707 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false |
13
|
3de502a18c7c6f2b00e17bbc23f6624c5a3b65dc
| 24,137,716,268,446 |
1c109b0620299d50ebeaf9b2256b32c353281eae
|
/src/sockets/Server.java
|
b8e62e4f351e37ac3db38bb7d9249fbbc59cac70
|
[] |
no_license
|
cindysanchez06/socketsJava
|
https://github.com/cindysanchez06/socketsJava
|
d512224e16ea3f707de0546f6ff06decd2d48437
|
cdcc22e0aceef75752d428f011770a82db9a092e
|
refs/heads/master
| 2023-08-04T15:51:33.079000 | 2021-09-21T05:40:41 | 2021-09-21T05:40:41 | 408,692,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sockets;
import sockets.Conexion;
import java.net.*;
import java.io.*;
public class Server extends Conexion //Se hereda de conexión para hacer uso de los sockets y demás
{
public Server() throws IOException{super("server");} //Se usa el constructor para servidor de Conexion
public void startServer()//Método para iniciar el servidor
{
try
{
System.out.println("Esperando..."); //Esperando conexión
cs = ss.accept(); //Accept comienza el socket y espera una conexión desde un cliente
System.out.println("Cliente en línea");
//Se obtiene el flujo de salida del cliente para enviarle mensajes
//salidaCliente = new DataOutputStream(cs.getOutputStream());
//Se le envía un mensaje al cliente usando su flujo de salida
//salidaCliente.writeUTF("Petición recibida y aceptada");
DataInputStream din = new DataInputStream(cs.getInputStream());
//Se obtiene el flujo entrante desde el cliente
//BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
mensajeServidor = "";
while(!mensajeServidor.equals("stop")) //Mientras haya mensajes desde el cliente
{
mensajeServidor = din.readUTF();
if(!mensajeServidor.equals("stop"))
{
System.out.println(mensajeServidor);
}
}
System.out.println("Fin de la conexión");
ss.close();//Se finaliza la conexión con el cliente
}
catch (Exception e)
{
System.out.println(e);
System.out.println(e.getMessage());
}
}
}
|
UTF-8
|
Java
| 1,762 |
java
|
Server.java
|
Java
|
[] | null |
[] |
package sockets;
import sockets.Conexion;
import java.net.*;
import java.io.*;
public class Server extends Conexion //Se hereda de conexión para hacer uso de los sockets y demás
{
public Server() throws IOException{super("server");} //Se usa el constructor para servidor de Conexion
public void startServer()//Método para iniciar el servidor
{
try
{
System.out.println("Esperando..."); //Esperando conexión
cs = ss.accept(); //Accept comienza el socket y espera una conexión desde un cliente
System.out.println("Cliente en línea");
//Se obtiene el flujo de salida del cliente para enviarle mensajes
//salidaCliente = new DataOutputStream(cs.getOutputStream());
//Se le envía un mensaje al cliente usando su flujo de salida
//salidaCliente.writeUTF("Petición recibida y aceptada");
DataInputStream din = new DataInputStream(cs.getInputStream());
//Se obtiene el flujo entrante desde el cliente
//BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
mensajeServidor = "";
while(!mensajeServidor.equals("stop")) //Mientras haya mensajes desde el cliente
{
mensajeServidor = din.readUTF();
if(!mensajeServidor.equals("stop"))
{
System.out.println(mensajeServidor);
}
}
System.out.println("Fin de la conexión");
ss.close();//Se finaliza la conexión con el cliente
}
catch (Exception e)
{
System.out.println(e);
System.out.println(e.getMessage());
}
}
}
| 1,762 | 0.599886 | 0.599886 | 51 | 33.35294 | 32.383621 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509804 | false | false |
13
|
7e1b45e61d043a84e4a6658f4551adae201c5c45
| 14,370,960,622,914 |
2d7fa3252c36074f47b1d1fe84c56b2f0844a840
|
/app/src/main/java/godaa/android/com/weathertaskapp/data/local/entity/AccuWeatherDb.java
|
cd0da04f0912d726d2f0ea9b768236c95081bcb1
|
[] |
no_license
|
gehadfatah/WeatherTaskMVVM
|
https://github.com/gehadfatah/WeatherTaskMVVM
|
0a2e79b3c2df1a7c8a8c5fc58e264f4124b60819
|
37a9fd424f799c94ee30f9795b36d94fd893a138
|
refs/heads/master
| 2020-06-09T23:10:56.019000 | 2019-07-27T02:56:22 | 2019-07-27T02:56:22 | 193,525,189 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package godaa.android.com.weathertaskapp.data.local.entity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.List;
import godaa.android.com.weathertaskapp.data.remote.model.AccuWeather5DayModel;
import godaa.android.com.weathertaskapp.data.remote.model.AccuWeatherModel;
@Entity(tableName = "weather")
public class AccuWeatherDb {
@PrimaryKey(autoGenerate = true)
@NonNull
private long id;
private String weatherText;
private String city;
private String keyLocation;
private String country;
private int weatherIcon;
private List<AccuWeather5DayModel.DailyForecast> dailyForecasts;
private double temperature;
@NonNull
public long getId() {
return id;
}
public String getWeatherText() {
return weatherText;
}
public void setWeatherText(String weatherText) {
this.weatherText = weatherText;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
public void setDailyForecasts(List<AccuWeather5DayModel.DailyForecast> dailyForecasts) {
this.dailyForecasts = dailyForecasts;
}
public void setCountry(String country) {
this.country = country;
}
public void setCity(String city) {
this.city = city;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public String getCity() {
return city;
}
public void setKeyLocation(String keyLocation) {
this.keyLocation = keyLocation;
}
public String getKeyLocation() {
return keyLocation;
}
public String getCountry() {
return country;
}
public int getWeatherIcon() {
return weatherIcon;
}
public double getTemperature() {
return temperature;
}
public List<AccuWeather5DayModel.DailyForecast> getDailyForecasts() {
return dailyForecasts;
}
public AccuWeatherDb() {
super();
}
public AccuWeatherDb(String weatherText, String city, String country, String keyLocation, int weatherIcon, List<AccuWeather5DayModel.DailyForecast> dailyForecasts, @Nullable double temperature) {
this.weatherText = weatherText;
this.city = city;
this.keyLocation = keyLocation;
this.country = country;
this.weatherIcon = weatherIcon;
this.dailyForecasts = dailyForecasts;
this.temperature = temperature;
}
public void setId(long id) {
this.id = id;
}
}
|
UTF-8
|
Java
| 2,639 |
java
|
AccuWeatherDb.java
|
Java
|
[] | null |
[] |
package godaa.android.com.weathertaskapp.data.local.entity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.List;
import godaa.android.com.weathertaskapp.data.remote.model.AccuWeather5DayModel;
import godaa.android.com.weathertaskapp.data.remote.model.AccuWeatherModel;
@Entity(tableName = "weather")
public class AccuWeatherDb {
@PrimaryKey(autoGenerate = true)
@NonNull
private long id;
private String weatherText;
private String city;
private String keyLocation;
private String country;
private int weatherIcon;
private List<AccuWeather5DayModel.DailyForecast> dailyForecasts;
private double temperature;
@NonNull
public long getId() {
return id;
}
public String getWeatherText() {
return weatherText;
}
public void setWeatherText(String weatherText) {
this.weatherText = weatherText;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
public void setDailyForecasts(List<AccuWeather5DayModel.DailyForecast> dailyForecasts) {
this.dailyForecasts = dailyForecasts;
}
public void setCountry(String country) {
this.country = country;
}
public void setCity(String city) {
this.city = city;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public String getCity() {
return city;
}
public void setKeyLocation(String keyLocation) {
this.keyLocation = keyLocation;
}
public String getKeyLocation() {
return keyLocation;
}
public String getCountry() {
return country;
}
public int getWeatherIcon() {
return weatherIcon;
}
public double getTemperature() {
return temperature;
}
public List<AccuWeather5DayModel.DailyForecast> getDailyForecasts() {
return dailyForecasts;
}
public AccuWeatherDb() {
super();
}
public AccuWeatherDb(String weatherText, String city, String country, String keyLocation, int weatherIcon, List<AccuWeather5DayModel.DailyForecast> dailyForecasts, @Nullable double temperature) {
this.weatherText = weatherText;
this.city = city;
this.keyLocation = keyLocation;
this.country = country;
this.weatherIcon = weatherIcon;
this.dailyForecasts = dailyForecasts;
this.temperature = temperature;
}
public void setId(long id) {
this.id = id;
}
}
| 2,639 | 0.679424 | 0.677529 | 116 | 21.75 | 26.37883 | 199 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396552 | false | false |
13
|
80748a97273f0530526a879b581ca27502121fa8
| 23,106,924,079,503 |
e63900f68c84bdd3ad600aff44ee948a35759e56
|
/Project6/src/p6_Package/TestClass.java
|
0b44a448aa80d9df2f9b4ac4044263843deffa4d
|
[] |
no_license
|
loganBehnke/CS249
|
https://github.com/loganBehnke/CS249
|
ed75dc6ad7afb98cfc91d7e03be127e767655786
|
35a4bda95171be2e3ace512a36b6d7a2b0934a71
|
refs/heads/master
| 2021-05-01T20:49:08.098000 | 2018-10-04T20:24:03 | 2018-10-04T20:24:03 | 120,965,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package p6_Package;
public class TestClass
{
public static void main(String[] args)
{
UtilityClass iterator = new UtilityClass(101);
iterator.iAdd(1);
iterator.iAdd(2);
iterator.iAdd(3);
System.out.println("Iterator Test: ");
System.out.println(iterator.iGetAtCurrent());
iterator.iMoveNext();
System.out.println(iterator.iGetAtCurrent());
iterator.iMoveNext();
System.out.println(iterator.iGetAtCurrent());
System.out.println();
iterator.iMovePrevious();
System.out.println(iterator.iGetAtCurrent());
iterator.iMovePrevious();
System.out.println(iterator.iGetAtCurrent());
System.out.println();
UtilityClass que = new UtilityClass(102);
que.qEnqueue(23);
que.qEnqueue(17);
que.qEnqueue(33);
System.out.println("Queue Test: ");
System.out.println(que.qDequeue());
System.out.println(que.qDequeue());
System.out.println(que.qDequeue());
System.out.println();
UtilityClass stack = new UtilityClass(103);
stack.sPush(11);
stack.sPush(22);
stack.sPush(33);
System.out.println("Stack Test: ");
System.out.println(stack.sPeek());
System.out.println(stack.sPop());
System.out.println(stack.sPop());
System.out.println(stack.sPop());
System.out.println();
}
}
|
UTF-8
|
Java
| 1,431 |
java
|
TestClass.java
|
Java
|
[] | null |
[] |
package p6_Package;
public class TestClass
{
public static void main(String[] args)
{
UtilityClass iterator = new UtilityClass(101);
iterator.iAdd(1);
iterator.iAdd(2);
iterator.iAdd(3);
System.out.println("Iterator Test: ");
System.out.println(iterator.iGetAtCurrent());
iterator.iMoveNext();
System.out.println(iterator.iGetAtCurrent());
iterator.iMoveNext();
System.out.println(iterator.iGetAtCurrent());
System.out.println();
iterator.iMovePrevious();
System.out.println(iterator.iGetAtCurrent());
iterator.iMovePrevious();
System.out.println(iterator.iGetAtCurrent());
System.out.println();
UtilityClass que = new UtilityClass(102);
que.qEnqueue(23);
que.qEnqueue(17);
que.qEnqueue(33);
System.out.println("Queue Test: ");
System.out.println(que.qDequeue());
System.out.println(que.qDequeue());
System.out.println(que.qDequeue());
System.out.println();
UtilityClass stack = new UtilityClass(103);
stack.sPush(11);
stack.sPush(22);
stack.sPush(33);
System.out.println("Stack Test: ");
System.out.println(stack.sPeek());
System.out.println(stack.sPop());
System.out.println(stack.sPop());
System.out.println(stack.sPop());
System.out.println();
}
}
| 1,431 | 0.608665 | 0.591195 | 51 | 26.058823 | 17.530268 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false |
13
|
84ffca400c1c82ff4adce94a11656902496eafe3
| 23,192,823,448,672 |
a02d278feb662d7c1d8343958ddf94c65baa54f5
|
/src/main/java/com/pavelfatin/typometer/statistics/Range.java
|
a959ebbc48d7fe671ba44c681ca5c091c9e9c507
|
[
"Apache-2.0"
] |
permissive
|
pavelfatin/typometer
|
https://github.com/pavelfatin/typometer
|
a3d2a5ef3e7294f8e0f897272d6b1cd0f98204a8
|
2084acfec845fdb3042f0155adffd88f14117c00
|
refs/heads/master
| 2021-01-10T05:30:35.188000 | 2017-09-22T11:27:45 | 2017-09-22T11:27:45 | 48,506,661 | 329 | 13 |
Apache-2.0
| false | 2020-09-28T07:10:45 | 2015-12-23T19:03:25 | 2020-09-26T04:21:04 | 2018-07-10T22:35:54 | 1,879 | 240 | 6 | 10 |
Java
| false | false |
/*
* Copyright 2017 Pavel Fatin, https://pavelfatin.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pavelfatin.typometer.statistics;
import java.util.ArrayList;
import java.util.Collection;
public class Range {
private double myMin;
private double myMax;
Range(double min, double max) {
myMin = min;
myMax = max;
}
public double getMin() {
return myMin;
}
public double getMax() {
return myMax;
}
public double getCenter() {
return 0.5D * (myMin + myMax);
}
public double getLength() {
return myMax - myMin;
}
Collection<Range> split(int count) {
Collection<Range> result = new ArrayList<>();
double step = getLength() / count;
double min = myMin;
for (int i = 0; i < count; i++) {
result.add(new Range(min, min + step));
min += step;
}
return result;
}
static Range of(Collection<Double> values) {
double min = values.stream().reduce(Double.MAX_VALUE, Math::min);
double max = values.stream().reduce(Double.MIN_VALUE, Math::max);
return new Range(min, max);
}
Range union(Range other) {
double min = Math.min(myMin, other.getMin());
double max = Math.max(myMax, other.getMax());
return new Range(min, max);
}
static Range union(Collection<Range> ranges) {
return ranges.stream().reduce((a, b) -> a.union(b))
.orElseThrow(() -> new IllegalArgumentException());
}
boolean contains(Double value) {
return myMin <= value && value < myMax;
}
}
|
UTF-8
|
Java
| 2,171 |
java
|
Range.java
|
Java
|
[
{
"context": "/*\n * Copyright 2017 Pavel Fatin, https://pavelfatin.com\n *\n * Licensed under the ",
"end": 32,
"score": 0.9998686909675598,
"start": 21,
"tag": "NAME",
"value": "Pavel Fatin"
}
] | null |
[] |
/*
* Copyright 2017 <NAME>, https://pavelfatin.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pavelfatin.typometer.statistics;
import java.util.ArrayList;
import java.util.Collection;
public class Range {
private double myMin;
private double myMax;
Range(double min, double max) {
myMin = min;
myMax = max;
}
public double getMin() {
return myMin;
}
public double getMax() {
return myMax;
}
public double getCenter() {
return 0.5D * (myMin + myMax);
}
public double getLength() {
return myMax - myMin;
}
Collection<Range> split(int count) {
Collection<Range> result = new ArrayList<>();
double step = getLength() / count;
double min = myMin;
for (int i = 0; i < count; i++) {
result.add(new Range(min, min + step));
min += step;
}
return result;
}
static Range of(Collection<Double> values) {
double min = values.stream().reduce(Double.MAX_VALUE, Math::min);
double max = values.stream().reduce(Double.MIN_VALUE, Math::max);
return new Range(min, max);
}
Range union(Range other) {
double min = Math.min(myMin, other.getMin());
double max = Math.max(myMax, other.getMax());
return new Range(min, max);
}
static Range union(Collection<Range> ranges) {
return ranges.stream().reduce((a, b) -> a.union(b))
.orElseThrow(() -> new IllegalArgumentException());
}
boolean contains(Double value) {
return myMin <= value && value < myMax;
}
}
| 2,166 | 0.61907 | 0.614003 | 81 | 25.802469 | 23.554728 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false |
13
|
9cef090c4093e0c717d37900f298a91ed6819fc8
| 19,748,259,660,868 |
3a46a2fb67f206c240985b4f757c1b7ff82aa18e
|
/ProtocolStackServer/src/yijiagou/tools/jdbctools/JDBCTools.java
|
c60585bc1bc78a9935a5a2f0d68a20363f7b6d95
|
[] |
no_license
|
1060783684/master1
|
https://github.com/1060783684/master1
|
b7fa5a5a072728a12f5e4857675f01a21b520a51
|
f022cf0325381bd2278e576c0d61e9052b60bf88
|
refs/heads/master
| 2021-01-22T13:23:59.309000 | 2017-09-24T15:20:41 | 2017-09-24T15:20:41 | 100,662,550 | 0 | 0 | null | false | 2017-08-30T01:50:03 | 2017-08-18T02:02:58 | 2017-08-18T05:03:12 | 2017-08-30T01:50:02 | 6,250 | 0 | 0 | 0 |
Java
| null | null |
package yijiagou.tools.jdbctools;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* Created by wangwei on 17-6-4.
*/
public class JDBCTools {
public static void release(Connection connection, Statement statement,ResultSet resultSet){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void release(Connection connection, Statement statement){
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection() throws Exception {
String clazz = null;
String url = null;
String user = null;
String password = null;
InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("JDBC.properties");
Properties properties = new Properties();
properties.load(in);
clazz = properties.getProperty("class");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(clazz);
Connection connection = DriverManager.getConnection(url,user,password);
return connection;
}
public static int updata(String sql,Object...args) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
int number = 0;
try {
connection = JDBCTools.getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
number = preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
release(connection,preparedStatement);
}
return number;
}
}
|
UTF-8
|
Java
| 2,676 |
java
|
JDBCTools.java
|
Java
|
[
{
"context": "*;\nimport java.util.Properties;\n\n/**\n * Created by wangwei on 17-6-4.\n */\npublic class JDBCTools {\n\n publ",
"end": 137,
"score": 0.9995381832122803,
"start": 130,
"tag": "USERNAME",
"value": "wangwei"
}
] | null |
[] |
package yijiagou.tools.jdbctools;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* Created by wangwei on 17-6-4.
*/
public class JDBCTools {
public static void release(Connection connection, Statement statement,ResultSet resultSet){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void release(Connection connection, Statement statement){
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Connection getConnection() throws Exception {
String clazz = null;
String url = null;
String user = null;
String password = null;
InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("JDBC.properties");
Properties properties = new Properties();
properties.load(in);
clazz = properties.getProperty("class");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(clazz);
Connection connection = DriverManager.getConnection(url,user,password);
return connection;
}
public static int updata(String sql,Object...args) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
int number = 0;
try {
connection = JDBCTools.getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
number = preparedStatement.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
release(connection,preparedStatement);
}
return number;
}
}
| 2,676 | 0.536996 | 0.53438 | 100 | 25.76 | 21.942707 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.48 | false | false |
13
|
2a580031a80b6edd79a2fc746facb31f07e78a79
| 18,588,618,486,117 |
ad1fea7e47b771424cadc63c93258bfb6005d1ba
|
/src/main/java/com/DDinside/desktop/servicce/DDinsideServiceImpl.java
|
6a3c5cd12b168c82e5f178444502f37fc9508859
|
[] |
no_license
|
plone93/DDinside_spring
|
https://github.com/plone93/DDinside_spring
|
566b9efb52fa7f683038dea45ee1484b206bf70d
|
44cb8f474729a87df63d8f53a79a632424f34243
|
refs/heads/master
| 2020-06-15T04:14:05.998000 | 2019-07-04T08:26:05 | 2019-07-04T08:26:05 | 195,200,655 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.DDinside.desktop.servicce;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.DDinside.desktop.domain.BoardVO;
import com.DDinside.desktop.domain.CommentVO;
import com.DDinside.desktop.domain.CountVO;
import com.DDinside.desktop.domain.SearchVO;
import com.DDinside.desktop.mapper.DDinsideMapper;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class DDinsideServiceImpl implements DDinsideService {
@Autowired
DDinsideMapper mapper;
@Override
public List<BoardVO> selectAllBoards(String board_id) {
return mapper.selectAllBoards(board_id);
}
@Override
public String selectUserId(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.selectUserId(map);
}
@Override
public BoardVO BoardView(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.BoardView(map);
}
@Override
public void updateReadCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.updateReadCount(map);
}
@Override
public void postUpCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postUpCount(map);
}
@Override
public void postDownCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postDownCount(map);
}
@Override
public void postAhoCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postAhoCount(map);
}
@Override
public void postReport(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postReport(map);
}
@Override
public int getReadCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.getReadCount(map);
}
@Override
public CountVO getPostCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
CountVO countVO = mapper.getPostCount(map);
return countVO;
}
@Override
public void boardDelete(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.boardDelete(map);
}
@Override
public List<BoardVO> selectAllBoard(int page, String board_id) {
int startNum = (page-1)*10+1;
int endNum = page*10;
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("board_id", board_id);
map.put("startNum", startNum);
map.put("endNum", endNum);
List<BoardVO> list = mapper.selectAllBoard(map);
return list;
}
@Override
public int tableCount(String board_id) {
return mapper.tableCount(board_id);
}
@Override
public int searchTableCount(SearchVO searchVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("searchVO", searchVO);
map.put("board_id", board_id);
return mapper.searchTableCount(map);
}
@Override
public int searchTableCountSuv(SearchVO searchVO, String word, String hotcount) {
return mapper.searchTableCountSuv(searchVO, word, hotcount);
}
@Override
public int searchTableCountTotal(SearchVO searchVO) {
return mapper.searchTableCountTotal(searchVO);
}
@Override
public List<BoardVO> selectNotice(String board_id) {
List<BoardVO> list = mapper.selectNotice(board_id);
return list;
}
@Override
public int insertComment(CommentVO commentVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentVO", commentVO);
map.put("board_id", board_id);
return mapper.insertComment(map);
}
@Override
public List<CommentVO> selectComment(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
List<CommentVO> list = mapper.selectComment(map);
return list;
}
@Override
public int commentCount(String board_num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("board_id", board_id);
map.put("board_num", board_num);
return mapper.commentCount(map);
}
@Override
public List<BoardVO> search(int page, SearchVO searchVO, String board_id) {
int startNum = (page-1)*10+1;
int endNum = page*10;
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("page", page);
map.put("searchVO", searchVO);
map.put("board_id", board_id);
map.put("startNum", startNum);
map.put("endNum", endNum);
return mapper.search(map);
}
@Override
public int searchTotalCount(SearchVO searchVO, String board_id) {
return mapper.searchTotalCount(searchVO, board_id);
}
@Override
public CommentVO commentView(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
CommentVO commentVO = mapper.commentView(map);
return commentVO;
}
@Override
public void updateComment(CommentVO commentVO, String board_id, String comment_num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentVO", commentVO);
map.put("board_id", board_id);
map.put("comment_num", comment_num);
mapper.updateComment(map);
}
@Override
public int commentDelete(String comment_num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("comment_num", comment_num);
map.put("board_id", board_id);
return mapper.commentDelete(map);
}
@Override
public void insertBoard(BoardVO boardVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("boardVO", boardVO);
map.put("board_id", board_id);
mapper.insertBoard(map);
}
@Override
public int updateBoard(BoardVO boardVO, String num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("boardVO", boardVO);
return mapper.updateBoard(map);
}
@Override
public List<BoardVO> mainNoticeBest() {
List<BoardVO> list = mapper.mainNoticeBest();
return list;
}
@Override
public List<BoardVO> mainNoticeWorst() {
List<BoardVO> list = mapper.mainNoticeWorst();
return list;
}
@Override
public List<BoardVO> mainNoticeAho() {
List<BoardVO> list = mapper.mainNoticeAho();
return list;
}
@Override
public void commentCountUpdate(int commentCount, String board_num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentCount", commentCount);
map.put("board_num", board_num);
mapper.commentCountUpdate(map);
}
}
|
UTF-8
|
Java
| 7,391 |
java
|
DDinsideServiceImpl.java
|
Java
|
[] | null |
[] |
package com.DDinside.desktop.servicce;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.DDinside.desktop.domain.BoardVO;
import com.DDinside.desktop.domain.CommentVO;
import com.DDinside.desktop.domain.CountVO;
import com.DDinside.desktop.domain.SearchVO;
import com.DDinside.desktop.mapper.DDinsideMapper;
import lombok.AllArgsConstructor;
@Service
@AllArgsConstructor
public class DDinsideServiceImpl implements DDinsideService {
@Autowired
DDinsideMapper mapper;
@Override
public List<BoardVO> selectAllBoards(String board_id) {
return mapper.selectAllBoards(board_id);
}
@Override
public String selectUserId(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.selectUserId(map);
}
@Override
public BoardVO BoardView(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.BoardView(map);
}
@Override
public void updateReadCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.updateReadCount(map);
}
@Override
public void postUpCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postUpCount(map);
}
@Override
public void postDownCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postDownCount(map);
}
@Override
public void postAhoCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postAhoCount(map);
}
@Override
public void postReport(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.postReport(map);
}
@Override
public int getReadCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
return mapper.getReadCount(map);
}
@Override
public CountVO getPostCount(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
CountVO countVO = mapper.getPostCount(map);
return countVO;
}
@Override
public void boardDelete(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
mapper.boardDelete(map);
}
@Override
public List<BoardVO> selectAllBoard(int page, String board_id) {
int startNum = (page-1)*10+1;
int endNum = page*10;
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("board_id", board_id);
map.put("startNum", startNum);
map.put("endNum", endNum);
List<BoardVO> list = mapper.selectAllBoard(map);
return list;
}
@Override
public int tableCount(String board_id) {
return mapper.tableCount(board_id);
}
@Override
public int searchTableCount(SearchVO searchVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("searchVO", searchVO);
map.put("board_id", board_id);
return mapper.searchTableCount(map);
}
@Override
public int searchTableCountSuv(SearchVO searchVO, String word, String hotcount) {
return mapper.searchTableCountSuv(searchVO, word, hotcount);
}
@Override
public int searchTableCountTotal(SearchVO searchVO) {
return mapper.searchTableCountTotal(searchVO);
}
@Override
public List<BoardVO> selectNotice(String board_id) {
List<BoardVO> list = mapper.selectNotice(board_id);
return list;
}
@Override
public int insertComment(CommentVO commentVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentVO", commentVO);
map.put("board_id", board_id);
return mapper.insertComment(map);
}
@Override
public List<CommentVO> selectComment(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
List<CommentVO> list = mapper.selectComment(map);
return list;
}
@Override
public int commentCount(String board_num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("board_id", board_id);
map.put("board_num", board_num);
return mapper.commentCount(map);
}
@Override
public List<BoardVO> search(int page, SearchVO searchVO, String board_id) {
int startNum = (page-1)*10+1;
int endNum = page*10;
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("page", page);
map.put("searchVO", searchVO);
map.put("board_id", board_id);
map.put("startNum", startNum);
map.put("endNum", endNum);
return mapper.search(map);
}
@Override
public int searchTotalCount(SearchVO searchVO, String board_id) {
return mapper.searchTotalCount(searchVO, board_id);
}
@Override
public CommentVO commentView(String num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("board_id", board_id);
CommentVO commentVO = mapper.commentView(map);
return commentVO;
}
@Override
public void updateComment(CommentVO commentVO, String board_id, String comment_num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentVO", commentVO);
map.put("board_id", board_id);
map.put("comment_num", comment_num);
mapper.updateComment(map);
}
@Override
public int commentDelete(String comment_num, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("comment_num", comment_num);
map.put("board_id", board_id);
return mapper.commentDelete(map);
}
@Override
public void insertBoard(BoardVO boardVO, String board_id) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("boardVO", boardVO);
map.put("board_id", board_id);
mapper.insertBoard(map);
}
@Override
public int updateBoard(BoardVO boardVO, String num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("num", num);
map.put("boardVO", boardVO);
return mapper.updateBoard(map);
}
@Override
public List<BoardVO> mainNoticeBest() {
List<BoardVO> list = mapper.mainNoticeBest();
return list;
}
@Override
public List<BoardVO> mainNoticeWorst() {
List<BoardVO> list = mapper.mainNoticeWorst();
return list;
}
@Override
public List<BoardVO> mainNoticeAho() {
List<BoardVO> list = mapper.mainNoticeAho();
return list;
}
@Override
public void commentCountUpdate(int commentCount, String board_num) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("commentCount", commentCount);
map.put("board_num", board_num);
mapper.commentCountUpdate(map);
}
}
| 7,391 | 0.705994 | 0.70437 | 289 | 24.574394 | 22.731367 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.16263 | false | false |
13
|
6e58465ecbe5b7aeaa25c776f9a65764b9b27b59
| 31,559,419,743,683 |
201e1afa22a4720b5f15f40b0a88a4d23df75a58
|
/model/src/main/java/ee/ut/solmir/act/model/WhileACT.java
|
c6346c024a59e6907ff8cd5429c8cad2bd0d04cb
|
[] |
no_license
|
karabut-viktor/mag
|
https://github.com/karabut-viktor/mag
|
377fe9d76f96a61cebafc8d9f21e00ee6a33e32b
|
0700886f088c25c23bafbfcb1e6f8318a03c752e
|
refs/heads/master
| 2020-12-24T15:58:40.877000 | 2015-12-22T00:03:40 | 2015-12-22T00:03:40 | 25,025,655 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ee.ut.solmir.act.model;
public interface WhileACT extends ACT{
ExprACT getCondition();
BlockACT getBody();
}
|
UTF-8
|
Java
| 128 |
java
|
WhileACT.java
|
Java
|
[] | null |
[] |
package ee.ut.solmir.act.model;
public interface WhileACT extends ACT{
ExprACT getCondition();
BlockACT getBody();
}
| 128 | 0.71875 | 0.71875 | 6 | 19.333334 | 14.31394 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
13
|
50c65ba5c327bfbe3fc51f52e61d7c818ceb65b1
| 16,183,436,833,942 |
efb7efbbd6baa5951748dfbe4139e18c0c3608be
|
/sources/com/bitcoin/mwallet/app/flows/onboarding/createuser/CreateUserView$bindDataObservers$3.java
|
b21f9c9afdc4e553b330a0b026e910e31eec36c2
|
[] |
no_license
|
blockparty-sh/600302-1_source_from_JADX
|
https://github.com/blockparty-sh/600302-1_source_from_JADX
|
08b757291e7c7a593d7ec20c7c47236311e12196
|
b443bbcde6def10895756b67752bb1834a12650d
|
refs/heads/master
| 2020-12-31T22:17:36.845000 | 2020-02-07T23:09:42 | 2020-02-07T23:09:42 | 239,038,650 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bitcoin.mwallet.app.flows.onboarding.createuser;
import android.view.View;
import android.widget.TextView;
import androidx.lifecycle.Observer;
import com.bitcoin.mwallet.C1018R;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
@Metadata(mo37403bv = {1, 0, 3}, mo37404d1 = {"\u0000\u0010\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u000b\n\u0002\b\u0003\u0010\u0000\u001a\u00020\u00012\u000e\u0010\u0002\u001a\n \u0004*\u0004\u0018\u00010\u00030\u0003H\n¢\u0006\u0004\b\u0005\u0010\u0006"}, mo37405d2 = {"<anonymous>", "", "shouldDisplay", "", "kotlin.jvm.PlatformType", "onChanged", "(Ljava/lang/Boolean;)V"}, mo37406k = 3, mo37407mv = {1, 1, 15})
/* compiled from: CreateUserView.kt */
final class CreateUserView$bindDataObservers$3<T> implements Observer<Boolean> {
final /* synthetic */ CreateUserView this$0;
CreateUserView$bindDataObservers$3(CreateUserView createUserView) {
this.this$0 = createUserView;
}
public final void onChanged(Boolean bool) {
Intrinsics.checkExpressionValueIsNotNull(bool, "shouldDisplay");
if (bool.booleanValue()) {
View view = this.this$0.getView();
if (view != null) {
TextView textView = (TextView) view.findViewById(C1018R.C1021id.loadingMessage);
if (textView != null) {
textView.setText(this.this$0.getText(C1018R.string.createuser_search_wallets_zion));
}
}
}
}
}
|
UTF-8
|
Java
| 1,497 |
java
|
CreateUserView$bindDataObservers$3.java
|
Java
|
[] | null |
[] |
package com.bitcoin.mwallet.app.flows.onboarding.createuser;
import android.view.View;
import android.widget.TextView;
import androidx.lifecycle.Observer;
import com.bitcoin.mwallet.C1018R;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
@Metadata(mo37403bv = {1, 0, 3}, mo37404d1 = {"\u0000\u0010\n\u0000\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u000b\n\u0002\b\u0003\u0010\u0000\u001a\u00020\u00012\u000e\u0010\u0002\u001a\n \u0004*\u0004\u0018\u00010\u00030\u0003H\n¢\u0006\u0004\b\u0005\u0010\u0006"}, mo37405d2 = {"<anonymous>", "", "shouldDisplay", "", "kotlin.jvm.PlatformType", "onChanged", "(Ljava/lang/Boolean;)V"}, mo37406k = 3, mo37407mv = {1, 1, 15})
/* compiled from: CreateUserView.kt */
final class CreateUserView$bindDataObservers$3<T> implements Observer<Boolean> {
final /* synthetic */ CreateUserView this$0;
CreateUserView$bindDataObservers$3(CreateUserView createUserView) {
this.this$0 = createUserView;
}
public final void onChanged(Boolean bool) {
Intrinsics.checkExpressionValueIsNotNull(bool, "shouldDisplay");
if (bool.booleanValue()) {
View view = this.this$0.getView();
if (view != null) {
TextView textView = (TextView) view.findViewById(C1018R.C1021id.loadingMessage);
if (textView != null) {
textView.setText(this.this$0.getText(C1018R.string.createuser_search_wallets_zion));
}
}
}
}
}
| 1,497 | 0.683155 | 0.559492 | 31 | 47.258064 | 74.511299 | 426 | false | false | 0 | 0 | 30 | 0.036096 | 0 | 0 | 0.935484 | false | false |
13
|
c9c954ef733d3d5371fd77702e1721ab1366353d
| 24,988,119,762,325 |
14f31b82e1b926f4fd02c60121180f83079268f5
|
/app/src/main/java/com/jarvis/foodcampus/presenter/favorite/FavoriteAdapter.java
|
f210bf49a98fa3a7f2a857f32eb4e519bd42c814
|
[] |
no_license
|
JunHoPark93/FoodCampus
|
https://github.com/JunHoPark93/FoodCampus
|
66bebc3732634fad79374faecdefd63398b8c832
|
33fcc09a88d09dcb1a61a8febb3767f51c8f634e
|
refs/heads/master
| 2021-01-11T05:20:34.069000 | 2018-11-19T12:00:33 | 2018-11-19T12:00:33 | 71,675,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.jarvis.foodcampus.presenter.favorite;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.jarvis.foodcampus.R;
import com.jarvis.foodcampus.model.FavoriteModel;
import java.util.ArrayList;
/**
* Created by JunHo on 2016-11-29.
*/
public class FavoriteAdapter extends BaseAdapter{
// Adapter에 추가된 데이터를 저장하기 위한 ArrayList
private ArrayList<FavoriteModel> listViewItemList = new ArrayList<FavoriteModel>();
// ListViewAdapter의 생성자
public FavoriteAdapter() {
}
// Adapter에 사용되는 데이터의 개수를 리턴 : 필수 구현
@Override
public int getCount() {
return listViewItemList.size();
}
// position에 위치한 데이터를 화면에 출력하는데 사용될 View를 리턴 : 필수 구현
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
// layout을 inflate하여 convertView 참조 획득
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.favorite_layout_onecol, parent, false);
}
// 화면에 표시될 View(Layout이 inflate된)으로부터 위젯에 대한 참조 획득
TextView titleTextView = (TextView) convertView.findViewById(R.id.favorite_name);
//listViewItemList에서 position에 위치한 데이터 참조 획득
FavoriteModel listViewItem = listViewItemList.get(position);
// 아이템 내 각 위젯에 데이터 반영
//iconImageView.setImageDrawable(listViewItem.getIconDrawable());
titleTextView.setText(String.valueOf(listViewItem.getRestaurantName()));
return convertView;
}
// 지정한 위치(position)에 있는 데이터와 관계된 아이템의 ID를 리턴 : 필수 구현
@Override
public long getItemId(int position) {
return position;
}
// 지정한 위치(position)에 있는 데이터 리턴 : 필수 구현
@Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
// 아이템 데이터 추가를 위한 함수
public void addItem(FavoriteModel model) {
/**
* 모델을 넘겨받아서 애드하자
*/
listViewItemList.add(model);
}
}
|
UTF-8
|
Java
| 2,642 |
java
|
FavoriteAdapter.java
|
Java
|
[
{
"context": "l;\n\nimport java.util.ArrayList;\n\n/**\n * Created by JunHo on 2016-11-29.\n */\n\npublic class FavoriteAdapter ",
"end": 379,
"score": 0.9983342885971069,
"start": 374,
"tag": "USERNAME",
"value": "JunHo"
}
] | null |
[] |
package com.jarvis.foodcampus.presenter.favorite;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.jarvis.foodcampus.R;
import com.jarvis.foodcampus.model.FavoriteModel;
import java.util.ArrayList;
/**
* Created by JunHo on 2016-11-29.
*/
public class FavoriteAdapter extends BaseAdapter{
// Adapter에 추가된 데이터를 저장하기 위한 ArrayList
private ArrayList<FavoriteModel> listViewItemList = new ArrayList<FavoriteModel>();
// ListViewAdapter의 생성자
public FavoriteAdapter() {
}
// Adapter에 사용되는 데이터의 개수를 리턴 : 필수 구현
@Override
public int getCount() {
return listViewItemList.size();
}
// position에 위치한 데이터를 화면에 출력하는데 사용될 View를 리턴 : 필수 구현
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
// layout을 inflate하여 convertView 참조 획득
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.favorite_layout_onecol, parent, false);
}
// 화면에 표시될 View(Layout이 inflate된)으로부터 위젯에 대한 참조 획득
TextView titleTextView = (TextView) convertView.findViewById(R.id.favorite_name);
//listViewItemList에서 position에 위치한 데이터 참조 획득
FavoriteModel listViewItem = listViewItemList.get(position);
// 아이템 내 각 위젯에 데이터 반영
//iconImageView.setImageDrawable(listViewItem.getIconDrawable());
titleTextView.setText(String.valueOf(listViewItem.getRestaurantName()));
return convertView;
}
// 지정한 위치(position)에 있는 데이터와 관계된 아이템의 ID를 리턴 : 필수 구현
@Override
public long getItemId(int position) {
return position;
}
// 지정한 위치(position)에 있는 데이터 리턴 : 필수 구현
@Override
public Object getItem(int position) {
return listViewItemList.get(position);
}
// 아이템 데이터 추가를 위한 함수
public void addItem(FavoriteModel model) {
/**
* 모델을 넘겨받아서 애드하자
*/
listViewItemList.add(model);
}
}
| 2,642 | 0.680739 | 0.677221 | 79 | 27.784811 | 26.451614 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35443 | false | false |
13
|
72cafee2cdb0cbb6057c1ccfa9d8ac707b449edf
| 6,932,077,235,884 |
b24e3d47a0fe51a9c4ca7c77b6e617321eca9b72
|
/src/base/DAOCliente.java
|
617eeec5da777bb1730d6573eaf458a38c55206c
|
[] |
no_license
|
lucianopulido/SNAKE-CLIENTE-SERVIDOR
|
https://github.com/lucianopulido/SNAKE-CLIENTE-SERVIDOR
|
152e608200b68f44f314d99b0d6d1302970d4c8c
|
ac4c079277cb15f763e0feb42015d62bc108ac2c
|
refs/heads/master
| 2020-04-08T12:49:02.161000 | 2018-11-28T22:54:43 | 2018-11-28T22:54:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package base;
import java.util.List;
import baseDeDatos.Persona;
public class DAOCliente extends DAO{
public DAOCliente() {
// this.c = conexion;
}
@Override
public List<Object[]> realizarLogin(Persona p) {
//c.logIn(p);
p.setNick("Nickk");
p.setIdPersona(1);
p.setColor("Azul");
return (List<Object[]>) p;
}
}
|
UTF-8
|
Java
| 338 |
java
|
DAOCliente.java
|
Java
|
[
{
"context": "arLogin(Persona p) {\n\t\t//c.logIn(p);\n\t\tp.setNick(\"Nickk\");\n\t\tp.setIdPersona(1);\n\t\tp.setColor(\"Azul\");\n\t\tr",
"end": 255,
"score": 0.881531298160553,
"start": 250,
"tag": "USERNAME",
"value": "Nickk"
}
] | null |
[] |
package base;
import java.util.List;
import baseDeDatos.Persona;
public class DAOCliente extends DAO{
public DAOCliente() {
// this.c = conexion;
}
@Override
public List<Object[]> realizarLogin(Persona p) {
//c.logIn(p);
p.setNick("Nickk");
p.setIdPersona(1);
p.setColor("Azul");
return (List<Object[]>) p;
}
}
| 338 | 0.656805 | 0.653846 | 23 | 13.695652 | 13.482468 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.26087 | false | false |
13
|
8931c182a0dd4050f95e20b62a741ea2f7f36e6b
| 1,666,447,365,038 |
9bc3c230785c7043825be89f70f259151c0108c1
|
/src/test/java/com/cbt/pages/TextBox.java
|
d15f734c2a396fe482110c9eb0ffcfd7a85bc1af
|
[] |
no_license
|
Nagihan-Karpuzcu/ToolsQa-1
|
https://github.com/Nagihan-Karpuzcu/ToolsQa-1
|
7210b8f53f4c279bc7c2b338a7b58e0fb10a8088
|
99d14a4b20cce05cebdb5a52ede6b4e42c489817
|
refs/heads/master
| 2022-12-25T12:13:27.452000 | 2020-10-01T15:50:50 | 2020-10-01T15:50:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.cbt.pages;
public class TextBox extends BasePage{
}
|
UTF-8
|
Java
| 67 |
java
|
TextBox.java
|
Java
|
[] | null |
[] |
package com.cbt.pages;
public class TextBox extends BasePage{
}
| 67 | 0.761194 | 0.761194 | 4 | 15.75 | 16.528385 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
13
|
47d4d828c31c9fa57252d1f629c9fb9690b41af1
| 32,349,693,717,550 |
041b673c9b18f24705fcebcbdc21f4f3c236487a
|
/app/src/main/java/com/homecaravan/android/consumer/model/EventDeleteSearch.java
|
9eb3147c9b26a68f81797eb7277edd4818496a72
|
[] |
no_license
|
Rainy1193/HCDemo
|
https://github.com/Rainy1193/HCDemo
|
63ed54d42e65cf17ba4873c424a7e5f27bc6519e
|
66498a0892e000f04aa30932b67106344a96ac8c
|
refs/heads/master
| 2021-09-04T20:08:27.932000 | 2018-01-22T01:55:26 | 2018-01-22T01:55:26 | 107,510,248 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.homecaravan.android.consumer.model;
public class EventDeleteSearch {
public String id;
public EventDeleteSearch(String id) {
this.id = id;
}
}
|
UTF-8
|
Java
| 177 |
java
|
EventDeleteSearch.java
|
Java
|
[] | null |
[] |
package com.homecaravan.android.consumer.model;
public class EventDeleteSearch {
public String id;
public EventDeleteSearch(String id) {
this.id = id;
}
}
| 177 | 0.689266 | 0.689266 | 9 | 18.666666 | 17.275545 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
13
|
e9be8c7b590b52da5dae6a9d3763bf0be3632a7c
| 38,079,180,051,797 |
b881a5baf3324e24de113c75b53b3f1a08e85914
|
/src/com/bj/jwt/MainActivity.java
|
a44aa81fc4ac96e2462d0f887f3ff1b0acab867e
|
[] |
no_license
|
yfyz/JWT
|
https://github.com/yfyz/JWT
|
d3597c5aa082c11b95caf4de712b248f3e568594
|
43dbbcad3cef1a3def0daee69db03c6977f83cd0
|
refs/heads/master
| 2021-09-03T13:15:33.274000 | 2018-01-09T09:42:56 | 2018-01-09T09:42:56 | 116,793,860 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bj.jwt;
import java.io.UnsupportedEncodingException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Debugging
private static final String TAG = "jwt";
private static final boolean D = true;
public boolean bFlagBluetoot=false;
public boolean bbluetootconn=false;
// Message types sent from the BluetoothService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
public static final int REQUEST_CONNECT_DEVICE = 1;
public static final int REQUEST_ENABLE_BT = 2;
// Name of the connected device
public String mConnectedDeviceName = null;
// String buffer for outgoing messages
public StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static BluetoothAdapter mBluetoothAdapter = null;
// Member object for the services
public static BluetoothService mService = null;
ImageButton btnlogin,btnpunish,btnquery;
TextView tvPoliceName,tvPoliceNum,tvPoliceTeam;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnpunish= (ImageButton)findViewById(R.id.allpunish);
tvPoliceNum=(TextView)findViewById(R.id.policenum);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
//finish();
//return;
bFlagBluetoot=false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mService != null) mService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
else {
if (mService == null)
mService = new BluetoothService(this, mHandler);;
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
bFlagBluetoot=true;
mService = new BluetoothService(this, mHandler);
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(MainActivity.this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
bFlagBluetoot=false;
finish();
}
}
}
// The Handler that gets information back from the BluetoothService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(MainActivity.this,R.string.title_connected_to, Toast.LENGTH_LONG).show();
//bbluetootconn=true;
break;
case BluetoothService.STATE_CONNECTING:
Toast.makeText(MainActivity.this,R.string.title_connecting, Toast.LENGTH_LONG).show();
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(MainActivity.this,R.string.title_not_connected, Toast.LENGTH_LONG).show();
// bbluetootconn=false;
break;
}
break;
case MESSAGE_WRITE:
//byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
//String writeMessage = new String(writeBuf);
break;
case MESSAGE_READ:
//byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
//String readMessage = new String(readBuf, 0, msg.arg1);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public static boolean sendprintinfo(String message)
{
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
// Toast.makeText(MainActivity.this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return false;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothService to write
byte[] send;
try{
send = message.getBytes("GB2312");
}
catch(UnsupportedEncodingException e)
{
send = message.getBytes();
}
mService.write(send);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.disconnect:
// disconnect
mService.stop();
return true;
}
return false;
//return super.onOptionsItemSelected(item);
}
/*登录*/
public void OnClickLogin(View v)
{
Intent intent=new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
//MainActivity.this.startActivity(intent);
}
/*执法*/
public void OnClickPunish(View v)
{
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
Toast.makeText(MainActivity.this, R.string.not_connected, Toast.LENGTH_SHORT).show();
// return ;
}
String spolicenum;
spolicenum=tvPoliceNum.getText().toString();
if(spolicenum.equals("00000"))
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("没有登录警员")
.setPositiveButton("确定", null)
.show();
return;
}
Intent intent = new Intent(MainActivity.this,AllpunishActivity.class);
startActivity(intent);
}
//查询
public void OnClickQuery(View v)
{
String spolicenum;
spolicenum=tvPoliceNum.getText().toString();
if(spolicenum.equals("00000"))
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("没有登录警员")
.setPositiveButton("确定", null)
.show();
return;
}
Intent intent = new Intent(MainActivity.this,AllQueryActivity.class);
startActivity(intent);
}
//核录
public void OnClickCheck(View v)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("暂无此功能")
.setPositiveButton("确定", null)
.show();
}
//日志
public void OnClickWorklog(View v)
{
Intent intent = new Intent(MainActivity.this,WorklogActivity.class);
startActivity(intent);
}
//工具
public void OnClickTool(View v)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("暂无此功能")
.setPositiveButton("确定", null)
.show();
}
//退出
public void OnClickLogout(View v)
{
AlertDialog dialog = new AlertDialog.Builder(
MainActivity.this)
.setTitle("提示")
.setMessage("是否退出移动警务?")
.setPositiveButton("返回", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
return;
}
})
.setNegativeButton("退出", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
MainActivity.this.finish();
}
}).create();
dialog.show();
}
}
|
GB18030
|
Java
| 12,286 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.bj.jwt;
import java.io.UnsupportedEncodingException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Debugging
private static final String TAG = "jwt";
private static final boolean D = true;
public boolean bFlagBluetoot=false;
public boolean bbluetootconn=false;
// Message types sent from the BluetoothService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
public static final int REQUEST_CONNECT_DEVICE = 1;
public static final int REQUEST_ENABLE_BT = 2;
// Name of the connected device
public String mConnectedDeviceName = null;
// String buffer for outgoing messages
public StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
public static BluetoothAdapter mBluetoothAdapter = null;
// Member object for the services
public static BluetoothService mService = null;
ImageButton btnlogin,btnpunish,btnquery;
TextView tvPoliceName,tvPoliceNum,tvPoliceTeam;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnpunish= (ImageButton)findViewById(R.id.allpunish);
tvPoliceNum=(TextView)findViewById(R.id.policenum);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
//finish();
//return;
bFlagBluetoot=false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mService != null) mService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
else {
if (mService == null)
mService = new BluetoothService(this, mHandler);;
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
bFlagBluetoot=true;
mService = new BluetoothService(this, mHandler);
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(MainActivity.this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
bFlagBluetoot=false;
finish();
}
}
}
// The Handler that gets information back from the BluetoothService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
Toast.makeText(MainActivity.this,R.string.title_connected_to, Toast.LENGTH_LONG).show();
//bbluetootconn=true;
break;
case BluetoothService.STATE_CONNECTING:
Toast.makeText(MainActivity.this,R.string.title_connecting, Toast.LENGTH_LONG).show();
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(MainActivity.this,R.string.title_not_connected, Toast.LENGTH_LONG).show();
// bbluetootconn=false;
break;
}
break;
case MESSAGE_WRITE:
//byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
//String writeMessage = new String(writeBuf);
break;
case MESSAGE_READ:
//byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
//String readMessage = new String(readBuf, 0, msg.arg1);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public static boolean sendprintinfo(String message)
{
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
// Toast.makeText(MainActivity.this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return false;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothService to write
byte[] send;
try{
send = message.getBytes("GB2312");
}
catch(UnsupportedEncodingException e)
{
send = message.getBytes();
}
mService.write(send);
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.disconnect:
// disconnect
mService.stop();
return true;
}
return false;
//return super.onOptionsItemSelected(item);
}
/*登录*/
public void OnClickLogin(View v)
{
Intent intent=new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
//MainActivity.this.startActivity(intent);
}
/*执法*/
public void OnClickPunish(View v)
{
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
Toast.makeText(MainActivity.this, R.string.not_connected, Toast.LENGTH_SHORT).show();
// return ;
}
String spolicenum;
spolicenum=tvPoliceNum.getText().toString();
if(spolicenum.equals("00000"))
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("没有登录警员")
.setPositiveButton("确定", null)
.show();
return;
}
Intent intent = new Intent(MainActivity.this,AllpunishActivity.class);
startActivity(intent);
}
//查询
public void OnClickQuery(View v)
{
String spolicenum;
spolicenum=tvPoliceNum.getText().toString();
if(spolicenum.equals("00000"))
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("没有登录警员")
.setPositiveButton("确定", null)
.show();
return;
}
Intent intent = new Intent(MainActivity.this,AllQueryActivity.class);
startActivity(intent);
}
//核录
public void OnClickCheck(View v)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("暂无此功能")
.setPositiveButton("确定", null)
.show();
}
//日志
public void OnClickWorklog(View v)
{
Intent intent = new Intent(MainActivity.this,WorklogActivity.class);
startActivity(intent);
}
//工具
public void OnClickTool(View v)
{
new AlertDialog.Builder(MainActivity.this)
.setTitle("标题")
.setMessage("暂无此功能")
.setPositiveButton("确定", null)
.show();
}
//退出
public void OnClickLogout(View v)
{
AlertDialog dialog = new AlertDialog.Builder(
MainActivity.this)
.setTitle("提示")
.setMessage("是否退出移动警务?")
.setPositiveButton("返回", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
return;
}
})
.setNegativeButton("退出", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
MainActivity.this.finish();
}
}).create();
dialog.show();
}
}
| 12,286 | 0.603769 | 0.601629 | 376 | 31.319149 | 24.719259 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.12766 | false | false |
15
|
31e89ebea288960f8ba3cce3a49872493353601d
| 24,378,234,405,758 |
b98ce703b1f31d44e56fc4c62091d1a8f2c04bcc
|
/app/src/main/java/com/zstudio/app/cinemovie/activity/AboutActivity.java
|
839689a4b7e027013570b6fdf0c4414cbc86c3c9
|
[
"MIT"
] |
permissive
|
karael/app-native-android
|
https://github.com/karael/app-native-android
|
c193eb5ed77e454ee3155218d87c4cfd9472c9ea
|
2f031a0893f4338d9b748ce0ad2d28a482d3b9db
|
refs/heads/master
| 2021-01-19T01:07:12.427000 | 2016-06-20T23:25:02 | 2016-06-20T23:25:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zstudio.app.cinemovie.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.zstudio.app.cinemovie.CineApplication;
import com.zstudio.app.cinemovie.R;
import com.zstudio.app.cinemovie.model.Movie;
import com.zstudio.app.cinemovie.network.NetworkManager;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AboutActivity extends AppCompatActivity {
private Activity activity = this;
private TextView tv;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
tv = (TextView) findViewById(R.id.textTester);
bt = (Button) findViewById(R.id.btTester);
List<Movie> movies = new ArrayList<>();
setTitle("test");
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
//pDialog.show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("coucou")
.setTitle("title");
final AlertDialog dialog = builder.create();
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshText(CineApplication.getSingleInstance().getAndroidId());
}
});
NetworkManager.getUserId("Test", new NetworkManager.JSONObjectResultListener() {
@Override
public void onResult(JSONObject result) {
pDialog.setMessage("Done");
pDialog.hide();
refreshText(result.toString());
}
@Override
public void onFail(String statusCode) {
pDialog.setMessage("Error: " + statusCode);
}
});
}
private void refreshText(String str) {
tv.append(CineApplication.getSingleInstance().getUserId());
}
}
|
UTF-8
|
Java
| 2,296 |
java
|
AboutActivity.java
|
Java
|
[] | null |
[] |
package com.zstudio.app.cinemovie.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.zstudio.app.cinemovie.CineApplication;
import com.zstudio.app.cinemovie.R;
import com.zstudio.app.cinemovie.model.Movie;
import com.zstudio.app.cinemovie.network.NetworkManager;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AboutActivity extends AppCompatActivity {
private Activity activity = this;
private TextView tv;
private Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
tv = (TextView) findViewById(R.id.textTester);
bt = (Button) findViewById(R.id.btTester);
List<Movie> movies = new ArrayList<>();
setTitle("test");
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
//pDialog.show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("coucou")
.setTitle("title");
final AlertDialog dialog = builder.create();
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshText(CineApplication.getSingleInstance().getAndroidId());
}
});
NetworkManager.getUserId("Test", new NetworkManager.JSONObjectResultListener() {
@Override
public void onResult(JSONObject result) {
pDialog.setMessage("Done");
pDialog.hide();
refreshText(result.toString());
}
@Override
public void onFail(String statusCode) {
pDialog.setMessage("Error: " + statusCode);
}
});
}
private void refreshText(String str) {
tv.append(CineApplication.getSingleInstance().getUserId());
}
}
| 2,296 | 0.66115 | 0.660279 | 75 | 29.613333 | 22.338543 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false |
15
|
6d08c2e7a5458dff491b2cafd45bcb8c8883b988
| 28,552,942,628,366 |
e6610868b7bb12f5eac5682e909c689ea84e2e48
|
/src/main/java/com/noviv/cleaner/filters/CleanerNet.java
|
e7b3f2b9bc2545bbf9e8c94c0037a2f3a8505a42
|
[] |
no_license
|
Noviv/Cleaner
|
https://github.com/Noviv/Cleaner
|
09512f3eb51372c9f75d54fddccd7a0988378235
|
dfb6a026083b8880efb349a635f1d43abbf1367e
|
refs/heads/master
| 2016-09-06T16:25:41.803000 | 2015-06-29T14:52:02 | 2015-06-29T14:52:02 | 37,796,284 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package main.java.com.noviv.cleaner.filters;
import java.io.File;
import java.util.ArrayList;
public class CleanerNet {
private ArrayList<CleanerFilter> filters;
public CleanerNet() {
filters = new ArrayList<>();
}
public void addFilter(CleanerFilter filter) {
filters.add(filter);
}
public boolean pass(File f) {
for (CleanerFilter filter : filters) {
if (!filter.pass(f)) {
return false;
}
}
return true;
}
}
|
UTF-8
|
Java
| 525 |
java
|
CleanerNet.java
|
Java
|
[] | null |
[] |
package main.java.com.noviv.cleaner.filters;
import java.io.File;
import java.util.ArrayList;
public class CleanerNet {
private ArrayList<CleanerFilter> filters;
public CleanerNet() {
filters = new ArrayList<>();
}
public void addFilter(CleanerFilter filter) {
filters.add(filter);
}
public boolean pass(File f) {
for (CleanerFilter filter : filters) {
if (!filter.pass(f)) {
return false;
}
}
return true;
}
}
| 525 | 0.584762 | 0.584762 | 26 | 19.192308 | 16.608662 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false |
15
|
c8ddadd5a07571835e4e11ac8df7ddb8d0af8ecb
| 22,857,815,995,433 |
377cfb2bb8e0a031f7357463035f3ee4f9354d5e
|
/.svn/pristine/38/3841035dc1aca470feaa78bb94a5061c82d358a9.svn-base
|
23769273448b2f886dfc9f83e6c6762064cc36c1
|
[] |
no_license
|
BinduBirol/XI-CLASS
|
https://github.com/BinduBirol/XI-CLASS
|
91a10f8221d2240dbe559d4c649ca2d6b8125aef
|
c059cfaf283332746c323c8f82b52b94d1c22229
|
refs/heads/main
| 2023-03-16T10:52:36.909000 | 2021-03-08T07:57:32 | 2021-03-08T07:57:32 | 345,574,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package edu.dto.college;
public class DashBoardCollegeDTO {
private int totalApplicant;
private int totalApplication;
private int webApplicant;
private int webApplication;
private int smsApplicant;
private int smsApplication;
public int getTotalApplicant() {
return totalApplicant;
}
public void setTotalApplicant(int totalApplicant) {
this.totalApplicant = totalApplicant;
}
public int getTotalApplication() {
return totalApplication;
}
public void setTotalApplication(int totalApplication) {
this.totalApplication = totalApplication;
}
public int getWebApplicant() {
return webApplicant;
}
public void setWebApplicant(int webApplicant) {
this.webApplicant = webApplicant;
}
public int getWebApplication() {
return webApplication;
}
public void setWebApplication(int webApplication) {
this.webApplication = webApplication;
}
public int getSmsApplicant() {
return smsApplicant;
}
public void setSmsApplicant(int smsApplicant) {
this.smsApplicant = smsApplicant;
}
public int getSmsApplication() {
return smsApplication;
}
public void setSmsApplication(int smsApplication) {
this.smsApplication = smsApplication;
}
}
|
UTF-8
|
Java
| 1,186 |
3841035dc1aca470feaa78bb94a5061c82d358a9.svn-base
|
Java
|
[] | null |
[] |
package edu.dto.college;
public class DashBoardCollegeDTO {
private int totalApplicant;
private int totalApplication;
private int webApplicant;
private int webApplication;
private int smsApplicant;
private int smsApplication;
public int getTotalApplicant() {
return totalApplicant;
}
public void setTotalApplicant(int totalApplicant) {
this.totalApplicant = totalApplicant;
}
public int getTotalApplication() {
return totalApplication;
}
public void setTotalApplication(int totalApplication) {
this.totalApplication = totalApplication;
}
public int getWebApplicant() {
return webApplicant;
}
public void setWebApplicant(int webApplicant) {
this.webApplicant = webApplicant;
}
public int getWebApplication() {
return webApplication;
}
public void setWebApplication(int webApplication) {
this.webApplication = webApplication;
}
public int getSmsApplicant() {
return smsApplicant;
}
public void setSmsApplicant(int smsApplicant) {
this.smsApplicant = smsApplicant;
}
public int getSmsApplication() {
return smsApplication;
}
public void setSmsApplication(int smsApplication) {
this.smsApplication = smsApplication;
}
}
| 1,186 | 0.768971 | 0.768971 | 54 | 20.962963 | 17.829401 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.481481 | false | false |
15
|
|
044cd50426c156e82b0daca8208b909fcafb2ecf
| 21,191,368,676,381 |
a9ab338031e01e50f88d3bb738d494e96ab508b4
|
/provider/provider-product-api/src/main/java/com/funtl/myshop/plus/provider/api/PmsFeightTemplateService.java
|
17867f7f0c1f8ffdbb062b4e08068452861ad331
|
[
"Apache-2.0"
] |
permissive
|
jiguang996/MyshopPlus
|
https://github.com/jiguang996/MyshopPlus
|
d809f5c71396193682f3709356b99eb14d3358ba
|
e70c826c979bc58065df366e793a4ed7b5578ae5
|
refs/heads/master
| 2020-09-21T01:38:31.590000 | 2020-07-23T06:51:32 | 2020-07-23T06:51:32 | 224,642,543 | 0 | 0 | null | false | 2019-12-13T17:33:50 | 2019-11-28T11:52:25 | 2019-11-28T13:41:18 | 2019-12-13T17:33:47 | 70,889 | 0 | 0 | 0 |
Java
| false | false |
package com.funtl.myshop.plus.provider.api;
public interface PmsFeightTemplateService {
}
|
UTF-8
|
Java
| 91 |
java
|
PmsFeightTemplateService.java
|
Java
|
[] | null |
[] |
package com.funtl.myshop.plus.provider.api;
public interface PmsFeightTemplateService {
}
| 91 | 0.824176 | 0.824176 | 4 | 21.75 | 21.252941 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false |
15
|
a7559a47bda68efe0bb3a19ba3bd1ed43d56e6fc
| 5,927,054,918,878 |
dbde38010aee32c5d04e58feca47c0d30abe34f5
|
/subprojects/opennaef.devicedriver.core/src/main/java/voss/discovery/iolib/DiscoveryTypeFactory.java
|
fe774019e7ddd5fb871a18bdef54b4c1009c07bb
|
[
"Apache-2.0"
] |
permissive
|
openNaEF/openNaEF
|
https://github.com/openNaEF/openNaEF
|
c2c8d5645b499aae36d90205dbc91421f4d0bd7b
|
c88f0e17adc8d3f266787846911787f9b8aa3b0d
|
refs/heads/master
| 2020-12-30T15:41:09.806000 | 2017-05-22T22:37:24 | 2017-05-22T22:38:36 | 91,155,672 | 13 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package voss.discovery.iolib;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import voss.discovery.agent.common.AgentConfiguration;
import voss.discovery.agent.mib.Mib2Impl;
import voss.discovery.iolib.snmp.SnmpAccess;
import java.io.IOException;
public class DiscoveryTypeFactory {
private static final Logger log = LoggerFactory.getLogger(DiscoveryTypeFactory.class);
public SupportedDiscoveryType getType(SnmpAccess snmp) throws IOException, UnknownTargetException {
if (snmp == null) {
throw new IllegalArgumentException();
}
String sysObjectID = getSysObjectId(snmp);
log.debug("getType():" + snmp.getSnmpAgentAddress().getAddress().getHostAddress()
+ ":" + sysObjectID);
String typeName = AgentConfiguration.getInstance().getAgentType(sysObjectID);
try {
return SupportedDiscoveryType.valueOf(typeName);
} catch (IllegalArgumentException e) {
return null;
}
}
private String getSysObjectId(SnmpAccess access) throws IOException {
try {
return Mib2Impl.getSysObjectId(access);
} catch (Exception e) {
log.error("unexpected error", e);
throw new IOException(e);
}
}
}
|
UTF-8
|
Java
| 1,283 |
java
|
DiscoveryTypeFactory.java
|
Java
|
[] | null |
[] |
package voss.discovery.iolib;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import voss.discovery.agent.common.AgentConfiguration;
import voss.discovery.agent.mib.Mib2Impl;
import voss.discovery.iolib.snmp.SnmpAccess;
import java.io.IOException;
public class DiscoveryTypeFactory {
private static final Logger log = LoggerFactory.getLogger(DiscoveryTypeFactory.class);
public SupportedDiscoveryType getType(SnmpAccess snmp) throws IOException, UnknownTargetException {
if (snmp == null) {
throw new IllegalArgumentException();
}
String sysObjectID = getSysObjectId(snmp);
log.debug("getType():" + snmp.getSnmpAgentAddress().getAddress().getHostAddress()
+ ":" + sysObjectID);
String typeName = AgentConfiguration.getInstance().getAgentType(sysObjectID);
try {
return SupportedDiscoveryType.valueOf(typeName);
} catch (IllegalArgumentException e) {
return null;
}
}
private String getSysObjectId(SnmpAccess access) throws IOException {
try {
return Mib2Impl.getSysObjectId(access);
} catch (Exception e) {
log.error("unexpected error", e);
throw new IOException(e);
}
}
}
| 1,283 | 0.67576 | 0.672642 | 38 | 32.789474 | 28.131418 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false |
15
|
0bdedbf99a76ca4c47c7a7b8a15a69d52f4f5dc7
| 24,086,176,638,932 |
5536e67b14dc95bd240e1d6ebb057a5c8fc5b1f0
|
/src/test/java/com/aliuge/context/support/nosql/redis/ShardedJedisMaxValueIncrementerTest.java
|
bbdc00eae34598a96df95a3d7dd317d3799a1efe
|
[
"Apache-2.0"
] |
permissive
|
liuzm/springdemo
|
https://github.com/liuzm/springdemo
|
b1bad6ccbd45152a9af1f337b1f8a2303f4710cd
|
e85bec97c1f3d26b0de60b6e838c85ee0943523e
|
refs/heads/springmvcAdminDemo
| 2016-03-07T03:07:56.424000 | 2015-05-05T05:53:56 | 2015-05-05T05:53:56 | 33,979,023 | 0 | 1 | null | false | 2016-03-09T05:59:42 | 2015-04-15T07:14:18 | 2015-05-05T05:53:59 | 2016-03-09T05:59:40 | 3,476 | 0 | 1 | 2 |
Java
| null | null |
package com.aliuge.context.support.nosql.redis;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.aliuge.jdbc.support.incrementer.ShardedJedisMaxValueIncrementer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/redis/applicationContext-service-redis.xml" })
public class ShardedJedisMaxValueIncrementerTest {
@Resource(name = "primaryKey1Incrementer1")
private ShardedJedisMaxValueIncrementer primaryKey1Incrementer1;
@Resource(name = "primaryKey1Incrementer2")
private ShardedJedisMaxValueIncrementer primaryKey1Incrementer2;
private final Logger logger = LoggerFactory.getLogger(ShardedJedisMaxValueIncrementerTest.class);
@Test
public void test() {
for (int i = 0; i < 100; i++) {
logger.info("{}", primaryKey1Incrementer1.nextLongValue());
}
for (int i = 0; i < 100; i++) {
logger.info("{}", primaryKey1Incrementer2.nextLongValue());
}
}
}
|
UTF-8
|
Java
| 1,162 |
java
|
ShardedJedisMaxValueIncrementerTest.java
|
Java
|
[] | null |
[] |
package com.aliuge.context.support.nosql.redis;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.aliuge.jdbc.support.incrementer.ShardedJedisMaxValueIncrementer;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/redis/applicationContext-service-redis.xml" })
public class ShardedJedisMaxValueIncrementerTest {
@Resource(name = "primaryKey1Incrementer1")
private ShardedJedisMaxValueIncrementer primaryKey1Incrementer1;
@Resource(name = "primaryKey1Incrementer2")
private ShardedJedisMaxValueIncrementer primaryKey1Incrementer2;
private final Logger logger = LoggerFactory.getLogger(ShardedJedisMaxValueIncrementerTest.class);
@Test
public void test() {
for (int i = 0; i < 100; i++) {
logger.info("{}", primaryKey1Incrementer1.nextLongValue());
}
for (int i = 0; i < 100; i++) {
logger.info("{}", primaryKey1Incrementer2.nextLongValue());
}
}
}
| 1,162 | 0.790878 | 0.769363 | 36 | 31.277779 | 29.186766 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.305556 | false | false |
15
|
4c39975e83f27b0dec340e84aa399d805d188836
| 8,701,603,785,587 |
d1edc13241cb658068939f9fce17a8ab07fbdbd5
|
/converter/src/fi/ni/ifc2x3/IfcStructuralLoadPlanarForce.java
|
63333f3009430a3bae0ecda2c62557d4edb1f8e8
|
[] |
no_license
|
lewismc/IFC-to-RDF-converter
|
https://github.com/lewismc/IFC-to-RDF-converter
|
c4e0d05822d018f75598434bbf820e27413dce77
|
efe5775417e92978c2032e15344fa8ec04277235
|
refs/heads/master
| 2020-12-25T02:50:06.051000 | 2013-02-09T08:59:22 | 2013-02-09T08:59:22 | 8,226,606 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package fi.ni.ifc2x3;
import fi.ni.ifc2x3.interfaces.*;
import fi.ni.*;
import java.util.*;
/*
* IFC Java class
* @author Jyrki Oraskari
* @license This work is licensed under a Creative Commons Attribution 3.0 Unported License.
* http://creativecommons.org/licenses/by/3.0/
*/
public class IfcStructuralLoadPlanarForce extends IfcStructuralLoadStatic
{
// The property attributes
Double planarForceX;
Double planarForceY;
Double planarForceZ;
// Getters and setters of properties
public Double getPlanarForceX() {
return planarForceX;
}
public void setPlanarForceX(String txt){
Double value = i.toDouble(txt);
this.planarForceX=value;
}
public Double getPlanarForceY() {
return planarForceY;
}
public void setPlanarForceY(String txt){
Double value = i.toDouble(txt);
this.planarForceY=value;
}
public Double getPlanarForceZ() {
return planarForceZ;
}
public void setPlanarForceZ(String txt){
Double value = i.toDouble(txt);
this.planarForceZ=value;
}
}
|
UTF-8
|
Java
| 1,016 |
java
|
IfcStructuralLoadPlanarForce.java
|
Java
|
[
{
"context": "port java.util.*;\n\n/*\n * IFC Java class\n * @author Jyrki Oraskari\n * @license This work is licensed under a Creativ",
"end": 139,
"score": 0.9998363852500916,
"start": 125,
"tag": "NAME",
"value": "Jyrki Oraskari"
}
] | null |
[] |
package fi.ni.ifc2x3;
import fi.ni.ifc2x3.interfaces.*;
import fi.ni.*;
import java.util.*;
/*
* IFC Java class
* @author <NAME>
* @license This work is licensed under a Creative Commons Attribution 3.0 Unported License.
* http://creativecommons.org/licenses/by/3.0/
*/
public class IfcStructuralLoadPlanarForce extends IfcStructuralLoadStatic
{
// The property attributes
Double planarForceX;
Double planarForceY;
Double planarForceZ;
// Getters and setters of properties
public Double getPlanarForceX() {
return planarForceX;
}
public void setPlanarForceX(String txt){
Double value = i.toDouble(txt);
this.planarForceX=value;
}
public Double getPlanarForceY() {
return planarForceY;
}
public void setPlanarForceY(String txt){
Double value = i.toDouble(txt);
this.planarForceY=value;
}
public Double getPlanarForceZ() {
return planarForceZ;
}
public void setPlanarForceZ(String txt){
Double value = i.toDouble(txt);
this.planarForceZ=value;
}
}
| 1,008 | 0.73622 | 0.728346 | 50 | 19.32 | 19.863977 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32 | false | false |
15
|
d41ef033b18ece7a23be321bf3528025a2eab6e1
| 32,667,521,294,576 |
c0e0b87fe65c2e0a86fd1768c4e26a5c15b1a167
|
/src/main/java/com/revature/servlet/HotelServlet.java
|
52ff8ea62a885d17cd7416058d26c7561594f15e
|
[] |
no_license
|
timtouch/hotel-reservation-app
|
https://github.com/timtouch/hotel-reservation-app
|
9bb90bfb234c1f03f272a0d63a8b16c79f5c4715
|
d0d8de8a9bf10af8a4ac1044fc2f55cb09519e17
|
refs/heads/master
| 2022-11-25T04:30:55.451000 | 2020-06-18T19:40:00 | 2020-06-18T19:40:00 | 142,476,478 | 0 | 0 | null | false | 2022-11-15T23:48:37 | 2018-07-26T18:03:55 | 2020-06-18T19:40:05 | 2022-11-15T23:48:33 | 80 | 0 | 0 | 2 |
Java
| false | false |
package com.revature.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.dao.HotelDao;
import com.revature.model.Host;
import com.revature.model.Hotel;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/api/v1/hotels")
public class HotelServlet extends HttpServlet
{
private HotelDao hotelDao = new HotelDao();
// GET /hotels
// GET /hotels?{id}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
List<Hotel> hotels;
Hotel hotel;
ObjectMapper mapper = new ObjectMapper();
resp.setContentType("application/json");
if(req.getParameterMap().containsKey("id")){
mapper.writeValue(resp.getOutputStream(), hotelDao.getHotelById(Integer.parseInt(req.getParameter("id"))));
} else {
mapper.writeValue(resp.getOutputStream(), hotelDao.getAllHotels());
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
Hotel insertHotel;
ObjectMapper mapper = new ObjectMapper();
insertHotel = mapper.readValue(req.getInputStream(), Hotel.class);
if (!insertHotel.getName().isEmpty()){
hotelDao.insertHotel(insertHotel);
} else {
resp.getWriter().println("Hotel needs a name");
}
}
}
|
UTF-8
|
Java
| 1,667 |
java
|
HotelServlet.java
|
Java
|
[] | null |
[] |
package com.revature.servlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.dao.HotelDao;
import com.revature.model.Host;
import com.revature.model.Hotel;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/api/v1/hotels")
public class HotelServlet extends HttpServlet
{
private HotelDao hotelDao = new HotelDao();
// GET /hotels
// GET /hotels?{id}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
List<Hotel> hotels;
Hotel hotel;
ObjectMapper mapper = new ObjectMapper();
resp.setContentType("application/json");
if(req.getParameterMap().containsKey("id")){
mapper.writeValue(resp.getOutputStream(), hotelDao.getHotelById(Integer.parseInt(req.getParameter("id"))));
} else {
mapper.writeValue(resp.getOutputStream(), hotelDao.getAllHotels());
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
Hotel insertHotel;
ObjectMapper mapper = new ObjectMapper();
insertHotel = mapper.readValue(req.getInputStream(), Hotel.class);
if (!insertHotel.getName().isEmpty()){
hotelDao.insertHotel(insertHotel);
} else {
resp.getWriter().println("Hotel needs a name");
}
}
}
| 1,667 | 0.70126 | 0.70066 | 55 | 29.309092 | 29.068491 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.563636 | false | false |
15
|
3290cf0326e21aaa1738b3e805fe3c007975b74c
| 11,922,829,261,607 |
84f2682397a30fad16440810e695da8ce6a99def
|
/1. back-end/restapi/src/main/java/sequence/restapi/mapper/MemberMapper.java
|
cd1b197ab7dd6e6a61e2ff8ee93cc452b6ede0ca
|
[] |
no_license
|
JunilHwang/task-management
|
https://github.com/JunilHwang/task-management
|
fb1ea9cf83152e56dc9749bade5b4abfda2afcd7
|
8cdf9114b92a5c3e3ab80c7beef2395fdaa61580
|
refs/heads/master
| 2020-04-09T07:22:17.635000 | 2018-11-28T01:27:48 | 2018-11-28T01:27:48 | 160,152,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sequence.restapi.mapper;
import java.util.HashMap;
import java.util.List;
public interface MemberMapper {
// email과 일치하는 회원 정보의 갯수 가져오기
int getMemberCount(String email);
// id와 동일한 회원 정보 가져오기
HashMap getMember(String id);
// project에 참여중인 member 가져오기
List getMemberOnProject(int pidx);
// 회원 등록하기
void postMember(HashMap data);
// 구글 토큰 업데이트
void putMemberGoogleToken(HashMap data);
}
|
UTF-8
|
Java
| 542 |
java
|
MemberMapper.java
|
Java
|
[] | null |
[] |
package sequence.restapi.mapper;
import java.util.HashMap;
import java.util.List;
public interface MemberMapper {
// email과 일치하는 회원 정보의 갯수 가져오기
int getMemberCount(String email);
// id와 동일한 회원 정보 가져오기
HashMap getMember(String id);
// project에 참여중인 member 가져오기
List getMemberOnProject(int pidx);
// 회원 등록하기
void postMember(HashMap data);
// 구글 토큰 업데이트
void putMemberGoogleToken(HashMap data);
}
| 542 | 0.695455 | 0.695455 | 22 | 19 | 15.623409 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false |
15
|
45d40b357738d18fc1e459c2bdea91a5c2438c7b
| 1,503,238,621,487 |
40fb7eb9785d205ff9f8013cc79178e4680315e1
|
/src/main/java/com/hs/structure/stack/Stack.java
|
86edcbdfc13fd1fc2fc3cd71f96a5640c353cf65
|
[] |
no_license
|
HeShuai-GitHub/DataStructure
|
https://github.com/HeShuai-GitHub/DataStructure
|
47bf78aa12a9b5b28cb58f3881993636e0f8280b
|
383bdadd723077e1894397e4687fe61e25945238
|
refs/heads/master
| 2023-06-28T19:49:03.190000 | 2021-08-03T01:33:35 | 2021-08-03T01:33:35 | 391,344,086 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hs.structure.stack;
/**
* @author heshuai
* @title: Stack
* @description: 栈抽象方法
* @date 2021年08月02日 19:55
*/
public interface Stack {
/**
* 清空栈
*/
public void clearStack();
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty();
/**
* 获得栈顶元素
* @return
*/
public int getTop();
/**
* 将元素压栈
* @param e
*/
public void push(int e);
/**
* 将栈顶元素返回并且删除
* @return
*/
public int pop();
/**
* 返回栈的长度
* @return
*/
public int length();
}
|
UTF-8
|
Java
| 671 |
java
|
Stack.java
|
Java
|
[
{
"context": "package com.hs.structure.stack;\n\n/**\n * @author heshuai\n * @title: Stack\n * @description: 栈抽象方法\n * @date ",
"end": 55,
"score": 0.9989613890647888,
"start": 48,
"tag": "USERNAME",
"value": "heshuai"
}
] | null |
[] |
package com.hs.structure.stack;
/**
* @author heshuai
* @title: Stack
* @description: 栈抽象方法
* @date 2021年08月02日 19:55
*/
public interface Stack {
/**
* 清空栈
*/
public void clearStack();
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty();
/**
* 获得栈顶元素
* @return
*/
public int getTop();
/**
* 将元素压栈
* @param e
*/
public void push(int e);
/**
* 将栈顶元素返回并且删除
* @return
*/
public int pop();
/**
* 返回栈的长度
* @return
*/
public int length();
}
| 671 | 0.469775 | 0.44905 | 45 | 11.866667 | 9.088698 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.155556 | false | false |
15
|
04fa7604b960879bf1ae600cdd9bcf12fb580081
| 20,040,317,445,962 |
57c5fda43b0c2f99c2ec78e389795955247cd244
|
/cobia-core/src/main/java/lam/cobia/cluster/AbstractCluster.java
|
25ffbf2e693b612e341c43ece027fcc17b8d40cc
|
[] |
no_license
|
jjavaboy/cobia
|
https://github.com/jjavaboy/cobia
|
3724909a98c91ff4c944281f91c5d4cecc279b24
|
429ca66e74c38261368946cc313408ca68966653
|
refs/heads/master
| 2020-03-26T01:46:13.118000 | 2018-08-11T09:48:30 | 2018-08-11T09:48:30 | 115,119,845 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lam.cobia.cluster;
import lam.cobia.loadbalance.LoadBalance;
import lam.cobia.rpc.Consumer;
import lam.cobia.rpc.Invocation;
import lam.cobia.rpc.Result;
import java.util.List;
/**
* @description: AbstractCluster
* @author: linanmiao
* @date: 2018/7/21 12:04
* @version: 1.0
*/
public abstract class AbstractCluster<T> implements Cluster<T>{
private Class<T> interfaceClass;
private List<Consumer<T>> consumers;
private LoadBalance loadBalance;
public AbstractCluster(Class<T> interfaceClass, List<Consumer<T>> consumers, LoadBalance loadBalance) {
this.interfaceClass = interfaceClass;
if (consumers == null || consumers.isEmpty()) {
throw new IllegalStateException("List<Consumer<T> consumers is null or empty.");
}
this.consumers = consumers;
this.loadBalance = loadBalance;
}
@Override
public String getKey() {
return interfaceClass.getName();
}
@Override
public Class<T> getInterface() {
return interfaceClass;
}
@Override
public Result invoke(Invocation invocation) {
return doInvoke(invocation);
}
@Override
public void close() {
for (Consumer<T> consumer : consumers) {
consumer.close();
}
}
protected List<Consumer<T>> getConsumers() {
return this.consumers;
}
public abstract Result doInvoke(Invocation invocation);
protected <T> Consumer<T> select(List<Consumer<T>> consumers, Consumer<T> selectedCosnumer, Invocation invocation) {
if (consumers == null || consumers.isEmpty()) {
return null;
}
Consumer<T> consumer = loadBalance.select(consumers, invocation);
if (selectedCosnumer != null && consumer.equals(selectedCosnumer)) {
consumers.remove(consumer);
return select(consumers, selectedCosnumer, invocation);
} else {
return consumer;
}
}
private void invokeIllegal() {
throw new IllegalStateException("This method can not be called.");
}
@Override
public void setParam(String key, Object value) {
invokeIllegal();
}
@Override
public String getParam(String key) {
invokeIllegal();
return null;
}
@Override
public String getParam(String key, String defaultValue) {
invokeIllegal();
return null;
}
@Override
public int getParamInt(String key) {
invokeIllegal();
return 0;
}
@Override
public int getParamInt(String key, int defaultValue) {
invokeIllegal();
return 0;
}
@Override
public boolean getParamBoolean(String key) {
invokeIllegal();
return false;
}
@Override
public boolean getParamBoolean(String key, boolean defaultValue) {
invokeIllegal();
return false;
}
}
|
UTF-8
|
Java
| 2,917 |
java
|
AbstractCluster.java
|
Java
|
[
{
"context": "\n\n/**\n * @description: AbstractCluster\n * @author: linanmiao\n * @date: 2018/7/21 12:04\n * @version: 1.0\n */\npu",
"end": 246,
"score": 0.9993680119514465,
"start": 237,
"tag": "USERNAME",
"value": "linanmiao"
}
] | null |
[] |
package lam.cobia.cluster;
import lam.cobia.loadbalance.LoadBalance;
import lam.cobia.rpc.Consumer;
import lam.cobia.rpc.Invocation;
import lam.cobia.rpc.Result;
import java.util.List;
/**
* @description: AbstractCluster
* @author: linanmiao
* @date: 2018/7/21 12:04
* @version: 1.0
*/
public abstract class AbstractCluster<T> implements Cluster<T>{
private Class<T> interfaceClass;
private List<Consumer<T>> consumers;
private LoadBalance loadBalance;
public AbstractCluster(Class<T> interfaceClass, List<Consumer<T>> consumers, LoadBalance loadBalance) {
this.interfaceClass = interfaceClass;
if (consumers == null || consumers.isEmpty()) {
throw new IllegalStateException("List<Consumer<T> consumers is null or empty.");
}
this.consumers = consumers;
this.loadBalance = loadBalance;
}
@Override
public String getKey() {
return interfaceClass.getName();
}
@Override
public Class<T> getInterface() {
return interfaceClass;
}
@Override
public Result invoke(Invocation invocation) {
return doInvoke(invocation);
}
@Override
public void close() {
for (Consumer<T> consumer : consumers) {
consumer.close();
}
}
protected List<Consumer<T>> getConsumers() {
return this.consumers;
}
public abstract Result doInvoke(Invocation invocation);
protected <T> Consumer<T> select(List<Consumer<T>> consumers, Consumer<T> selectedCosnumer, Invocation invocation) {
if (consumers == null || consumers.isEmpty()) {
return null;
}
Consumer<T> consumer = loadBalance.select(consumers, invocation);
if (selectedCosnumer != null && consumer.equals(selectedCosnumer)) {
consumers.remove(consumer);
return select(consumers, selectedCosnumer, invocation);
} else {
return consumer;
}
}
private void invokeIllegal() {
throw new IllegalStateException("This method can not be called.");
}
@Override
public void setParam(String key, Object value) {
invokeIllegal();
}
@Override
public String getParam(String key) {
invokeIllegal();
return null;
}
@Override
public String getParam(String key, String defaultValue) {
invokeIllegal();
return null;
}
@Override
public int getParamInt(String key) {
invokeIllegal();
return 0;
}
@Override
public int getParamInt(String key, int defaultValue) {
invokeIllegal();
return 0;
}
@Override
public boolean getParamBoolean(String key) {
invokeIllegal();
return false;
}
@Override
public boolean getParamBoolean(String key, boolean defaultValue) {
invokeIllegal();
return false;
}
}
| 2,917 | 0.631128 | 0.625986 | 118 | 23.720339 | 23.997488 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.449153 | false | false |
15
|
9cfb15d53ec8bfc0d9d5a964df8a8f3d43562168
| 20,040,317,448,742 |
30b5d28e140bfb568ecc371066fcdb9d6ebabac8
|
/webservice-principal/src/main/java/br/com/maicon/pratica/webserviceprincipal/model/persistence/specification/operation/ContainsOperation.java
|
9e6b274dabaaa8c01594b650a459fe6637cb9014
|
[] |
no_license
|
MaiconCanedo/multi-tenant-multi-module-master
|
https://github.com/MaiconCanedo/multi-tenant-multi-module-master
|
fe395a744631257ec80fcb90cff4f36cb2c51ad9
|
861c608ee29f701ffcf7b24e774b38270e8df1f5
|
refs/heads/master
| 2020-06-02T17:03:22.179000 | 2019-06-23T23:16:18 | 2019-06-23T23:16:18 | 190,830,754 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.maicon.pratica.webserviceprincipal.model.persistence.specification.operation;
import br.com.maicon.pratica.webserviceprincipal.model.entity.Carro;
import br.com.maicon.pratica.webserviceprincipal.model.persistence.specification.SearchCriteria;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
public class ContainsOperation implements BasicOperation {
private SearchCriteria criteria;
@Override
public boolean isValid(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
return true;
}
@Override
public Predicate toPredicate(Root<Carro> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (root.get(criteria.getKey()).getJavaType() == String.class)
return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue() + "%");
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
|
UTF-8
|
Java
| 1,057 |
java
|
ContainsOperation.java
|
Java
|
[] | null |
[] |
package br.com.maicon.pratica.webserviceprincipal.model.persistence.specification.operation;
import br.com.maicon.pratica.webserviceprincipal.model.entity.Carro;
import br.com.maicon.pratica.webserviceprincipal.model.persistence.specification.SearchCriteria;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
public class ContainsOperation implements BasicOperation {
private SearchCriteria criteria;
@Override
public boolean isValid(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
return true;
}
@Override
public Predicate toPredicate(Root<Carro> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (root.get(criteria.getKey()).getJavaType() == String.class)
return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue() + "%");
return builder.equal(root.get(criteria.getKey()), criteria.getValue());
}
}
| 1,057 | 0.758751 | 0.758751 | 27 | 38.148148 | 34.373444 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592593 | false | false |
15
|
6cff53469987b752de20764c04c2558d37bf3492
| 6,098,853,618,896 |
a03e55d09554e82b93279e5a869d363e4b0e1539
|
/src/main/java/com/candou/ic/navigation/jcwx/crawler/JCWX_JobCrawler.java
|
38be155484680c1e98d4613dcb2bc641629c8fde
|
[] |
no_license
|
jiangchao1987/maincrawler
|
https://github.com/jiangchao1987/maincrawler
|
b487772f2aa1c7746785b5203a406841ad6dfa30
|
306096013df6bcdcd8f3d1672bd39cae99e9e2c6
|
refs/heads/master
| 2021-01-25T08:42:26.830000 | 2013-07-26T09:07:17 | 2013-07-26T09:07:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.candou.ic.navigation.jcwx.crawler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.candou.ic.navigation.jcwx.bean.Category;
import com.candou.ic.navigation.jcwx.bean.Job;
import com.candou.ic.navigation.jcwx.dao.CategoryDao;
import com.candou.ic.navigation.jcwx.dao.JobDao;
import com.candou.util.DateTimeUtil;
import com.candou.util.SeedUtil;
import com.candou.util.TextUtil;
import com.candou.util.URLFetchUtil;
/**
* 精彩微信 Job爬虫逻辑。
*
* @author jiangchao
*/
public class JCWX_JobCrawler {
private final String seedFile;
private final int retryNumber = 5;
private static ObjectMapper mapper;
private static Logger log = Logger.getLogger(JCWX_JobCrawler.class);
public JCWX_JobCrawler(String file) {
seedFile = file;
}
public void start() {
List<Category> categories = getCategory();
List<Job> newJobs = new ArrayList<Job>();
CategoryDao.addBatchCategory(categories);
for (Category category : categories) {
log.info(String.format("fetch category %s[%s]", category.getCname(), category.getCurl()));
int page = 1;
int retryCounter = 0;
while (true) {
String pageUrl = category.getCurl().concat("&page=" + page);
String htmlSource = null;
do {
htmlSource = URLFetchUtil.fetchGet(pageUrl);
retryCounter++;
if (retryCounter > 1) {
log.info("retry connection: " + pageUrl);
}
} while (retryCounter < retryNumber && (null == htmlSource || htmlSource.length() == 0));
// if html source length equal zero
if (htmlSource == null || htmlSource.length() == 0) {
continue;
}
// analyze
JsonNode appNodeList = getNode(htmlSource);
if (appNodeList == null) {
break;
}
int size = appNodeList.size();
for (int index = 0; index < size; index++) {
JsonNode appNode = appNodeList.get(index);
Job job = new Job();
job.setId(Integer.parseInt(appNode.get("id").asText()));
job.setTitle(appNode.get("thumbnail").asText());
job.setWxh(appNode.get("wxh").asText());
job.setCname(appNode.get("category").asText());
job.setViews(Integer.parseInt(appNode.get("views").asText()));
job.setContent(appNode.get("content").asText());
job.setThumbnail(appNode.get("thumbnail").asText());
job.setCreatedAt(DateTimeUtil.nowDateTime());
job.setUpdatedAt(DateTimeUtil.nowDateTime());
job.setCid(category.getCid());
job.setCname(category.getCname());
newJobs.add(job);
}
if (newJobs.size() > 0) {
log.info("add batch jobs");
JobDao.addBatchJobs(newJobs);
newJobs.clear();
}
page++;
retryCounter = 0;
}
}
}
public static JsonNode getNode(String json) {
try {
if (mapper == null) {
mapper = new ObjectMapper();
}
JsonNode root = mapper.readTree(json);
JsonNode results = root.get("ItemList");
if (results.isArray() && results.size() > 0) {
return results;
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<Category> getCategory() {
List<Category> categories = new ArrayList<Category>();
Map<String, String> seeds = TextUtil.getSeedList(SeedUtil.getSeedFile(seedFile));
for (String name : seeds.keySet()) {
String url = seeds.get(name);
Category category = new Category();
category.setCid(Integer.parseInt(url.substring(url.indexOf("id=") + 3)));
category.setCname(name);
category.setCurl(url);
categories.add(category);
}
return categories;
}
}
|
UTF-8
|
Java
| 4,660 |
java
|
JCWX_JobCrawler.java
|
Java
|
[
{
"context": ".URLFetchUtil;\n\n/**\n * 精彩微信 Job爬虫逻辑。\n *\n * @author jiangchao\n */\npublic class JCWX_JobCrawler {\n\n private f",
"end": 679,
"score": 0.9973094463348389,
"start": 670,
"tag": "USERNAME",
"value": "jiangchao"
}
] | null |
[] |
package com.candou.ic.navigation.jcwx.crawler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.candou.ic.navigation.jcwx.bean.Category;
import com.candou.ic.navigation.jcwx.bean.Job;
import com.candou.ic.navigation.jcwx.dao.CategoryDao;
import com.candou.ic.navigation.jcwx.dao.JobDao;
import com.candou.util.DateTimeUtil;
import com.candou.util.SeedUtil;
import com.candou.util.TextUtil;
import com.candou.util.URLFetchUtil;
/**
* 精彩微信 Job爬虫逻辑。
*
* @author jiangchao
*/
public class JCWX_JobCrawler {
private final String seedFile;
private final int retryNumber = 5;
private static ObjectMapper mapper;
private static Logger log = Logger.getLogger(JCWX_JobCrawler.class);
public JCWX_JobCrawler(String file) {
seedFile = file;
}
public void start() {
List<Category> categories = getCategory();
List<Job> newJobs = new ArrayList<Job>();
CategoryDao.addBatchCategory(categories);
for (Category category : categories) {
log.info(String.format("fetch category %s[%s]", category.getCname(), category.getCurl()));
int page = 1;
int retryCounter = 0;
while (true) {
String pageUrl = category.getCurl().concat("&page=" + page);
String htmlSource = null;
do {
htmlSource = URLFetchUtil.fetchGet(pageUrl);
retryCounter++;
if (retryCounter > 1) {
log.info("retry connection: " + pageUrl);
}
} while (retryCounter < retryNumber && (null == htmlSource || htmlSource.length() == 0));
// if html source length equal zero
if (htmlSource == null || htmlSource.length() == 0) {
continue;
}
// analyze
JsonNode appNodeList = getNode(htmlSource);
if (appNodeList == null) {
break;
}
int size = appNodeList.size();
for (int index = 0; index < size; index++) {
JsonNode appNode = appNodeList.get(index);
Job job = new Job();
job.setId(Integer.parseInt(appNode.get("id").asText()));
job.setTitle(appNode.get("thumbnail").asText());
job.setWxh(appNode.get("wxh").asText());
job.setCname(appNode.get("category").asText());
job.setViews(Integer.parseInt(appNode.get("views").asText()));
job.setContent(appNode.get("content").asText());
job.setThumbnail(appNode.get("thumbnail").asText());
job.setCreatedAt(DateTimeUtil.nowDateTime());
job.setUpdatedAt(DateTimeUtil.nowDateTime());
job.setCid(category.getCid());
job.setCname(category.getCname());
newJobs.add(job);
}
if (newJobs.size() > 0) {
log.info("add batch jobs");
JobDao.addBatchJobs(newJobs);
newJobs.clear();
}
page++;
retryCounter = 0;
}
}
}
public static JsonNode getNode(String json) {
try {
if (mapper == null) {
mapper = new ObjectMapper();
}
JsonNode root = mapper.readTree(json);
JsonNode results = root.get("ItemList");
if (results.isArray() && results.size() > 0) {
return results;
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<Category> getCategory() {
List<Category> categories = new ArrayList<Category>();
Map<String, String> seeds = TextUtil.getSeedList(SeedUtil.getSeedFile(seedFile));
for (String name : seeds.keySet()) {
String url = seeds.get(name);
Category category = new Category();
category.setCid(Integer.parseInt(url.substring(url.indexOf("id=") + 3)));
category.setCname(name);
category.setCurl(url);
categories.add(category);
}
return categories;
}
}
| 4,660 | 0.544377 | 0.541792 | 140 | 32.157143 | 24.813957 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578571 | false | false |
15
|
cfffc614b3b04b3b17356558fd545e6f5f88c0ac
| 14,199,161,927,086 |
076743dab651eb88fb4f06a2a522c4487938c415
|
/ordem_crescente.java
|
a9e720c29d5c53c2ae141b7ac9f35d433ae6b5da
|
[] |
no_license
|
GuilhermeCLima/exercicios_java
|
https://github.com/GuilhermeCLima/exercicios_java
|
9c032382d64517a055ac4db143665923d8792d48
|
ec6c7f91de0e376433bfb4aec02fa5b986170666
|
refs/heads/master
| 2022-11-12T03:14:17.008000 | 2020-07-07T22:37:55 | 2020-07-07T22:37:55 | 277,607,073 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cursojava;
import java.util.Scanner;
public class ordem_crescente {
public static void main(String args[]) {
Scanner numero = new Scanner(System.in);
int a,b,c,numTroca;
System.out.printf("Digite o numero 1: ");// 7
a = numero.nextInt();
System.out.printf("Digite o numero 2: ");//8
b = numero.nextInt();
System.out.printf("Digite o numero 3: ");//9
c = numero.nextInt();
if((a>=b)&&(b>=c)) {
numTroca = a;
a = b;
b = numTroca;
System.out.println(" ordem crescente dos numeros = " + c +"-" + a + "-" + b);
}
else if((b>=a)&&(a>=c)) {
numTroca = b;
b = a;
a = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ c +"-" + b + "-" + a);
}
else if((c>=a)&&(b>=a)) {
numTroca = c;
c = a;
a = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ c +"-" + b + "-" + a);
}
else if((c>=a)&&(a>=b)) {
numTroca = a;
a = b;
b = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ a +"-" + b + "-" + c);
}
}
}
|
UTF-8
|
Java
| 1,044 |
java
|
ordem_crescente.java
|
Java
|
[] | null |
[] |
package cursojava;
import java.util.Scanner;
public class ordem_crescente {
public static void main(String args[]) {
Scanner numero = new Scanner(System.in);
int a,b,c,numTroca;
System.out.printf("Digite o numero 1: ");// 7
a = numero.nextInt();
System.out.printf("Digite o numero 2: ");//8
b = numero.nextInt();
System.out.printf("Digite o numero 3: ");//9
c = numero.nextInt();
if((a>=b)&&(b>=c)) {
numTroca = a;
a = b;
b = numTroca;
System.out.println(" ordem crescente dos numeros = " + c +"-" + a + "-" + b);
}
else if((b>=a)&&(a>=c)) {
numTroca = b;
b = a;
a = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ c +"-" + b + "-" + a);
}
else if((c>=a)&&(b>=a)) {
numTroca = c;
c = a;
a = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ c +"-" + b + "-" + a);
}
else if((c>=a)&&(a>=b)) {
numTroca = a;
a = b;
b = numTroca;
System.out.printf(" ordem crescente dos numeros = "+ a +"-" + b + "-" + c);
}
}
}
| 1,044 | 0.530651 | 0.524904 | 44 | 22.727272 | 22.697981 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.886364 | false | false |
15
|
6ab4cc488be56955b3409539f63b94d90a7f6ac0
| 18,932,215,899,268 |
3fbefb817ae2a62350edfb6444ec62053dbf73d1
|
/backend/src/main/java/com/r/connect/service/AccountService.java
|
004268fc377f46191b64a48b8be0617833d3da5f
|
[] |
no_license
|
CodeVaDOs/client-bank--spring-react
|
https://github.com/CodeVaDOs/client-bank--spring-react
|
4631dd9bfe374f167368b510fbfd7556b7512acc
|
ec2f7f45d4f748b351dafc001aa37cc93bdce16c
|
refs/heads/master
| 2023-02-16T23:03:08.223000 | 2021-01-10T21:37:22 | 2021-01-10T21:37:22 | 328,484,114 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.r.connect.service;
import com.r.connect.entity.Account;
import com.r.connect.exception.LackOfMoneyException;
import com.r.connect.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
@Service
public class AccountService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public List<Account> getAccounts() {
return this.accountRepository.findAll();
}
public Account doDeposit(String number, Double amount) {
Account account = accountRepository.findAccountByNumber(number).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", number)));
if (amount > 0) {
account.setBalance(account.getBalance() + amount);
return accountRepository.save(account);
}
throw new IllegalArgumentException("Amount must be > 0");
}
public Account doWithdraw(String number, Double amount) {
Account account = accountRepository.findAccountByNumber(number).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", number)));
if (account.getBalance() < amount) throw new LackOfMoneyException(String.format("An attempt to withdraw an amount more than is available. Balance: %d, Amount: %d", account.getBalance(), amount));
if (amount <= 0) throw new IllegalArgumentException("Amount must be > 0");
account.setBalance(account.getBalance() - amount);
return accountRepository.save(account);
}
public List<Account> doTransfer(String fn, String tn, Double a) {
Account accountFrom = accountRepository.findAccountByNumber(fn).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", fn)));
Account accountTo = accountRepository.findAccountByNumber(tn).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", tn)));
if (a <= 0) throw new IllegalArgumentException("Amount must be > 0");
if (accountFrom.getBalance() < a) throw new LackOfMoneyException(String.format("An attempt to withdraw an amount more than is available. Balance: %d, Amount: %d", accountFrom.getBalance(), a));
accountFrom.setBalance(accountFrom.getBalance() - a);
accountTo.setBalance(accountTo.getBalance() + a);
return accountRepository.saveAll(Arrays.asList(accountFrom, accountTo));
}
}
|
UTF-8
|
Java
| 2,680 |
java
|
AccountService.java
|
Java
|
[] | null |
[] |
package com.r.connect.service;
import com.r.connect.entity.Account;
import com.r.connect.exception.LackOfMoneyException;
import com.r.connect.repository.AccountRepository;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
@Service
public class AccountService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public List<Account> getAccounts() {
return this.accountRepository.findAll();
}
public Account doDeposit(String number, Double amount) {
Account account = accountRepository.findAccountByNumber(number).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", number)));
if (amount > 0) {
account.setBalance(account.getBalance() + amount);
return accountRepository.save(account);
}
throw new IllegalArgumentException("Amount must be > 0");
}
public Account doWithdraw(String number, Double amount) {
Account account = accountRepository.findAccountByNumber(number).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", number)));
if (account.getBalance() < amount) throw new LackOfMoneyException(String.format("An attempt to withdraw an amount more than is available. Balance: %d, Amount: %d", account.getBalance(), amount));
if (amount <= 0) throw new IllegalArgumentException("Amount must be > 0");
account.setBalance(account.getBalance() - amount);
return accountRepository.save(account);
}
public List<Account> doTransfer(String fn, String tn, Double a) {
Account accountFrom = accountRepository.findAccountByNumber(fn).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", fn)));
Account accountTo = accountRepository.findAccountByNumber(tn).orElseThrow(() -> new NoSuchElementException(String.format("Account with number %s not found :(", tn)));
if (a <= 0) throw new IllegalArgumentException("Amount must be > 0");
if (accountFrom.getBalance() < a) throw new LackOfMoneyException(String.format("An attempt to withdraw an amount more than is available. Balance: %d, Amount: %d", accountFrom.getBalance(), a));
accountFrom.setBalance(accountFrom.getBalance() - a);
accountTo.setBalance(accountTo.getBalance() + a);
return accountRepository.saveAll(Arrays.asList(accountFrom, accountTo));
}
}
| 2,680 | 0.722388 | 0.720149 | 56 | 46.857143 | 54.63562 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767857 | false | false |
15
|
f4ad0d1bb20e7c1c0be14feaddd7d39cde3f6eb5
| 25,254,407,757,045 |
7edd94d51b249f9aab62c076707d23c46d462d99
|
/src/main/java/com/haoding/demo/controller/MainController.java
|
baf49860b9361da6ad006ac76643004631c3db27
|
[] |
no_license
|
Mr-XM/securitiesTradingSystem
|
https://github.com/Mr-XM/securitiesTradingSystem
|
8f3c680640fb26ad07200acace9ba4819ee0ea3f
|
cdce5fb8a3a5ba665b42ba7ac51cd505f5ef5338
|
refs/heads/master
| 2022-06-23T04:19:10.569000 | 2019-07-24T09:16:42 | 2019-07-24T09:16:42 | 189,235,947 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.haoding.demo.controller;
import com.haoding.demo.service.serviceImpl.OptionalStockServiceImp;
import com.haoding.demo.service.serviceImpl.StockDataServiceImpl;
import com.haoding.demo.service.serviceImpl.StockInfoServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
//@RequestMapping("/main")
public class MainController {
@Autowired
private StockDataServiceImpl stockDataService;
@Autowired
private StockInfoServiceImpl stockInfoService;
@Autowired
private OptionalStockServiceImp optionalStockServiceImp;
@GetMapping("/getStockData")
@ResponseBody
@ApiOperation(value = "获取股票的全部历史数据" )
public String getStockData(String stockCode) {
String stockName = stockInfoService.getStockName(stockCode);
if(!"".equals(stockName)){
String stockData = stockDataService.getStockData(stockCode);
return stockData;
}
return "";
}
@GetMapping("/getStockName")
@ResponseBody
@ApiOperation(value = "根据股票代码获取股票的名字")
public String getStockName(String stockCode) {
String stockName = stockInfoService.getStockName(stockCode);
return stockName;
}
@GetMapping("/getStockInfoByStockCode")
@ResponseBody
@ApiOperation(value = "根据股票代码获取股票的信息")
public String getStockInfoByStockCode(String stockCode) {
String stockName = stockInfoService.getStockInfoByStockCode(stockCode);
return stockName;
}
/**
* 获得主页初始数据
* @return
*/
@GetMapping("/getInitialization")
@ResponseBody
@ApiOperation(value = "首页初始页面的股票数据")
public String getInitialization(){
String initialization=stockInfoService.getInitialization();
return initialization;
}
/**
* 添加自选股
* @param phone
* @param stock_name
* @param stock_id
* @return
*/
@PostMapping("/addOptionalStock")
@ResponseBody
@ApiOperation(value = "添加自选股")
public String addOptionalStock(String phone,String stock_name,String stock_id){
String msg=optionalStockServiceImp.addOptionalStock(phone,stock_name,stock_id);
return msg;
}
@PostMapping("/delOptionalStock")
@ResponseBody
@ApiOperation(value = "删除自选股")
public String delOptionalStock(String phone,String stock_id){
String msg=optionalStockServiceImp.delOptionalStock(phone,stock_id);
return msg;
}
@GetMapping("/selectOptionalStock")
@ResponseBody
@ApiOperation(value = "查询我的自选股")
public String selectOptionalStock(String phone){
String msg=optionalStockServiceImp.selectOptionalStock(phone);
return msg;
}
}
|
UTF-8
|
Java
| 2,951 |
java
|
MainController.java
|
Java
|
[] | null |
[] |
package com.haoding.demo.controller;
import com.haoding.demo.service.serviceImpl.OptionalStockServiceImp;
import com.haoding.demo.service.serviceImpl.StockDataServiceImpl;
import com.haoding.demo.service.serviceImpl.StockInfoServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
//@RequestMapping("/main")
public class MainController {
@Autowired
private StockDataServiceImpl stockDataService;
@Autowired
private StockInfoServiceImpl stockInfoService;
@Autowired
private OptionalStockServiceImp optionalStockServiceImp;
@GetMapping("/getStockData")
@ResponseBody
@ApiOperation(value = "获取股票的全部历史数据" )
public String getStockData(String stockCode) {
String stockName = stockInfoService.getStockName(stockCode);
if(!"".equals(stockName)){
String stockData = stockDataService.getStockData(stockCode);
return stockData;
}
return "";
}
@GetMapping("/getStockName")
@ResponseBody
@ApiOperation(value = "根据股票代码获取股票的名字")
public String getStockName(String stockCode) {
String stockName = stockInfoService.getStockName(stockCode);
return stockName;
}
@GetMapping("/getStockInfoByStockCode")
@ResponseBody
@ApiOperation(value = "根据股票代码获取股票的信息")
public String getStockInfoByStockCode(String stockCode) {
String stockName = stockInfoService.getStockInfoByStockCode(stockCode);
return stockName;
}
/**
* 获得主页初始数据
* @return
*/
@GetMapping("/getInitialization")
@ResponseBody
@ApiOperation(value = "首页初始页面的股票数据")
public String getInitialization(){
String initialization=stockInfoService.getInitialization();
return initialization;
}
/**
* 添加自选股
* @param phone
* @param stock_name
* @param stock_id
* @return
*/
@PostMapping("/addOptionalStock")
@ResponseBody
@ApiOperation(value = "添加自选股")
public String addOptionalStock(String phone,String stock_name,String stock_id){
String msg=optionalStockServiceImp.addOptionalStock(phone,stock_name,stock_id);
return msg;
}
@PostMapping("/delOptionalStock")
@ResponseBody
@ApiOperation(value = "删除自选股")
public String delOptionalStock(String phone,String stock_id){
String msg=optionalStockServiceImp.delOptionalStock(phone,stock_id);
return msg;
}
@GetMapping("/selectOptionalStock")
@ResponseBody
@ApiOperation(value = "查询我的自选股")
public String selectOptionalStock(String phone){
String msg=optionalStockServiceImp.selectOptionalStock(phone);
return msg;
}
}
| 2,951 | 0.705188 | 0.705188 | 93 | 29.053764 | 23.744774 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344086 | false | false |
15
|
6d6a8387b3b876fff545a5779c52e33d1e7db28c
| 3,195,455,699,398 |
20f817474bdcd3a052e0404e7b9cf3372c129ca0
|
/contributions-actors/fr.soleil.passerelle.extensions/src/test/java/be/isencia/passerelle/message/type/PasserelleMsgConversionTest.java
|
8ded89df86889aa0f81a74ec439b4c9d5fe2a596
|
[] |
no_license
|
tectronics/passerelle
|
https://github.com/tectronics/passerelle
|
20bd5b1dbe1a05cb9256086a7cd67d14d26f6125
|
74212c9f32cf1166742af33e1d79cdc1e546c3e6
|
refs/heads/master
| 2018-01-11T14:44:22.502000 | 2015-06-29T08:50:37 | 2015-06-29T08:50:37 | 44,732,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* (c) Copyright 2001-2005, iSencia Belgium NV All Rights Reserved.
*
* This software is the proprietary information of iSencia Belgium NV. Use is
* subject to license terms.
*/
package be.isencia.passerelle.message.type;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.testng.annotations.Test;
import com.isencia.passerelle.core.PasserelleException;
import com.isencia.passerelle.core.PasserelleToken;
import com.isencia.passerelle.message.ManagedMessage;
import com.isencia.passerelle.message.MessageFactory;
import com.isencia.passerelle.message.type.TypeConversionChain;
import fr.soleil.tango.clientapi.TangoAttribute;
public class PasserelleMsgConversionTest {
PasserelleToken origToken;
@BeforeClass
protected void setUp() throws Exception {
System.setProperty("TANGO_HOST", "localhost:20000");
final TangoAttribute attr = new TangoAttribute("test/mouse/1/positionY");
// attr.insert("5");
final ManagedMessage msg = MessageFactory.getInstance().createMessage();
msg.setBodyContent(attr, ManagedMessage.objectContentType);
origToken = new PasserelleToken(msg);
}
/*
* Test method for
* 'be.isencia.passerelle.message.type.TypeConversionChain.convertPasserelleMessageContent(PasserelleToken,
* Class)'
*/
@Test(enabled = false)
public void testConvertPasserelleMessageContent() throws UnsupportedOperationException,
PasserelleException {
final PasserelleToken result = TypeConversionChain.getInstance()
.convertPasserelleMessageContent(origToken, Double.class);
assertThat(result).isNotNull();
assertThat(Double.class.isAssignableFrom(result.getMessageContentType())).isTrue();
// assertEquals(new Double(5),
// result.getMessage().getBodyContent());
assertThat(result.getMessage().getID()).isEqualTo(origToken.getMessage().getID());
assertThat(result.getMessage().getVersion()).isEqualTo(origToken.getMessage().getVersion());
}
}
|
UTF-8
|
Java
| 2,150 |
java
|
PasserelleMsgConversionTest.java
|
Java
|
[] | null |
[] |
/*
* (c) Copyright 2001-2005, iSencia Belgium NV All Rights Reserved.
*
* This software is the proprietary information of iSencia Belgium NV. Use is
* subject to license terms.
*/
package be.isencia.passerelle.message.type;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.testng.annotations.Test;
import com.isencia.passerelle.core.PasserelleException;
import com.isencia.passerelle.core.PasserelleToken;
import com.isencia.passerelle.message.ManagedMessage;
import com.isencia.passerelle.message.MessageFactory;
import com.isencia.passerelle.message.type.TypeConversionChain;
import fr.soleil.tango.clientapi.TangoAttribute;
public class PasserelleMsgConversionTest {
PasserelleToken origToken;
@BeforeClass
protected void setUp() throws Exception {
System.setProperty("TANGO_HOST", "localhost:20000");
final TangoAttribute attr = new TangoAttribute("test/mouse/1/positionY");
// attr.insert("5");
final ManagedMessage msg = MessageFactory.getInstance().createMessage();
msg.setBodyContent(attr, ManagedMessage.objectContentType);
origToken = new PasserelleToken(msg);
}
/*
* Test method for
* 'be.isencia.passerelle.message.type.TypeConversionChain.convertPasserelleMessageContent(PasserelleToken,
* Class)'
*/
@Test(enabled = false)
public void testConvertPasserelleMessageContent() throws UnsupportedOperationException,
PasserelleException {
final PasserelleToken result = TypeConversionChain.getInstance()
.convertPasserelleMessageContent(origToken, Double.class);
assertThat(result).isNotNull();
assertThat(Double.class.isAssignableFrom(result.getMessageContentType())).isTrue();
// assertEquals(new Double(5),
// result.getMessage().getBodyContent());
assertThat(result.getMessage().getID()).isEqualTo(origToken.getMessage().getID());
assertThat(result.getMessage().getVersion()).isEqualTo(origToken.getMessage().getVersion());
}
}
| 2,150 | 0.717209 | 0.709767 | 56 | 36.392857 | 31.758394 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false |
15
|
c954a3cb8dabe3488e150aab9ffec0a7fe811e4c
| 6,880,537,659,290 |
a05a9cfe387c1f2395fb55fed9a6bb9c9d2ee079
|
/day07/src/loop/Test08.java
|
ab7222990e309dbd871fa70dba66f420b53bbeab
|
[] |
no_license
|
1sol2sol/1sol
|
https://github.com/1sol2sol/1sol
|
15f2b70e21f9212646d20d9a7837bc3f62554f98
|
aefcc6e93b404c044881f1371d9d64bc9a29de4d
|
refs/heads/main
| 2023-03-01T18:29:09.648000 | 2021-02-07T06:45:16 | 2021-02-07T06:45:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package loop;
import java.lang.*;
public class Test08 {
public static void main(String[] args) {
//목표 : 1부터 10까지의 합계 구하기(or 짝수합 or 홀수합)
//우리가 이해하는 방식으로 구성하면
//int sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
//System.out.println(sum);
// 반복문을 사용하려면 규칙이 있어야한다. 없으면 어거지로 만들어야한다.
// =합계를 위한 변수를 만들고 숫자를 하나씩 더한다.
int sum = 0;
for(int i=1; i<=10; i++) {
sum+=i;
// System.out.println("sum=" + sum);// 확인용코드
}
// sum+=1;
// sum+=2;
// sum+=3;
// sum+=4;
// sum+=5;
// sum+=6;
// sum+=7;
// sum+=8;
// sum+=9;
// sum+=10;
System.out.println("sum="+sum);
}
}
|
UTF-8
|
Java
| 833 |
java
|
Test08.java
|
Java
|
[] | null |
[] |
package loop;
import java.lang.*;
public class Test08 {
public static void main(String[] args) {
//목표 : 1부터 10까지의 합계 구하기(or 짝수합 or 홀수합)
//우리가 이해하는 방식으로 구성하면
//int sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
//System.out.println(sum);
// 반복문을 사용하려면 규칙이 있어야한다. 없으면 어거지로 만들어야한다.
// =합계를 위한 변수를 만들고 숫자를 하나씩 더한다.
int sum = 0;
for(int i=1; i<=10; i++) {
sum+=i;
// System.out.println("sum=" + sum);// 확인용코드
}
// sum+=1;
// sum+=2;
// sum+=3;
// sum+=4;
// sum+=5;
// sum+=6;
// sum+=7;
// sum+=8;
// sum+=9;
// sum+=10;
System.out.println("sum="+sum);
}
}
| 833 | 0.473364 | 0.42618 | 34 | 17.32353 | 14.482689 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.823529 | false | false |
15
|
7396dea2ef6b34738d9ed4ef4297228f7991df20
| 11,235,634,462,751 |
28e7b5278b2ffcdde8ea8bbbe7ac074792cf9bf0
|
/appier-sdk-sample/src/main/java/com/appier/android/sample/fragment/BaseFragment.java
|
2aeb493645c26a97c06bff1fad53ec265ccc5aab
|
[
"MIT"
] |
permissive
|
appier/pmp-android-sample
|
https://github.com/appier/pmp-android-sample
|
3082b7e6b4c3749245c4e3fcc07bdf3d812f3bae
|
9bf72b51862ca1222ecf7c3ec56624e972acc2f5
|
refs/heads/master
| 2023-04-06T01:39:29.368000 | 2021-04-06T08:00:20 | 2021-04-06T08:00:20 | 255,259,704 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.appier.android.sample.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.appier.ads.AppierError;
import com.appier.android.sample.common.DemoFlowController;
public abstract class BaseFragment extends Fragment {
private static final String ARG_TITLE = "title";
private String mTitle;
protected DemoFlowController mDemoFlowController;
public BaseFragment() {}
public String getTitle() {
return mTitle;
}
public void setTitleArgs(String title) {
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
this.setArguments(args);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(ARG_TITLE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mDemoFlowController != null) {
return mDemoFlowController.createView(inflater, container, savedInstanceState);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
if (mDemoFlowController != null && mDemoFlowController.isDemoAvailable()) {
onViewVisible(getView());
}
}
protected void enableErrorHandling() {
enableErrorHandling(1);
}
protected void enableErrorHandling(final int adCount) {
if (adCount <= 1) {
mDemoFlowController = new DemoFlowController(this, getContext()) {
@Override
public View createDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return BaseFragment.this.onCreateDemoView(inflater, container, savedInstanceState);
}
};
} else {
mDemoFlowController = new DemoFlowController(this, getContext()) {
int mTotalCount = 0;
int mBidCount = 0;
@Override
public void notifyAdBid() {
mTotalCount += 1;
mBidCount += 1;
if (mTotalCount == adCount) {
if (mBidCount > 0) {
super.notifyAdBid();
}
}
}
@Override
public void notifyAdNoBid() {
mTotalCount += 1;
if (mTotalCount == adCount) {
if (mBidCount > 0) {
super.notifyAdBid();
} else {
super.notifyAdNoBid();
}
}
}
@Override
public void notifyAdError(AppierError appierError) {
mTotalCount = 0;
mBidCount = 0;
super.notifyAdError(appierError);
}
@Override
public void refresh() {
super.refresh();
mTotalCount = 0;
mBidCount = 0;
}
@Override
public View createDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return BaseFragment.this.onCreateDemoView(inflater, container, savedInstanceState);
}
};
}
}
protected View onCreateDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return new View(getContext());
}
protected abstract void onViewVisible(View view);
}
|
UTF-8
|
Java
| 3,930 |
java
|
BaseFragment.java
|
Java
|
[] | null |
[] |
package com.appier.android.sample.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.appier.ads.AppierError;
import com.appier.android.sample.common.DemoFlowController;
public abstract class BaseFragment extends Fragment {
private static final String ARG_TITLE = "title";
private String mTitle;
protected DemoFlowController mDemoFlowController;
public BaseFragment() {}
public String getTitle() {
return mTitle;
}
public void setTitleArgs(String title) {
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
this.setArguments(args);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(ARG_TITLE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mDemoFlowController != null) {
return mDemoFlowController.createView(inflater, container, savedInstanceState);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
if (mDemoFlowController != null && mDemoFlowController.isDemoAvailable()) {
onViewVisible(getView());
}
}
protected void enableErrorHandling() {
enableErrorHandling(1);
}
protected void enableErrorHandling(final int adCount) {
if (adCount <= 1) {
mDemoFlowController = new DemoFlowController(this, getContext()) {
@Override
public View createDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return BaseFragment.this.onCreateDemoView(inflater, container, savedInstanceState);
}
};
} else {
mDemoFlowController = new DemoFlowController(this, getContext()) {
int mTotalCount = 0;
int mBidCount = 0;
@Override
public void notifyAdBid() {
mTotalCount += 1;
mBidCount += 1;
if (mTotalCount == adCount) {
if (mBidCount > 0) {
super.notifyAdBid();
}
}
}
@Override
public void notifyAdNoBid() {
mTotalCount += 1;
if (mTotalCount == adCount) {
if (mBidCount > 0) {
super.notifyAdBid();
} else {
super.notifyAdNoBid();
}
}
}
@Override
public void notifyAdError(AppierError appierError) {
mTotalCount = 0;
mBidCount = 0;
super.notifyAdError(appierError);
}
@Override
public void refresh() {
super.refresh();
mTotalCount = 0;
mBidCount = 0;
}
@Override
public View createDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return BaseFragment.this.onCreateDemoView(inflater, container, savedInstanceState);
}
};
}
}
protected View onCreateDemoView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return new View(getContext());
}
protected abstract void onViewVisible(View view);
}
| 3,930 | 0.550891 | 0.547583 | 124 | 30.693548 | 27.28824 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.491935 | false | false |
15
|
e81a8ee41b72a5fe70ba39bb25c41a90461e1ab9
| 23,639,500,049,053 |
49f387ce31433acb6917b73eff8399d17a6d3b23
|
/conssat-backend/src/main/java/pe/gob/mtpe/sivice/externo/core/accesodatos/repository/Impl/CorrelativoSesionDaoImpl.java
|
112b1d48da54fb15ac25862512e81df1422d5320
|
[] |
no_license
|
vsuncion/BACKEND
|
https://github.com/vsuncion/BACKEND
|
5af9c2360a17b2a336d692c0a0101d0ecc35da46
|
8a58de7c4794863a0f047f8c931817631b0ca3d1
|
refs/heads/master
| 2023-04-13T00:50:46.778000 | 2021-04-24T03:23:31 | 2021-04-24T03:23:31 | 359,958,631 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package pe.gob.mtpe.sivice.externo.core.accesodatos.repository.Impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import pe.gob.mtpe.sivice.externo.core.accesodatos.base.BaseDao;
import pe.gob.mtpe.sivice.externo.core.accesodatos.entity.CorrelativosSesion;
import pe.gob.mtpe.sivice.externo.core.accesodatos.repository.CorrelativoSesionDao;
@Component
public class CorrelativoSesionDaoImpl extends BaseDao<Long, CorrelativosSesion> implements CorrelativoSesionDao {
@Override
public List<CorrelativosSesion> listarCorrelativoSesiones(CorrelativosSesion correlativosSesion) {
List<CorrelativosSesion> lista = new ArrayList<CorrelativosSesion>();
EntityManager manager = createEntityManager();
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<CorrelativosSesion> criteriaQuery = builder.createQuery(CorrelativosSesion.class);
Root<CorrelativosSesion> root = criteriaQuery.from(CorrelativosSesion.class);
if(correlativosSesion.getRegion()!=null) {
Predicate valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
criteriaQuery.where(valor1);
}else {
criteriaQuery.select(root);
}
criteriaQuery.orderBy(builder.desc(root.get("correlativoSesion")),builder.desc(root.get("region")));
Query<CorrelativosSesion> query = (Query<CorrelativosSesion>) manager.createQuery(criteriaQuery);
lista = query.getResultList();
manager.close();
return lista;
}
@Override
public List<CorrelativosSesion> buscarCorrelativoSesiones(CorrelativosSesion correlativosSesion) {
EntityManager manager = createEntityManager();
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<CorrelativosSesion> criteriaQuery = builder.createQuery(CorrelativosSesion.class);
Root<CorrelativosSesion> root = criteriaQuery.from(CorrelativosSesion.class);
List<CorrelativosSesion> lista = new ArrayList<CorrelativosSesion>();
Predicate valor1 = null;
Predicate valor2 = null;
Predicate valor3 = null;
Predicate valor4 = null;
Predicate finalbusqueda = null;
if(correlativosSesion.getRegion().getrEgionidpk()>0) {
valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
finalbusqueda = builder.and(valor1);
}
if(correlativosSesion.getTipoSesion().gettIposesionidpk()!=null) {
valor2 = builder.equal(root.get("TipoSesion"), correlativosSesion.getTipoSesion().gettIposesionidpk());
finalbusqueda = builder.and(valor1, valor2);
}
if(correlativosSesion.getTipoSesion().gettIposesionidpk()!=null && correlativosSesion.getCodigocomision().trim().length()>0) {
valor3 = builder.equal(root.get("comision").get("vCodcomision"), correlativosSesion.getCodigocomision().trim());
finalbusqueda = builder.and(valor1, valor2, valor3);
}else if(correlativosSesion.getCodigocomision().trim().length()>0) {
valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
valor4 =builder.equal(root.get("comision").get("vCodcomision"), correlativosSesion.getCodigocomision().trim());
finalbusqueda = builder.and(valor1,valor4);
}
criteriaQuery.where(finalbusqueda);
Query<CorrelativosSesion> query = (Query<CorrelativosSesion>) manager.createQuery(criteriaQuery);
lista = query.getResultList();
manager.close();
return lista;
}
@Override
public CorrelativosSesion RegistrarCorrelativoSesion(CorrelativosSesion correlativosSesion) {
guardar(correlativosSesion);
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
@Override
public CorrelativosSesion ActualizarCorrelativoSesion(CorrelativosSesion correlativosSesion) {
actualizar(correlativosSesion);
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
@Override
public CorrelativosSesion buscarCorrelativoSesionId(CorrelativosSesion correlativosSesion) {
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
}
|
UTF-8
|
Java
| 4,422 |
java
|
CorrelativoSesionDaoImpl.java
|
Java
|
[] | null |
[] |
package pe.gob.mtpe.sivice.externo.core.accesodatos.repository.Impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import pe.gob.mtpe.sivice.externo.core.accesodatos.base.BaseDao;
import pe.gob.mtpe.sivice.externo.core.accesodatos.entity.CorrelativosSesion;
import pe.gob.mtpe.sivice.externo.core.accesodatos.repository.CorrelativoSesionDao;
@Component
public class CorrelativoSesionDaoImpl extends BaseDao<Long, CorrelativosSesion> implements CorrelativoSesionDao {
@Override
public List<CorrelativosSesion> listarCorrelativoSesiones(CorrelativosSesion correlativosSesion) {
List<CorrelativosSesion> lista = new ArrayList<CorrelativosSesion>();
EntityManager manager = createEntityManager();
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<CorrelativosSesion> criteriaQuery = builder.createQuery(CorrelativosSesion.class);
Root<CorrelativosSesion> root = criteriaQuery.from(CorrelativosSesion.class);
if(correlativosSesion.getRegion()!=null) {
Predicate valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
criteriaQuery.where(valor1);
}else {
criteriaQuery.select(root);
}
criteriaQuery.orderBy(builder.desc(root.get("correlativoSesion")),builder.desc(root.get("region")));
Query<CorrelativosSesion> query = (Query<CorrelativosSesion>) manager.createQuery(criteriaQuery);
lista = query.getResultList();
manager.close();
return lista;
}
@Override
public List<CorrelativosSesion> buscarCorrelativoSesiones(CorrelativosSesion correlativosSesion) {
EntityManager manager = createEntityManager();
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<CorrelativosSesion> criteriaQuery = builder.createQuery(CorrelativosSesion.class);
Root<CorrelativosSesion> root = criteriaQuery.from(CorrelativosSesion.class);
List<CorrelativosSesion> lista = new ArrayList<CorrelativosSesion>();
Predicate valor1 = null;
Predicate valor2 = null;
Predicate valor3 = null;
Predicate valor4 = null;
Predicate finalbusqueda = null;
if(correlativosSesion.getRegion().getrEgionidpk()>0) {
valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
finalbusqueda = builder.and(valor1);
}
if(correlativosSesion.getTipoSesion().gettIposesionidpk()!=null) {
valor2 = builder.equal(root.get("TipoSesion"), correlativosSesion.getTipoSesion().gettIposesionidpk());
finalbusqueda = builder.and(valor1, valor2);
}
if(correlativosSesion.getTipoSesion().gettIposesionidpk()!=null && correlativosSesion.getCodigocomision().trim().length()>0) {
valor3 = builder.equal(root.get("comision").get("vCodcomision"), correlativosSesion.getCodigocomision().trim());
finalbusqueda = builder.and(valor1, valor2, valor3);
}else if(correlativosSesion.getCodigocomision().trim().length()>0) {
valor1 = builder.equal(root.get("region"), correlativosSesion.getRegion().getrEgionidpk());
valor4 =builder.equal(root.get("comision").get("vCodcomision"), correlativosSesion.getCodigocomision().trim());
finalbusqueda = builder.and(valor1,valor4);
}
criteriaQuery.where(finalbusqueda);
Query<CorrelativosSesion> query = (Query<CorrelativosSesion>) manager.createQuery(criteriaQuery);
lista = query.getResultList();
manager.close();
return lista;
}
@Override
public CorrelativosSesion RegistrarCorrelativoSesion(CorrelativosSesion correlativosSesion) {
guardar(correlativosSesion);
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
@Override
public CorrelativosSesion ActualizarCorrelativoSesion(CorrelativosSesion correlativosSesion) {
actualizar(correlativosSesion);
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
@Override
public CorrelativosSesion buscarCorrelativoSesionId(CorrelativosSesion correlativosSesion) {
correlativosSesion = buscarId(correlativosSesion.getCorrelativoSesion());
return correlativosSesion;
}
}
| 4,422 | 0.784939 | 0.779964 | 112 | 38.482143 | 36.972717 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.321429 | false | false |
15
|
114233f6db2e061a2f08ec429cb0f0b5cb019681
| 11,647,951,349,547 |
94e23ac355709bc0003fffaa3d8ebd8b5f056db7
|
/src/com/futaba/InputPin.java
|
b27f76d233fc5661d30616440e15972e15e6647f
|
[] |
no_license
|
davidmahbubi/atm-system-app
|
https://github.com/davidmahbubi/atm-system-app
|
42fa36fdfa973c8f764e46ac7f7d6ebd0a93d7d6
|
2a9793511ee57904beb598c6e4541b8022367486
|
refs/heads/master
| 2022-01-06T08:31:37.840000 | 2019-05-28T13:08:01 | 2019-05-28T13:08:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.futaba;
import com.sun.glass.events.KeyEvent;
import javax.swing.JOptionPane;
/**
*
* @author David
*/
public class InputPin extends javax.swing.JFrame {
/**
* Creates new form InputPin
*/
// String nasabah;
int percobaan = 3;
int noRekening;
int pin;
public InputPin() {
initComponents();
tvTryAgain.setText(String.valueOf(percobaan));
}
void getNas(String namaNasabah, int noRek){
// nasabah = namaNasabah;
tvNasabah.setText(namaNasabah);
noRekening = noRek;
}
void checkPin(){
if (pfPin.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "PIN Belum dimasukkan !","Kesalahan",JOptionPane.ERROR_MESSAGE);
} else if (percobaan == 0) {
JOptionPane.showMessageDialog(this, "Akun teblokir !","Error",JOptionPane.ERROR_MESSAGE);
}
else {
try{
Bridge bdg = new Bridge();
try{
pin = Integer.parseInt(pfPin.getText());
} catch(NumberFormatException e){
JOptionPane.showMessageDialog(this, "Error, Input hanya bisa angka !","Error",JOptionPane.ERROR_MESSAGE);
}
bdg.getResultOf("select * from nasabah where no_rek="+noRekening+" && pin="+pin);
if (bdg.rs.next()) {
JOptionPane.showMessageDialog(this, "Sukses !");
MainMenu mn = new MainMenu();
mn.fillInfo(tvNasabah.getText(), String.valueOf(noRekening));
mn.setVisible(true);
this.dispose();
} else{
JOptionPane.showMessageDialog(this, "PIN Salah !","Kesalahan",JOptionPane.ERROR_MESSAGE);
pfPin.setText(null);
percobaan--;
tvTryAgain.setText(""+percobaan);
if (percobaan == 0) {
JOptionPane.showMessageDialog(this, "Terlalu banyak upaya ! akun diblokir !","Akun diblok !",JOptionPane.ERROR_MESSAGE);
new Bridge().smtUpdate("UPDATE `nasabah` SET `banned` = '1' WHERE `nasabah`.`no_rek` ="+noRekening);
this.dispose();
new InputRekening().setVisible(true);
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
pfPin = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
tvNasabah = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tvTryAgain = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Masukkan pin");
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Masukkan Pin"));
pfPin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
pfPinKeyPressed(evt);
}
});
jButton1.setText("Selanjutnya >>>");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Nama Nasabah :");
tvNasabah.setText("jLabel2");
jLabel2.setText("Percobaan tersedia :");
tvTryAgain.setText("jLabel3");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pfPin)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 208, Short.MAX_VALUE)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(tvTryAgain)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tvNasabah)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tvNasabah))
.addGap(18, 18, 18)
.addComponent(pfPin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tvTryAgain))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
checkPin();
}//GEN-LAST:event_jButton1ActionPerformed
private void pfPinKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pfPinKeyPressed
// TODO add your handling code here:
if (evt.getKeyCode()==KeyEvent.VK_ENTER) {
checkPin();
}
}//GEN-LAST:event_pfPinKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InputPin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField pfPin;
private javax.swing.JLabel tvNasabah;
private javax.swing.JLabel tvTryAgain;
// End of variables declaration//GEN-END:variables
}
|
UTF-8
|
Java
| 10,675 |
java
|
InputPin.java
|
Java
|
[
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author David\n */\npublic class InputPin extends javax.swing.JFr",
"end": 300,
"score": 0.9981886744499207,
"start": 295,
"tag": "NAME",
"value": "David"
},
{
"context": " }\n });\n\n jLabel1.setText(\"Nama Nasabah :\");\n\n tvNasabah.setText(\"jLabel2\");\n\n ",
"end": 4175,
"score": 0.950411319732666,
"start": 4163,
"tag": "NAME",
"value": "Nama Nasabah"
}
] | null |
[] |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.futaba;
import com.sun.glass.events.KeyEvent;
import javax.swing.JOptionPane;
/**
*
* @author David
*/
public class InputPin extends javax.swing.JFrame {
/**
* Creates new form InputPin
*/
// String nasabah;
int percobaan = 3;
int noRekening;
int pin;
public InputPin() {
initComponents();
tvTryAgain.setText(String.valueOf(percobaan));
}
void getNas(String namaNasabah, int noRek){
// nasabah = namaNasabah;
tvNasabah.setText(namaNasabah);
noRekening = noRek;
}
void checkPin(){
if (pfPin.getText().trim().isEmpty()) {
JOptionPane.showMessageDialog(this, "PIN Belum dimasukkan !","Kesalahan",JOptionPane.ERROR_MESSAGE);
} else if (percobaan == 0) {
JOptionPane.showMessageDialog(this, "Akun teblokir !","Error",JOptionPane.ERROR_MESSAGE);
}
else {
try{
Bridge bdg = new Bridge();
try{
pin = Integer.parseInt(pfPin.getText());
} catch(NumberFormatException e){
JOptionPane.showMessageDialog(this, "Error, Input hanya bisa angka !","Error",JOptionPane.ERROR_MESSAGE);
}
bdg.getResultOf("select * from nasabah where no_rek="+noRekening+" && pin="+pin);
if (bdg.rs.next()) {
JOptionPane.showMessageDialog(this, "Sukses !");
MainMenu mn = new MainMenu();
mn.fillInfo(tvNasabah.getText(), String.valueOf(noRekening));
mn.setVisible(true);
this.dispose();
} else{
JOptionPane.showMessageDialog(this, "PIN Salah !","Kesalahan",JOptionPane.ERROR_MESSAGE);
pfPin.setText(null);
percobaan--;
tvTryAgain.setText(""+percobaan);
if (percobaan == 0) {
JOptionPane.showMessageDialog(this, "Terlalu banyak upaya ! akun diblokir !","Akun diblok !",JOptionPane.ERROR_MESSAGE);
new Bridge().smtUpdate("UPDATE `nasabah` SET `banned` = '1' WHERE `nasabah`.`no_rek` ="+noRekening);
this.dispose();
new InputRekening().setVisible(true);
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
pfPin = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
tvNasabah = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tvTryAgain = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Masukkan pin");
setResizable(false);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Masukkan Pin"));
pfPin.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
pfPinKeyPressed(evt);
}
});
jButton1.setText("Selanjutnya >>>");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("<NAME> :");
tvNasabah.setText("jLabel2");
jLabel2.setText("Percobaan tersedia :");
tvTryAgain.setText("jLabel3");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pfPin)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 208, Short.MAX_VALUE)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(tvTryAgain)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tvNasabah)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tvNasabah))
.addGap(18, 18, 18)
.addComponent(pfPin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tvTryAgain))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
checkPin();
}//GEN-LAST:event_jButton1ActionPerformed
private void pfPinKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pfPinKeyPressed
// TODO add your handling code here:
if (evt.getKeyCode()==KeyEvent.VK_ENTER) {
checkPin();
}
}//GEN-LAST:event_pfPinKeyPressed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InputPin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InputPin().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPasswordField pfPin;
private javax.swing.JLabel tvNasabah;
private javax.swing.JLabel tvTryAgain;
// End of variables declaration//GEN-END:variables
}
| 10,669 | 0.601592 | 0.595035 | 237 | 44.042194 | 34.377254 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.556962 | false | false |
15
|
2f6fd41b2cb98a84b18aaceb635eaffe50b0b902
| 4,217,657,951,994 |
c695262d0e2f93665dd4495537865e81954e75b7
|
/src/server/EchoServerHandler.java
|
599b7ff8220e54a82dedb0315518876805500017
|
[] |
no_license
|
DeepViolet/java-netty
|
https://github.com/DeepViolet/java-netty
|
0423a0772521ff634114b6c74679b0a0fc8b1c94
|
afc71cf39ca7db2d205883eea59fabf4dd9cd29b
|
refs/heads/master
| 2021-01-22T03:30:08.480000 | 2017-05-25T09:59:11 | 2017-05-25T09:59:11 | 92,382,029 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package server;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Created by liuhuiyi on 2017/5/25.
*/
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server channel Read..");
System.out.println(ctx.channel().remoteAddress()+"-->Server :"+ msg.toString());
ctx.write("\nserver write:"+msg+"\n");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
|
UTF-8
|
Java
| 722 |
java
|
EchoServerHandler.java
|
Java
|
[
{
"context": "l.ChannelInboundHandlerAdapter;\n\n/**\n * Created by liuhuiyi on 2017/5/25.\n */\npublic class EchoServerHandler ",
"end": 145,
"score": 0.9996031522750854,
"start": 137,
"tag": "USERNAME",
"value": "liuhuiyi"
}
] | null |
[] |
package server;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Created by liuhuiyi on 2017/5/25.
*/
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("server channel Read..");
System.out.println(ctx.channel().remoteAddress()+"-->Server :"+ msg.toString());
ctx.write("\nserver write:"+msg+"\n");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
| 722 | 0.696676 | 0.686981 | 23 | 30.391304 | 30.086454 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false |
15
|
2121e5f6a6ef29b0d7366092f6bfc508b133af35
| 12,618,613,958,527 |
b6a57365e16f9251272742b438a385565ec6aa50
|
/src/main/java/com/dgi/dsi/winregistre/entites/BordereauActe.java
|
e9b7a535cbb5fa80af683808dc5faf26db0f003d
|
[] |
no_license
|
SedjroSylvanus/winregistreBack
|
https://github.com/SedjroSylvanus/winregistreBack
|
8d6f3f93c0f9761990977970dc7c8fd3135da58e
|
663aba9b136a1ee4802a28d141f602302461fb3d
|
refs/heads/master
| 2022-12-08T13:57:41.982000 | 2020-07-06T15:10:20 | 2020-07-06T15:10:20 | 179,077,788 | 0 | 0 | null | false | 2022-11-16T12:16:53 | 2019-04-02T12:55:05 | 2020-07-06T15:11:18 | 2022-11-16T12:16:50 | 1,885 | 0 | 0 | 3 |
Java
| false | false |
package com.dgi.dsi.winregistre.entites;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import com.dgi.dsi.winregistre.parent.entites.EntityBaseBean;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="bordereauacte", schema = "winregist")
//@Table(name="bordereauacte")
public class BordereauActe extends EntityBaseBean implements Serializable {
private static final long serialVersionUID = 1L;
// @Column(unique = true)
private String numero;
@Temporal(TemporalType.TIMESTAMP)
private Date dateBordereau ;
private Integer nbreActe ;
private Double totalDS = 0.;
private Double totalPenalite = 0.;
private Double totalAmende = 0.;
private Double totalRedevance = 0.;
// private Double droitSimple = 0.;
private Double totalTimbre = 0.;
private Double totalPlusValueImobiliere = 0.;
private Boolean validated ;
private Boolean sourceInterne ;
private Boolean transferred = Boolean.FALSE ;
private String numeroBordereauValidateur ;
// @ManyToOne
// private CategorieActe categorieActe;
@JsonIgnore
@OneToMany(mappedBy="bordereauActe")
List<Acte> actesBordereau = new ArrayList<>();
@ManyToOne
private Agent agent;
// @ManyToOne
// private Institution institution;
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public Date getDateBordereau() {
return dateBordereau;
}
public void setDateBordereau(Date dateBordereau) {
this.dateBordereau = dateBordereau;
}
public Integer getNbreActe() {
return nbreActe;
}
public void setNbreActe(Integer nbreActe) {
this.nbreActe = nbreActe;
}
public Double getTotalDS() {
return totalDS;
}
public void setTotalDS(Double totalDS) {
this.totalDS = totalDS;
}
public Double getTotalPenalite() {
return totalPenalite;
}
public void setTotalPenalite(Double totalPenalite) {
this.totalPenalite = totalPenalite;
}
public Double getTotalAmende() {
return totalAmende;
}
public void setTotalAmende(Double totalAmende) {
this.totalAmende = totalAmende;
}
public Boolean getValidated() {
return validated;
}
public void setValidated(Boolean validated) {
this.validated = validated;
}
public Boolean getTransferred() {
return transferred;
}
public void setTransferred(Boolean transferred) {
this.transferred = transferred;
}
public Boolean getSourceInterne() {
return sourceInterne;
}
public void setSourceInterne(Boolean sourceInterne) {
this.sourceInterne = sourceInterne;
}
// public CategorieActe getCategorieActe() {
// return categorieActe;
// }
//
// public void setCategorieActe(CategorieActe categorieActe) {
// this.categorieActe = categorieActe;
// }
public Agent getAgent() {
return agent;
}
public void setAgent(Agent agent) {
this.agent = agent;
}
// public Institution getInstitution() {
// return institution;
// }
//
// public void setInstitution(Institution institution) {
// this.institution = institution;
// }
@Override
public String toString() {
return "BordereauActeDao [numero=" + numero + ", dateBordereau=" + dateBordereau + ", nbreActe=" + nbreActe
+ ", totalDS=" + totalDS + ", totalPenalite=" + totalPenalite + ", totalAmende=" + totalAmende
+ ", agent=" + agent + "]"+ super.toString();
}
public BordereauActe() {
super();
this.totalDS = 0.;
this.totalPenalite = 0.;
this.totalAmende = 0.;
this.totalRedevance = 0.;
this.totalTimbre = 0.;
}
public BordereauActe(String numero, Date dateBordereau, Integer nbreActe, Double totalDS, Double totalPenalite, Double totalAmende, Double totalRedevance, Double totalTimbre, List<Acte> actes, Agent agent) {
this.numero = numero;
this.dateBordereau = dateBordereau;
this.nbreActe = nbreActe;
this.totalDS = totalDS;
this.totalPenalite = totalPenalite;
this.totalAmende = totalAmende;
this.totalRedevance = totalRedevance;
this.totalTimbre = totalTimbre;
this.actesBordereau = actes;
this.agent = agent;
}
public List<Acte> getActesBordereau() {
return actesBordereau;
}
public void setActesBordereau(List<Acte> actesBordereau) {
this.actesBordereau = actesBordereau;
}
// `CONT_NUM` varchar(13) NOT NULL,
public Double getTotalRedevance() {
return totalRedevance;
}
public void setTotalRedevance(Double totalRedevance) {
this.totalRedevance = totalRedevance;
}
public Double getTotalTimbre() {
return totalTimbre;
}
public void setTotalTimbre(Double totalTimbre) {
this.totalTimbre = totalTimbre;
}
public String getNumeroBordereauValidateur() {
return numeroBordereauValidateur;
}
public void setNumeroBordereauValidateur(String numeroBordereauValidateur) {
this.numeroBordereauValidateur = numeroBordereauValidateur;
}
public Double getTotalPlusValueImobiliere() {
return totalPlusValueImobiliere;
}
public void setTotalPlusValueImobiliere(Double totalPlusValueImobiliere) {
this.totalPlusValueImobiliere = totalPlusValueImobiliere;
}
}
|
UTF-8
|
Java
| 5,189 |
java
|
BordereauActe.java
|
Java
|
[] | null |
[] |
package com.dgi.dsi.winregistre.entites;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.*;
import com.dgi.dsi.winregistre.parent.entites.EntityBaseBean;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name="bordereauacte", schema = "winregist")
//@Table(name="bordereauacte")
public class BordereauActe extends EntityBaseBean implements Serializable {
private static final long serialVersionUID = 1L;
// @Column(unique = true)
private String numero;
@Temporal(TemporalType.TIMESTAMP)
private Date dateBordereau ;
private Integer nbreActe ;
private Double totalDS = 0.;
private Double totalPenalite = 0.;
private Double totalAmende = 0.;
private Double totalRedevance = 0.;
// private Double droitSimple = 0.;
private Double totalTimbre = 0.;
private Double totalPlusValueImobiliere = 0.;
private Boolean validated ;
private Boolean sourceInterne ;
private Boolean transferred = Boolean.FALSE ;
private String numeroBordereauValidateur ;
// @ManyToOne
// private CategorieActe categorieActe;
@JsonIgnore
@OneToMany(mappedBy="bordereauActe")
List<Acte> actesBordereau = new ArrayList<>();
@ManyToOne
private Agent agent;
// @ManyToOne
// private Institution institution;
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public Date getDateBordereau() {
return dateBordereau;
}
public void setDateBordereau(Date dateBordereau) {
this.dateBordereau = dateBordereau;
}
public Integer getNbreActe() {
return nbreActe;
}
public void setNbreActe(Integer nbreActe) {
this.nbreActe = nbreActe;
}
public Double getTotalDS() {
return totalDS;
}
public void setTotalDS(Double totalDS) {
this.totalDS = totalDS;
}
public Double getTotalPenalite() {
return totalPenalite;
}
public void setTotalPenalite(Double totalPenalite) {
this.totalPenalite = totalPenalite;
}
public Double getTotalAmende() {
return totalAmende;
}
public void setTotalAmende(Double totalAmende) {
this.totalAmende = totalAmende;
}
public Boolean getValidated() {
return validated;
}
public void setValidated(Boolean validated) {
this.validated = validated;
}
public Boolean getTransferred() {
return transferred;
}
public void setTransferred(Boolean transferred) {
this.transferred = transferred;
}
public Boolean getSourceInterne() {
return sourceInterne;
}
public void setSourceInterne(Boolean sourceInterne) {
this.sourceInterne = sourceInterne;
}
// public CategorieActe getCategorieActe() {
// return categorieActe;
// }
//
// public void setCategorieActe(CategorieActe categorieActe) {
// this.categorieActe = categorieActe;
// }
public Agent getAgent() {
return agent;
}
public void setAgent(Agent agent) {
this.agent = agent;
}
// public Institution getInstitution() {
// return institution;
// }
//
// public void setInstitution(Institution institution) {
// this.institution = institution;
// }
@Override
public String toString() {
return "BordereauActeDao [numero=" + numero + ", dateBordereau=" + dateBordereau + ", nbreActe=" + nbreActe
+ ", totalDS=" + totalDS + ", totalPenalite=" + totalPenalite + ", totalAmende=" + totalAmende
+ ", agent=" + agent + "]"+ super.toString();
}
public BordereauActe() {
super();
this.totalDS = 0.;
this.totalPenalite = 0.;
this.totalAmende = 0.;
this.totalRedevance = 0.;
this.totalTimbre = 0.;
}
public BordereauActe(String numero, Date dateBordereau, Integer nbreActe, Double totalDS, Double totalPenalite, Double totalAmende, Double totalRedevance, Double totalTimbre, List<Acte> actes, Agent agent) {
this.numero = numero;
this.dateBordereau = dateBordereau;
this.nbreActe = nbreActe;
this.totalDS = totalDS;
this.totalPenalite = totalPenalite;
this.totalAmende = totalAmende;
this.totalRedevance = totalRedevance;
this.totalTimbre = totalTimbre;
this.actesBordereau = actes;
this.agent = agent;
}
public List<Acte> getActesBordereau() {
return actesBordereau;
}
public void setActesBordereau(List<Acte> actesBordereau) {
this.actesBordereau = actesBordereau;
}
// `CONT_NUM` varchar(13) NOT NULL,
public Double getTotalRedevance() {
return totalRedevance;
}
public void setTotalRedevance(Double totalRedevance) {
this.totalRedevance = totalRedevance;
}
public Double getTotalTimbre() {
return totalTimbre;
}
public void setTotalTimbre(Double totalTimbre) {
this.totalTimbre = totalTimbre;
}
public String getNumeroBordereauValidateur() {
return numeroBordereauValidateur;
}
public void setNumeroBordereauValidateur(String numeroBordereauValidateur) {
this.numeroBordereauValidateur = numeroBordereauValidateur;
}
public Double getTotalPlusValueImobiliere() {
return totalPlusValueImobiliere;
}
public void setTotalPlusValueImobiliere(Double totalPlusValueImobiliere) {
this.totalPlusValueImobiliere = totalPlusValueImobiliere;
}
}
| 5,189 | 0.725188 | 0.722297 | 235 | 21.080851 | 24.337997 | 211 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.187234 | false | false |
15
|
c3dfa433927256c5a585a2dd3305c5d31af2bfeb
| 12,618,613,961,594 |
7b67910dcbfafd11faa18f3d9a65fcdd4e1a0432
|
/app/src/main/java/com/example/phil/bookapplication/model/Book.java
|
2717c6554802b1259351f242b311eb5e42c66d42
|
[] |
no_license
|
tydaikho/BookApplication
|
https://github.com/tydaikho/BookApplication
|
0f56b7fc2fb1d6e60c941e3be48692c5c28c7173
|
55c4b96eda0c76826e047440112218030a62fc5c
|
refs/heads/master
| 2020-12-26T02:39:15.615000 | 2015-04-09T10:40:53 | 2015-04-09T10:40:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.phil.bookapplication.model;
import java.io.Serializable;
public class Book implements Serializable{
private static final String[] urls = {
"http://41.media.tumblr.com/b200093e29442b05f3d86f574780e414/tumblr_nmi8r5svD61tvcttpo1_250.jpg",
"http://36.media.tumblr.com/b6df8a8e502ac323ea8f5aa0fb0a3fd9/tumblr_nm7zaqTlLj1tgbkn6o1_250.jpg",
"http://40.media.tumblr.com/93793efa7ea69b72fd41a153344b7180/tumblr_nkszyzplmj1r4lihzo1_250.png",
"http://36.media.tumblr.com/beb69bc24c16422c92fb1cdfbc0f1fc5/tumblr_n7jywgpWqa1qgqig6o1_400.png",
"http://40.media.tumblr.com/6e478504b2636561581783e7ae76b129/tumblr_n7pd83Hkhp1tthm8wo1_400.jpg",
"http://41.media.tumblr.com/ab63ccb43481b427bc37ff8b59114cfc/tumblr_nmhtjzJw7a1qemdseo1_250.jpg",
"http://40.media.tumblr.com/3b7e658300aefe352d5b6430624af799/tumblr_naxqvbCSGi1qgddlro1_250.jpg",
"http://41.media.tumblr.com/d91e9c2e44dfd66187e9c78408f6bb29/tumblr_ne9u4tZPI31rags0ko1_250.jpg",
"http://41.media.tumblr.com/4f6cdbac6f6a82ae8c392bdf1857e368/tumblr_nmbo7y3y6k1scp6t2o1_400.png",
"http://40.media.tumblr.com/aa1159ed4876a69af5c9b4725d2b02dc/tumblr_nm7z1qqAE71qb139no1_400.jpg"
};
private Long bookUid;
private String title;
private String author;
private String publisher;
private Long bookImageUid;
public Book() {
}
public Book(Long bookUid, String title, String author, String publisher, Long bookImageUid) {
this.bookUid = bookUid;
this.title = title;
this.author = author;
this.publisher = publisher;
this.bookImageUid = bookImageUid;
}
public String getImageUrl() {
return urls[((int) (bookImageUid % urls.length))];
}
public Long getBookImageUid() {
return bookImageUid;
}
public void setBookImageUid(Long bookImageUid) {
this.bookImageUid = bookImageUid;
}
public Long getBookUid() {
return bookUid;
}
public void setBookUid(Long bookUid) {
this.bookUid = bookUid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
|
UTF-8
|
Java
| 2,572 |
java
|
Book.java
|
Java
|
[
{
"context": "\n this.title = title;\n this.author = author;\n this.publisher = publisher;\n this",
"end": 1628,
"score": 0.9656319618225098,
"start": 1622,
"tag": "NAME",
"value": "author"
}
] | null |
[] |
package com.example.phil.bookapplication.model;
import java.io.Serializable;
public class Book implements Serializable{
private static final String[] urls = {
"http://41.media.tumblr.com/b200093e29442b05f3d86f574780e414/tumblr_nmi8r5svD61tvcttpo1_250.jpg",
"http://36.media.tumblr.com/b6df8a8e502ac323ea8f5aa0fb0a3fd9/tumblr_nm7zaqTlLj1tgbkn6o1_250.jpg",
"http://40.media.tumblr.com/93793efa7ea69b72fd41a153344b7180/tumblr_nkszyzplmj1r4lihzo1_250.png",
"http://36.media.tumblr.com/beb69bc24c16422c92fb1cdfbc0f1fc5/tumblr_n7jywgpWqa1qgqig6o1_400.png",
"http://40.media.tumblr.com/6e478504b2636561581783e7ae76b129/tumblr_n7pd83Hkhp1tthm8wo1_400.jpg",
"http://41.media.tumblr.com/ab63ccb43481b427bc37ff8b59114cfc/tumblr_nmhtjzJw7a1qemdseo1_250.jpg",
"http://40.media.tumblr.com/3b7e658300aefe352d5b6430624af799/tumblr_naxqvbCSGi1qgddlro1_250.jpg",
"http://41.media.tumblr.com/d91e9c2e44dfd66187e9c78408f6bb29/tumblr_ne9u4tZPI31rags0ko1_250.jpg",
"http://41.media.tumblr.com/4f6cdbac6f6a82ae8c392bdf1857e368/tumblr_nmbo7y3y6k1scp6t2o1_400.png",
"http://40.media.tumblr.com/aa1159ed4876a69af5c9b4725d2b02dc/tumblr_nm7z1qqAE71qb139no1_400.jpg"
};
private Long bookUid;
private String title;
private String author;
private String publisher;
private Long bookImageUid;
public Book() {
}
public Book(Long bookUid, String title, String author, String publisher, Long bookImageUid) {
this.bookUid = bookUid;
this.title = title;
this.author = author;
this.publisher = publisher;
this.bookImageUid = bookImageUid;
}
public String getImageUrl() {
return urls[((int) (bookImageUid % urls.length))];
}
public Long getBookImageUid() {
return bookImageUid;
}
public void setBookImageUid(Long bookImageUid) {
this.bookImageUid = bookImageUid;
}
public Long getBookUid() {
return bookUid;
}
public void setBookUid(Long bookUid) {
this.bookUid = bookUid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
| 2,572 | 0.679238 | 0.563764 | 81 | 30.753086 | 34.386162 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45679 | false | false |
15
|
14278b2439516d823206188b68206c5cb8b0fc81
| 15,341,623,244,187 |
9356d86037b599628e34da1887a7214505ea47a1
|
/app/src/main/java/com/zsg/address/MainActivity.java
|
72f09d73f7980ff508ca4b4d06cd05daea628e2d
|
[] |
no_license
|
592713711/text
|
https://github.com/592713711/text
|
42df28bc379993ab49a997d5fbcb9b89054393aa
|
4392e7edf8f54b8542df1d3dea5948bd5240642c
|
refs/heads/master
| 2021-07-15T21:35:17.632000 | 2021-03-01T08:26:40 | 2021-03-01T08:26:40 | 53,394,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.zsg.address;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends Activity {
@Bind(R.id.listView)
ListView listView;
ArrayList<AddressBook> data;
AddressAdapter adapter;
ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//获得手机联系人
resolver = getContentResolver();
//addData();
// initview();
initview2();
}
private void initview() {
data = new ArrayList<>();
Iterator<AddressBook> books = AddressBook.findAll(AddressBook.class);
while (books.hasNext()) {
data.add(books.next());
}
adapter = new AddressAdapter(data, this);
listView.setAdapter(adapter);
}
public void addData() {
AddressBook book = new AddressBook("张三", "15755554444");
AddressBook book2 = new AddressBook("李四", "15733334444");
AddressBook book3 = new AddressBook("王五", "15755556666");
book.save();
book2.save();
book3.save();
}
public void initview2() {
data = new ArrayList<>();
//统一资源标识 content://contract/phones
Uri uri=ContactsContract.Contacts.CONTENT_URI;
//HAS_PHONE_NUMBER 有号码返回1 无号码返回0
String projection[]={
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
Cursor c=resolver.query(uri,projection,"has_phone_number=?",new String[]{String.valueOf(1)},null);
while(c.moveToNext()){
long id=c.getLong(0);
String name=c.getString(1);
int h=c.getInt(2);
AddressBook book=new AddressBook();
book.setName(name);
book.setId(id);
data.add(book);
}
adapter = new AddressAdapter(data, this);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
UTF-8
|
Java
| 3,257 |
java
|
MainActivity.java
|
Java
|
[
{
"context": "a() {\n AddressBook book = new AddressBook(\"张三\", \"15755554444\");\n AddressBook book2 = new",
"end": 1352,
"score": 0.9954544305801392,
"start": 1350,
"tag": "NAME",
"value": "张三"
},
{
"context": "4\");\n AddressBook book2 = new AddressBook(\"李四\", \"15733334444\");\n AddressBook book3 = new",
"end": 1418,
"score": 0.9972426891326904,
"start": 1416,
"tag": "NAME",
"value": "李四"
},
{
"context": "4\");\n AddressBook book3 = new AddressBook(\"王五\", \"15755556666\");\n\n book.save();\n b",
"end": 1484,
"score": 0.9982588291168213,
"start": 1482,
"tag": "NAME",
"value": "王五"
}
] | null |
[] |
package com.zsg.address;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.Bind;
import butterknife.ButterKnife;
public class MainActivity extends Activity {
@Bind(R.id.listView)
ListView listView;
ArrayList<AddressBook> data;
AddressAdapter adapter;
ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//获得手机联系人
resolver = getContentResolver();
//addData();
// initview();
initview2();
}
private void initview() {
data = new ArrayList<>();
Iterator<AddressBook> books = AddressBook.findAll(AddressBook.class);
while (books.hasNext()) {
data.add(books.next());
}
adapter = new AddressAdapter(data, this);
listView.setAdapter(adapter);
}
public void addData() {
AddressBook book = new AddressBook("张三", "15755554444");
AddressBook book2 = new AddressBook("李四", "15733334444");
AddressBook book3 = new AddressBook("王五", "15755556666");
book.save();
book2.save();
book3.save();
}
public void initview2() {
data = new ArrayList<>();
//统一资源标识 content://contract/phones
Uri uri=ContactsContract.Contacts.CONTENT_URI;
//HAS_PHONE_NUMBER 有号码返回1 无号码返回0
String projection[]={
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
Cursor c=resolver.query(uri,projection,"has_phone_number=?",new String[]{String.valueOf(1)},null);
while(c.moveToNext()){
long id=c.getLong(0);
String name=c.getString(1);
int h=c.getInt(2);
AddressBook book=new AddressBook();
book.setName(name);
book.setId(id);
data.add(book);
}
adapter = new AddressAdapter(data, this);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 3,257 | 0.632385 | 0.618318 | 109 | 28.348623 | 21.569336 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642202 | false | false |
15
|
14431f11897dca87f3745d4fbdb7176f5f8a62f9
| 1,185,411,016,078 |
84200e758195ef4264ecc2bbad1cc8045a927bc7
|
/softstaolibrary/src/main/java/com/softstao/softstaolibrary/library/widget/NumberView.java
|
a560471b4b3179ae94d46a71f3cc66bfa6aeaaf0
|
[] |
no_license
|
stargatex/MVP-Dagger2-Retrofit-Demo
|
https://github.com/stargatex/MVP-Dagger2-Retrofit-Demo
|
12457e06b8009d4a824350ff8764d36c6ccf1ce2
|
eafb4bb375496851560f6ac1682fa3348f691c33
|
refs/heads/master
| 2020-05-15T21:45:48.221000 | 2016-11-15T06:48:16 | 2016-11-15T06:48:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.softstao.softstaolibrary.library.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.softstao.softstaolibrary.R;
/**
* Created by apple2310 on 15/4/2.
*/
public class NumberView extends LinearLayout {
private TextView decreaceView;
private EditText numberView;
private TextView increaceView;
private Context mContext;
private int number;
private OnNumberButtonClickListener listener;
public NumberView(Context context) {
super(context);
mContext = context;
initView();
}
public NumberView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initView();
}
public int getNumber() {
number = Integer.valueOf(numberView.getText().toString());
return number;
}
public void setNumber(int number) {
this.number = number;
this.numberView.setText(number + "");
}
public void setListener(OnNumberButtonClickListener listener) {
this.listener = listener;
}
private void initView() {
LayoutInflater.from(mContext).inflate(R.layout.number_layout, this, true);
decreaceView = (TextView) findViewById(R.id.decreace_btn);
decreaceView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
number = Integer.valueOf(numberView.getText().toString());
int preNumber = number;
if (number > 1) {
number--;
} else {
number = 1;
}
numberView.setText(number + "");
if (listener != null)
listener.onDecreaseButtonClick(numberView, number,preNumber);
}
});
increaceView = (TextView) findViewById(R.id.increase_btn);
increaceView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
number = Integer.valueOf(numberView.getText().toString());
number++;
numberView.setText(number + "");
if (listener != null)
listener.onIncreaseButtonClick(numberView, number);
}
});
numberView = (EditText) findViewById(R.id.number);
}
public interface OnNumberButtonClickListener {
void onDecreaseButtonClick(View view, int number, int preNumber);
void onIncreaseButtonClick(View view, int number);
}
}
|
UTF-8
|
Java
| 2,756 |
java
|
NumberView.java
|
Java
|
[
{
"context": "om.softstao.softstaolibrary.R;\n\n\n/**\n * Created by apple2310 on 15/4/2.\n */\npublic class NumberView extends Li",
"end": 351,
"score": 0.9993708729743958,
"start": 342,
"tag": "USERNAME",
"value": "apple2310"
}
] | null |
[] |
package com.softstao.softstaolibrary.library.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.softstao.softstaolibrary.R;
/**
* Created by apple2310 on 15/4/2.
*/
public class NumberView extends LinearLayout {
private TextView decreaceView;
private EditText numberView;
private TextView increaceView;
private Context mContext;
private int number;
private OnNumberButtonClickListener listener;
public NumberView(Context context) {
super(context);
mContext = context;
initView();
}
public NumberView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initView();
}
public int getNumber() {
number = Integer.valueOf(numberView.getText().toString());
return number;
}
public void setNumber(int number) {
this.number = number;
this.numberView.setText(number + "");
}
public void setListener(OnNumberButtonClickListener listener) {
this.listener = listener;
}
private void initView() {
LayoutInflater.from(mContext).inflate(R.layout.number_layout, this, true);
decreaceView = (TextView) findViewById(R.id.decreace_btn);
decreaceView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
number = Integer.valueOf(numberView.getText().toString());
int preNumber = number;
if (number > 1) {
number--;
} else {
number = 1;
}
numberView.setText(number + "");
if (listener != null)
listener.onDecreaseButtonClick(numberView, number,preNumber);
}
});
increaceView = (TextView) findViewById(R.id.increase_btn);
increaceView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
number = Integer.valueOf(numberView.getText().toString());
number++;
numberView.setText(number + "");
if (listener != null)
listener.onIncreaseButtonClick(numberView, number);
}
});
numberView = (EditText) findViewById(R.id.number);
}
public interface OnNumberButtonClickListener {
void onDecreaseButtonClick(View view, int number, int preNumber);
void onIncreaseButtonClick(View view, int number);
}
}
| 2,756 | 0.611756 | 0.608128 | 101 | 26.297029 | 23.487745 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534653 | false | false |
15
|
ad0b68a3f7ae317fce3471d6876e6d6e6db1c04e
| 1,185,411,018,890 |
3d6ec108278dcec00cb45523df7570b73374ad68
|
/Karel/Chapter 9/GoHomeBot.java
|
694e5812282e460ceb411a8d51e94f46bfa67bd0
|
[] |
no_license
|
guninvalid/labs
|
https://github.com/guninvalid/labs
|
67dcbca0ec2d989af514438db339f38bd6cf0c5b
|
a641ed0144a28c4ab27a9c191add0d78bad9b254
|
refs/heads/master
| 2021-06-28T03:24:07.151000 | 2020-10-29T03:05:59 | 2020-10-29T03:05:59 | 175,740,201 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
*
* Author:
* Date:
* Teacher:
* Lab: Racers
*
**/
import kareltherobot.*;
public class GoHomeBot extends BetterMoverRobot {
public GoHomeBot(int st, int ave, Direction dir, int beeps) {
super(st, ave, dir, beeps);
}
public void goHome() {
goToWestWall();
turnLeft();
while(!nextToABeeper()) {
move();
}
moveBackward();
}
}
|
UTF-8
|
Java
| 427 |
java
|
GoHomeBot.java
|
Java
|
[] | null |
[] |
/**
*
* Author:
* Date:
* Teacher:
* Lab: Racers
*
**/
import kareltherobot.*;
public class GoHomeBot extends BetterMoverRobot {
public GoHomeBot(int st, int ave, Direction dir, int beeps) {
super(st, ave, dir, beeps);
}
public void goHome() {
goToWestWall();
turnLeft();
while(!nextToABeeper()) {
move();
}
moveBackward();
}
}
| 427 | 0.519906 | 0.519906 | 35 | 10.2 | 13.835359 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.514286 | false | false |
15
|
668a6c729dc3d0933aa2e0e0bc107aaa98ac931e
| 24,773,371,391,420 |
ee92ef0d0ea846eb2de969a8350693a1515e900b
|
/src/main/java/Model/PartA/Parse/Text.java
|
95424a31ff834cc9c9e02fa0c431f232185b1df2
|
[] |
no_license
|
lidorav/Search-Engine-Final
|
https://github.com/lidorav/Search-Engine-Final
|
91c92847796eb0ff0040329fb15af66343ecbed0
|
e984768bfc3887856d4005107116c5591eca2b25
|
refs/heads/master
| 2020-04-09T13:29:03.265000 | 2019-01-03T17:18:44 | 2019-01-03T17:18:44 | 160,373,449 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Model.PartA.Parse;
import Model.PartA.Index.Dictionary;
/**
* Class that represent only text tokens
*/
class Text {
/**
* Converting a given token to term by uppercase or lowercase by defined conditions
* @param index the index in the token list
* @param token the text token to be converted
* @return
*/
public static String parseText(int index, String token){
token = token.replace("!","");
if(token.contains("\"") && token.length()>1)
token = token.replace("\"","");
String upperToken = token.toUpperCase();
String lowerToken = token.toLowerCase();
//check if first letter is uppercased
if(Character.isUpperCase(token.charAt(0))) {
//check if uppercased word exist in dictionary, if so return uppercased
if (Dictionary.checkExist(upperToken)||Parser.checkExist(upperToken)) {
return upperToken;
}
else {
//check if lowered cased exist in the dictionary, if so return lowercased
if (Dictionary.checkExist(lowerToken)||Parser.checkExist(lowerToken))
return lowerToken;
//if none if the cases exist = dictionary doesn't contain this word return uppercased
else
return upperToken;
}
}
else {
//check if uppercase cased exist in the dictionary, if so replace to lowercase in dictionary and return it
if (Dictionary.checkExist(upperToken)) {
Dictionary.replaceTerm(upperToken, lowerToken);
return lowerToken;
}
if (Parser.checkExist(upperToken)) {
Parser.replaceTerm(upperToken, lowerToken);
return lowerToken;
}
//check if lowered cased exist in the dictionary, if so return lowercased
//if (Dictionary.checkExist(lowerToken) || Parser.checkExist())
// return lowerToken;
//if none if the cases exist = dictionary doesn't contain this word return lowercase
//else {
return lowerToken;
//}
}
}
}
|
UTF-8
|
Java
| 2,228 |
java
|
Text.java
|
Java
|
[] | null |
[] |
package Model.PartA.Parse;
import Model.PartA.Index.Dictionary;
/**
* Class that represent only text tokens
*/
class Text {
/**
* Converting a given token to term by uppercase or lowercase by defined conditions
* @param index the index in the token list
* @param token the text token to be converted
* @return
*/
public static String parseText(int index, String token){
token = token.replace("!","");
if(token.contains("\"") && token.length()>1)
token = token.replace("\"","");
String upperToken = token.toUpperCase();
String lowerToken = token.toLowerCase();
//check if first letter is uppercased
if(Character.isUpperCase(token.charAt(0))) {
//check if uppercased word exist in dictionary, if so return uppercased
if (Dictionary.checkExist(upperToken)||Parser.checkExist(upperToken)) {
return upperToken;
}
else {
//check if lowered cased exist in the dictionary, if so return lowercased
if (Dictionary.checkExist(lowerToken)||Parser.checkExist(lowerToken))
return lowerToken;
//if none if the cases exist = dictionary doesn't contain this word return uppercased
else
return upperToken;
}
}
else {
//check if uppercase cased exist in the dictionary, if so replace to lowercase in dictionary and return it
if (Dictionary.checkExist(upperToken)) {
Dictionary.replaceTerm(upperToken, lowerToken);
return lowerToken;
}
if (Parser.checkExist(upperToken)) {
Parser.replaceTerm(upperToken, lowerToken);
return lowerToken;
}
//check if lowered cased exist in the dictionary, if so return lowercased
//if (Dictionary.checkExist(lowerToken) || Parser.checkExist())
// return lowerToken;
//if none if the cases exist = dictionary doesn't contain this word return lowercase
//else {
return lowerToken;
//}
}
}
}
| 2,228 | 0.582136 | 0.581239 | 56 | 38.785713 | 30.110342 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false |
15
|
8b856c795789eeb86140d2a0585529b5a35aff23
| 15,178,414,445,254 |
12d77015283946c2d13fd15b8a78c255d1fa5cc5
|
/src/test/java/com/telran/sheduler/tests/tests/TestBase.java
|
52eac33d5954296a875521760574535259cb9748
|
[] |
no_license
|
Svetlana-Lappo/SuperSchedule_mobileApp
|
https://github.com/Svetlana-Lappo/SuperSchedule_mobileApp
|
9d37508af037abdfd131c5256eb32dccf9d587a5
|
606024623a02263ab32d9fcf18e9ecedfaa8ccd5
|
refs/heads/main
| 2023-06-09T18:13:42.478000 | 2021-07-04T11:05:00 | 2021-07-04T11:05:00 | 381,782,293 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.telran.sheduler.tests.tests;
import com.telran.sheduler.tests.fw.ApplicationManager;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.net.MalformedURLException;
public class TestBase {
protected static ApplicationManager app = new ApplicationManager();
@BeforeMethod
public void setUp() throws MalformedURLException {
app.init();
}
@AfterMethod(enabled = false)
public void tearDown(){
app.stop();
}
}
|
UTF-8
|
Java
| 516 |
java
|
TestBase.java
|
Java
|
[] | null |
[] |
package com.telran.sheduler.tests.tests;
import com.telran.sheduler.tests.fw.ApplicationManager;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.net.MalformedURLException;
public class TestBase {
protected static ApplicationManager app = new ApplicationManager();
@BeforeMethod
public void setUp() throws MalformedURLException {
app.init();
}
@AfterMethod(enabled = false)
public void tearDown(){
app.stop();
}
}
| 516 | 0.728682 | 0.728682 | 24 | 20.5 | 21.37171 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
15
|
90a63537976438a66098e138a275c80fdb017661
| 15,178,414,445,348 |
1583a93a305000c21523e91a90341fa3b870c382
|
/lab3 AndroidSec/02 - Confused Deputy/Notes/app/src/main/java/tcs/lbs/notes/DataBaseHelper.java
|
876f631b420a2c59a9d9d186c8133b2afb1bddad
|
[] |
no_license
|
JamerryShan/Language-Based-Security
|
https://github.com/JamerryShan/Language-Based-Security
|
7bee5d1bb7c28cd7551016de35251931ad59e6fe
|
389453c4575bf1819230d0ea893e22954c6239ab
|
refs/heads/main
| 2023-07-01T07:44:56.163000 | 2021-07-22T20:27:31 | 2021-07-22T20:27:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package tcs.lbs.notes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
// just some helper functions that directly interact with the Database
public class DataBaseHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String NOTES_TABLE = "notes_table";
private static final String DATABASE_NAME = "notes.db";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note_text";
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NOTE + " TEXT)";
private SQLiteDatabase mWritableDB;
private SQLiteDatabase mReadableDB;
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(NOTES_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("onUpgrade","Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + NOTES_TABLE);
onCreate(db);
}
protected String getText(String id)
{
String text = "";
String query = "SELECT * FROM " + NOTES_TABLE + " WHERE " + KEY_ID + " = " + id;
Cursor cursor = null;
try
{
if (mReadableDB == null)
{
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.rawQuery(query, null);
}
catch (Exception e)
{
Log.d("getText", "getText EXCEPTION! " + e);
}
finally
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
text = cursor.getString(cursor.getColumnIndex(KEY_NOTE));
}
cursor.close();
}
return text;
}
protected void remove(String noteID)
{
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
mWritableDB.delete(NOTES_TABLE, KEY_ID + "=" + noteID, null);
}
catch (Exception e)
{
Log.d("Delete", "DELETE EXCEPTION! " + e.getMessage());
}
}
protected void update(String noteID, String noteText)
{
ContentValues values = new ContentValues();
values.put(KEY_NOTE, noteText);
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
mWritableDB.update(NOTES_TABLE, values, KEY_ID + "=" + noteID, null);
}
catch (Exception e)
{
Log.d("Insert", "UPDATE EXCEPTION! " + e.getMessage());
}
}
protected String insert(String noteText)
{
long rowID = 0;
ContentValues values = new ContentValues();
values.put(KEY_NOTE, noteText);
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
rowID = mWritableDB.insert(NOTES_TABLE, null, values);
}
catch (Exception e)
{
Log.d("Insert", "INSERT EXCEPTION! " + e.getMessage());
}
return String.valueOf(rowID);
}
protected ArrayList<NoteItem> getAllNotes()
{
ArrayList<NoteItem> notes = new ArrayList<>();
String query = "SELECT * FROM " + NOTES_TABLE;
Cursor cursor = null;
try
{
if (mReadableDB == null)
{
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.rawQuery(query, null);
}
catch (Exception e)
{
Log.d("getAllNotes", "getAllNotes EXCEPTION! " + e);
}
finally
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
String ID = cursor.getString(cursor.getColumnIndex(KEY_ID));
String Text = cursor.getString(cursor.getColumnIndex(KEY_NOTE));
notes.add(new NoteItem(ID, Text));
}
cursor.close();
}
return notes;
}
}
|
UTF-8
|
Java
| 4,671 |
java
|
DataBaseHelper.java
|
Java
|
[
{
"context": "tes.db\";\n\n private static final String KEY_ID = \"_id\";\n private static final String KEY_NOTE = \"not",
"end": 621,
"score": 0.9978580474853516,
"start": 617,
"tag": "KEY",
"value": "\"_id"
},
{
"context": "_id\";\n private static final String KEY_NOTE = \"note_text\";\n\n private static final String NOTES_TABLE_CR",
"end": 677,
"score": 0.9578508734703064,
"start": 668,
"tag": "KEY",
"value": "note_text"
}
] | null |
[] |
package tcs.lbs.notes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
// just some helper functions that directly interact with the Database
public class DataBaseHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String NOTES_TABLE = "notes_table";
private static final String DATABASE_NAME = "notes.db";
private static final String KEY_ID = "_id";
private static final String KEY_NOTE = "note_text";
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + KEY_NOTE + " TEXT)";
private SQLiteDatabase mWritableDB;
private SQLiteDatabase mReadableDB;
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(NOTES_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("onUpgrade","Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + NOTES_TABLE);
onCreate(db);
}
protected String getText(String id)
{
String text = "";
String query = "SELECT * FROM " + NOTES_TABLE + " WHERE " + KEY_ID + " = " + id;
Cursor cursor = null;
try
{
if (mReadableDB == null)
{
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.rawQuery(query, null);
}
catch (Exception e)
{
Log.d("getText", "getText EXCEPTION! " + e);
}
finally
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
text = cursor.getString(cursor.getColumnIndex(KEY_NOTE));
}
cursor.close();
}
return text;
}
protected void remove(String noteID)
{
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
mWritableDB.delete(NOTES_TABLE, KEY_ID + "=" + noteID, null);
}
catch (Exception e)
{
Log.d("Delete", "DELETE EXCEPTION! " + e.getMessage());
}
}
protected void update(String noteID, String noteText)
{
ContentValues values = new ContentValues();
values.put(KEY_NOTE, noteText);
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
mWritableDB.update(NOTES_TABLE, values, KEY_ID + "=" + noteID, null);
}
catch (Exception e)
{
Log.d("Insert", "UPDATE EXCEPTION! " + e.getMessage());
}
}
protected String insert(String noteText)
{
long rowID = 0;
ContentValues values = new ContentValues();
values.put(KEY_NOTE, noteText);
try
{
if (mWritableDB == null)
{
mWritableDB = getWritableDatabase();
}
rowID = mWritableDB.insert(NOTES_TABLE, null, values);
}
catch (Exception e)
{
Log.d("Insert", "INSERT EXCEPTION! " + e.getMessage());
}
return String.valueOf(rowID);
}
protected ArrayList<NoteItem> getAllNotes()
{
ArrayList<NoteItem> notes = new ArrayList<>();
String query = "SELECT * FROM " + NOTES_TABLE;
Cursor cursor = null;
try
{
if (mReadableDB == null)
{
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.rawQuery(query, null);
}
catch (Exception e)
{
Log.d("getAllNotes", "getAllNotes EXCEPTION! " + e);
}
finally
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
String ID = cursor.getString(cursor.getColumnIndex(KEY_ID));
String Text = cursor.getString(cursor.getColumnIndex(KEY_NOTE));
notes.add(new NoteItem(ID, Text));
}
cursor.close();
}
return notes;
}
}
| 4,671 | 0.549989 | 0.549561 | 177 | 25.38983 | 26.249359 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485876 | false | false |
15
|
4d3d335def2e4e921d5f03eda5d2732eec4f45fa
| 23,974,507,455,774 |
95b42ba0cb473b7495058ac8bb29300dfccef72a
|
/frame01/src/com/bit/controller/LoginController.java
|
946825132295fdf71cc7e9cd1105554993228697
|
[] |
no_license
|
Girin-jaeman/framework2020
|
https://github.com/Girin-jaeman/framework2020
|
154d02e35294b90c508907389fa8a8e0a48a8b22
|
a609edf632310d98bc0426b57c9a8ab760b51c75
|
refs/heads/master
| 2022-12-25T17:08:43.630000 | 2020-02-18T09:25:53 | 2020-02-18T09:42:37 | 238,646,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bit.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login.bit")
public class LoginController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id=req.getParameter("id");
String pw=req.getParameter("pw");
if(id.equals("admin")) {
if(pw.equals("1234")) {
resp.sendRedirect("index.jsp");
}else {
doGet(req,resp);
}
}else {
doGet(req,resp);
}
}
}
|
UTF-8
|
Java
| 929 |
java
|
LoginController.java
|
Java
|
[] | null |
[] |
package com.bit.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login.bit")
public class LoginController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id=req.getParameter("id");
String pw=req.getParameter("pw");
if(id.equals("admin")) {
if(pw.equals("1234")) {
resp.sendRedirect("index.jsp");
}else {
doGet(req,resp);
}
}else {
doGet(req,resp);
}
}
}
| 929 | 0.733046 | 0.728741 | 35 | 25.542856 | 27.057972 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.514286 | false | false |
15
|
93c18a659761df27c76f32097f48b097b9afb233
| 9,105,330,721,229 |
3fca0941c377d31adcfa6b75df683e9c8101b7f3
|
/src/线性结构/client/ClientOfTask.java
|
deee957d205aea12a068068056b14f121d5e6981
|
[] |
no_license
|
toly1994328/DS
|
https://github.com/toly1994328/DS
|
517f3b0daacae63191dd38b3c14c11e9eb9f0fd1
|
f90be364b278d173fc0809b88b05636a6a0dea22
|
refs/heads/master
| 2020-03-29T00:52:29.118000 | 2018-09-27T07:04:22 | 2018-09-27T07:04:22 | 149,360,185 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package 线性结构.client;
import Jutils.TimeTest;
import 线性结构.栈.ArrayChartStack;
import 线性结构.栈.SingleLinkedStack;
/**
* 作者:张风捷特烈
* 时间:2018/8/17 0017:14:50
* 邮箱:1981462002@qq.com
* 说明:
*/
public class ClientOfTask {
public static void main(String[] args) {
// arrayStackTest();
// linkStackTest();
int opCount = 10000000;
// 数组栈添加(opCount);
// 链表栈添加(opCount);
数组栈出栈(opCount);
链表栈出栈(opCount);
}
/////////////////////////////性能测试S//////////////////////////
private static void 链表栈添加(int opCount) {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
new TimeTest("链表栈添加", opCount) {
@Override
protected void run() {
linkedStack.push(1);
}
};
}
private static void 链表栈出栈(int opCount) {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
for (int i = 0; i < opCount; i++) {
linkedStack.push(1);
}
new TimeTest("链表栈出栈", opCount) {
@Override
protected void run() {
linkedStack.pop();
}
};
}
private static void 数组栈添加(int opCount) {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
new TimeTest("数组栈添加", opCount) {
@Override
protected void run() {
arrayChartStack.push(1);
}
};
}
private static void 数组栈出栈(int opCount) {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
for (int i = 0; i < opCount; i++) {
arrayChartStack.push(1);
}
new TimeTest("数组栈添加", opCount) {
@Override
protected void run() {
arrayChartStack.pop();
}
};
}
/////////////////////////////性能测试E//////////////////////////
/**
* 链表式集合实现的栈测试方法
*/
private static void linkStackTest() {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
for (int i = 0; i < 5; i++) {
linkedStack.push(i);
System.out.println(linkedStack);
}
linkedStack.pop();
linkedStack.pop();
Integer peek = linkedStack.peek();
System.out.println(peek);
//SingleLinkedStack Stack :head: 0->NULL
//SingleLinkedStack Stack :head: 1->0->NULL
//SingleLinkedStack Stack :head: 2->1->0->NULL
//SingleLinkedStack Stack :head: 3->2->1->0->NULL
//SingleLinkedStack Stack :head: 4->3->2->1->0->NULL
//2
}
/**
* 数组式集合实现的栈测试方法
*/
private static void arrayStackTest() {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
for (int i = 0; i < 5; i++) {
arrayChartStack.push(i);
System.out.println(arrayChartStack);
}
arrayChartStack.pop();
arrayChartStack.pop();
Integer peek = arrayChartStack.peek();
System.out.println(peek);
//Stack :[ 0] <--top
//Stack :[ 0, 1] <--top
//Stack :[ 0, 1, 2] <--top
//Stack :[ 0, 1, 2, 3] <--top
//Stack :[ 0, 1, 2, 3, 4] <--top
//2
}
}
|
UTF-8
|
Java
| 3,522 |
java
|
ClientOfTask.java
|
Java
|
[
{
"context": "tack;\nimport 线性结构.栈.SingleLinkedStack;\n\n/**\n * 作者:张风捷特烈\n * 时间:2018/8/17 0017:14:50\n * 邮箱:1981462002@qq.co",
"end": 126,
"score": 0.9996038675308228,
"start": 121,
"tag": "NAME",
"value": "张风捷特烈"
},
{
"context": "\n/**\n * 作者:张风捷特烈\n * 时间:2018/8/17 0017:14:50\n * 邮箱:1981462002@qq.com\n * 说明:\n */\npublic class ClientOfTask {\n public",
"end": 177,
"score": 0.9998318552970886,
"start": 160,
"tag": "EMAIL",
"value": "1981462002@qq.com"
}
] | null |
[] |
package 线性结构.client;
import Jutils.TimeTest;
import 线性结构.栈.ArrayChartStack;
import 线性结构.栈.SingleLinkedStack;
/**
* 作者:张风捷特烈
* 时间:2018/8/17 0017:14:50
* 邮箱:<EMAIL>
* 说明:
*/
public class ClientOfTask {
public static void main(String[] args) {
// arrayStackTest();
// linkStackTest();
int opCount = 10000000;
// 数组栈添加(opCount);
// 链表栈添加(opCount);
数组栈出栈(opCount);
链表栈出栈(opCount);
}
/////////////////////////////性能测试S//////////////////////////
private static void 链表栈添加(int opCount) {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
new TimeTest("链表栈添加", opCount) {
@Override
protected void run() {
linkedStack.push(1);
}
};
}
private static void 链表栈出栈(int opCount) {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
for (int i = 0; i < opCount; i++) {
linkedStack.push(1);
}
new TimeTest("链表栈出栈", opCount) {
@Override
protected void run() {
linkedStack.pop();
}
};
}
private static void 数组栈添加(int opCount) {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
new TimeTest("数组栈添加", opCount) {
@Override
protected void run() {
arrayChartStack.push(1);
}
};
}
private static void 数组栈出栈(int opCount) {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
for (int i = 0; i < opCount; i++) {
arrayChartStack.push(1);
}
new TimeTest("数组栈添加", opCount) {
@Override
protected void run() {
arrayChartStack.pop();
}
};
}
/////////////////////////////性能测试E//////////////////////////
/**
* 链表式集合实现的栈测试方法
*/
private static void linkStackTest() {
SingleLinkedStack<Integer> linkedStack = new SingleLinkedStack<>();
for (int i = 0; i < 5; i++) {
linkedStack.push(i);
System.out.println(linkedStack);
}
linkedStack.pop();
linkedStack.pop();
Integer peek = linkedStack.peek();
System.out.println(peek);
//SingleLinkedStack Stack :head: 0->NULL
//SingleLinkedStack Stack :head: 1->0->NULL
//SingleLinkedStack Stack :head: 2->1->0->NULL
//SingleLinkedStack Stack :head: 3->2->1->0->NULL
//SingleLinkedStack Stack :head: 4->3->2->1->0->NULL
//2
}
/**
* 数组式集合实现的栈测试方法
*/
private static void arrayStackTest() {
ArrayChartStack<Integer> arrayChartStack = new ArrayChartStack<>();
for (int i = 0; i < 5; i++) {
arrayChartStack.push(i);
System.out.println(arrayChartStack);
}
arrayChartStack.pop();
arrayChartStack.pop();
Integer peek = arrayChartStack.peek();
System.out.println(peek);
//Stack :[ 0] <--top
//Stack :[ 0, 1] <--top
//Stack :[ 0, 1, 2] <--top
//Stack :[ 0, 1, 2, 3] <--top
//Stack :[ 0, 1, 2, 3, 4] <--top
//2
}
}
| 3,512 | 0.510148 | 0.487085 | 119 | 26.32773 | 19.955879 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512605 | false | false |
15
|
9b1fce1ba2ad758cfbe50141c9fae8d0515bb03d
| 19,653,770,386,056 |
39a8b38b874738e27b622404c5074079b718bf35
|
/src/main/java/com/kinob/WebKino/WebKinoApplication.java
|
d09aa56611ba8756f398a16f19f0d2818c18e114
|
[] |
no_license
|
Nastya-Bilida/kino_java_spring
|
https://github.com/Nastya-Bilida/kino_java_spring
|
97af912a4fb74eedf0959434771d57d408887966
|
7cc651e493727c5e4e9af9bb207272e19acd0a36
|
refs/heads/master
| 2022-11-05T14:48:28.797000 | 2020-06-26T22:16:57 | 2020-06-26T22:16:57 | 275,256,530 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kinob.WebKino;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebKinoApplication {
public static void main(String[] args) {
SpringApplication.run(WebKinoApplication.class, args);
}
}
|
UTF-8
|
Java
| 312 |
java
|
WebKinoApplication.java
|
Java
|
[] | null |
[] |
package com.kinob.WebKino;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebKinoApplication {
public static void main(String[] args) {
SpringApplication.run(WebKinoApplication.class, args);
}
}
| 312 | 0.820513 | 0.820513 | 13 | 23 | 23.726 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false |
15
|
8eb2867209a886fd4f7dbd7f25f87c6eee68f13a
| 27,831,388,099,371 |
0a2680f26a9868aec40ed5f315c29d9c167a6df9
|
/src/main/java/com/hongqiang/shop/website/entity/Navigation.java
|
3b562c0ad4984bf15464cf1f9e212212384c9ba2
|
[] |
no_license
|
hongqiang/shop_format
|
https://github.com/hongqiang/shop_format
|
6c599decd6871efa1ba52ad97c64c5b46abe85ed
|
007b16447ff22e6170057ee1fe454cff63a9124d
|
refs/heads/master
| 2020-06-01T03:54:23.770000 | 2014-04-24T12:39:28 | 2014-04-24T12:39:28 | 14,840,544 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hongqiang.shop.website.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.hongqiang.shop.modules.entity.OrderEntity;
@Entity
@Table(name="hq_navigation")
public class Navigation extends OrderEntity
{
public enum Position
{
top, middle, bottom;
}
private static final long serialVersionUID = -7635757647887646795L;
private String name;
private Position position;
private String url;
private Boolean isBlankTarget;
@NotEmpty
@Length(max=200)
@Column(nullable=false)
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
@NotNull
@Column(nullable=false)
public Position getPosition()
{
return this.position;
}
public void setPosition(Position position)
{
this.position = position;
}
@NotEmpty
@Length(max=200)
@Column(nullable=false)
public String getUrl()
{
return this.url;
}
public void setUrl(String url)
{
this.url = url;
}
@NotNull
@Column(nullable=false)
public Boolean getIsBlankTarget()
{
return this.isBlankTarget;
}
public void setIsBlankTarget(Boolean isBlankTarget)
{
this.isBlankTarget = isBlankTarget;
}
}
|
UTF-8
|
Java
| 1,416 |
java
|
Navigation.java
|
Java
|
[] | null |
[] |
package com.hongqiang.shop.website.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.hongqiang.shop.modules.entity.OrderEntity;
@Entity
@Table(name="hq_navigation")
public class Navigation extends OrderEntity
{
public enum Position
{
top, middle, bottom;
}
private static final long serialVersionUID = -7635757647887646795L;
private String name;
private Position position;
private String url;
private Boolean isBlankTarget;
@NotEmpty
@Length(max=200)
@Column(nullable=false)
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
@NotNull
@Column(nullable=false)
public Position getPosition()
{
return this.position;
}
public void setPosition(Position position)
{
this.position = position;
}
@NotEmpty
@Length(max=200)
@Column(nullable=false)
public String getUrl()
{
return this.url;
}
public void setUrl(String url)
{
this.url = url;
}
@NotNull
@Column(nullable=false)
public Boolean getIsBlankTarget()
{
return this.isBlankTarget;
}
public void setIsBlankTarget(Boolean isBlankTarget)
{
this.isBlankTarget = isBlankTarget;
}
}
| 1,416 | 0.727401 | 0.709746 | 77 | 17.402597 | 16.919411 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.311688 | false | false |
15
|
2d1589fcc3e43cdca37b6c54fb661b30c794b9b7
| 26,697,516,760,677 |
ae926db9363c20a5ced3ca80f581df0a2586e766
|
/src/com/kayako/api/ticket/TicketTimeTrack.java
|
ade1a7befb71d7cb58faa3435c19a13c0c084e5d
|
[
"BSD-2-Clause-Views"
] |
permissive
|
vijayvani/kayako-java-api-library
|
https://github.com/vijayvani/kayako-java-api-library
|
886be9a8bea76c04a4729003690c789dce697e4f
|
4a704dd763e0938609f245a1cb65d37efba94c77
|
refs/heads/master
| 2020-04-15T08:48:57.089000 | 2018-04-16T19:09:08 | 2018-04-16T19:09:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.kayako.api.ticket;
/*
Copyright (c) 2013 Kayako
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import com.kayako.api.enums.ColorEnum;
import com.kayako.api.exception.KayakoException;
import com.kayako.api.rest.KEntity;
import com.kayako.api.rest.RawArrayElement;
import com.kayako.api.user.Staff;
import com.kayako.api.util.Helper;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The type Ticket time track.
*/
public class TicketTimeTrack extends KEntity {
/**
* The Controller.
*/
static protected String controller = "/Tickets/TicketTimeTrack";
/**
* The Object xml name.
*/
static protected String objectXmlName = "timetrack";
/**
* Ticket timetrack identifier.
*
* @apiField
* @var int
*/
protected int id;
/**
* Ticket identifier - if this timetrack is associated with ticket.
*
* @apiField required_create =true
* @var int
*/
protected int ticketId;
/**
* Time worked (in seconds) in this ticket time track.
*
* @apiField required_create =true alias=timespent
* @var int
*/
protected int timeWorked;
/**
* Billable time (in seconds) in this ticket time track.
*
* @apiField required_create =true
* @var int
*/
protected int timeBillable;
/**
* Bill timestamp of this ticket time track.
*
* @apiField required_create =true alias=billtimeline
* @var int
*/
protected int billDate;
/**
* Work timestamp of this ticket time track.
*
* @apiField required_create =true alias=worktimeline
* @var int
*/
protected int workDate;
/**
* Worker staff identifier.
*
* @apiField
* @var int
*/
protected int workerStaffId = 0;
/**
* Worker staff full name.
*
* @apiField
* @var string
*/
protected String workerStaffName;
/**
* Creator staff identifier.
*
* @apiField required_create =true alias=staffid
* @var int
*/
protected int creatorStaffId;
/**
* Creator staff full name.
*
* @apiField
* @var string
*/
protected String creatorStaffName;
/**
* Ticket time track note color.
*/
protected ColorEnum noteColor;
/**
* Note contents of this ticket time track.
*
* @apiField required_create =true
* @var String
*/
protected String contents;
/**
* The ticket that this time track will be connected with.
*
* @var Ticket
*/
private Ticket ticket;
/**
* Worker staff.
*
* @var Staff
*/
private Staff workerStaff = null;
/**
* Creator staff.
*
* @var Staff
*/
private Staff creatorStaff = null;
/**
* Instantiates a new Ticket time track.
*/
public TicketTimeTrack() {
}
/**
* Instantiates a new Ticket time track.
*
* @param ticket the ticket
* @param contents the contents
* @param staff the staff
* @param timeWorked the time worked
* @param timeBillable the time billable
*/
public TicketTimeTrack(Ticket ticket, String contents, Staff staff, int timeWorked, int timeBillable) {
this.setTicketId(ticket.getId()).setContents(contents).setCreatorStaffId(staff.getId());
this.setTimeWorked(timeWorked).setTimeBillable(timeBillable).setWorkerStaff(staff);
}
/**
* Instantiates a new Ticket time track.
*
* @param ticket the ticket
* @param contents the contents
* @param staff the staff
* @param timeWorked the time worked
* @param timeBillable the time billable
*/
public TicketTimeTrack(Ticket ticket, String contents, Staff staff, String timeWorked, String timeBillable) {
this.setTicketId(ticket.getId()).setContents(contents).setCreatorStaffId(staff.getId());
this.setTimeWorked(timeWorked).setTimeBillable(timeBillable).setWorkerStaff(staff);
}
public int getId() {
return id;
}
/**
* Sets id.
*
* @param id the id
* @return the id
*/
public TicketTimeTrack setId(int id) {
this.id = id;
return this;
}
@Override
public Boolean getReadOnly() {
return readOnly;
}
@Override
public TicketTimeTrack setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
/**
* Gets object xml name.
*
* @return the object xml name
*/
public static String getObjectXmlName() {
return objectXmlName;
}
/**
* Sets object xml name.
*
* @param objectXmlName the object xml name
*/
public static void setObjectXmlName(String objectXmlName) {
TicketTimeTrack.objectXmlName = objectXmlName;
}
/**
* Gets controller.
*
* @return the controller
*/
public static String getController() {
return controller;
}
/**
* Sets controller.
*
* @param controller the controller
*/
public static void setController(String controller) {
TicketTimeTrack.controller = controller;
}
/**
* Gets ticket id.
*
* @return the ticket id
*/
public int getTicketId() {
return ticketId;
}
/**
* Sets ticket id.
*
* @param ticketId the ticket id
* @return the ticket id
*/
public TicketTimeTrack setTicketId(int ticketId) {
this.ticketId = ticketId;
this.ticket = null;
return this;
}
/**
* Gets ticket.
*
* @return the ticket
* @throws com.kayako.api.exception.KayakoException
* the kayako exception
*/
public Ticket getTicket() throws KayakoException {
return this.getTicket(false);
}
/**
* Gets ticket.
*
* @param refresh the refresh
* @return the ticket
* @throws KayakoException the kayako exception
*/
public Ticket getTicket(Boolean refresh) throws KayakoException {
if (this.ticket == null || refresh) {
if (this.getTicketId() == 0) {
return null;
}
this.ticket = new Ticket().populate(get(Ticket.getController(), this.getTicketId()));
}
return ticket;
}
/**
* Sets ticket.
*
* @param ticket the ticket
* @return the ticket
*/
public TicketTimeTrack setTicket(Ticket ticket) {
this.ticket = ticket;
this.ticketId = ticket.getId();
return this;
}
/**
* Gets creator staff id.
*
* @return the creator staff id
*/
public int getCreatorStaffId() {
return creatorStaffId;
}
/**
* Sets creator staff id.
*
* @param creatorStaffId the creator staff id
* @return the creator staff id
*/
public TicketTimeTrack setCreatorStaffId(int creatorStaffId) {
this.creatorStaffId = creatorStaffId;
return this;
}
/**
* Gets creator staff name.
*
* @return the creator staff name
*/
public String getCreatorStaffName() {
return creatorStaffName;
}
/**
* Sets creator staff name.
*
* @param creatorStaffName the creator staff name
* @return the creator staff name
*/
public TicketTimeTrack setCreatorStaffName(String creatorStaffName) {
this.creatorStaffName = creatorStaffName;
return this;
}
/**
* Gets creator staff.
*
* @return the creator staff
* @throws KayakoException the kayako exception
*/
public Staff getCreatorStaff() throws KayakoException {
if (this.getCreatorStaffId() == 0) {
return null;
}
if (this.creatorStaff == null) {
this.creatorStaff = (Staff) Staff.get(this.getCreatorStaffId());
}
return this.creatorStaff;
}
/**
* Sets creator staff.
*
* @param creatorStaff the creator staff
* @return the creator staff
*/
public TicketTimeTrack setCreatorStaff(Staff creatorStaff) {
this.creatorStaff = creatorStaff;
this.setCreatorStaffId(creatorStaff.getId());
this.setCreatorStaffName(creatorStaff.getFullName());
return this;
}
/**
* Gets time worked.
*
* @return the time worked
*/
public int getTimeWorked() {
return timeWorked;
}
/**
* Sets time worked.
*
* @param timeWorked the time worked
* @return the time worked
*/
public TicketTimeTrack setTimeWorked(int timeWorked) {
this.timeWorked = timeWorked;
return this;
}
/**
* Sets time worked.
*
* @param timeWorked the time worked
* @return the time worked
*/
public TicketTimeTrack setTimeWorked(String timeWorked) {
this.setTimeWorked(stringToSeconds(timeWorked));
return this;
}
//input String as "12:10" (hh:mm)
private static int stringToSeconds(String timeWorked) {
String[] timeArray = timeWorked.split(":");
return (Helper.parseInt(timeArray[0]) * 60 * 60) + (Helper.parseInt(timeArray[1]) * 60);
}
/**
* Gets time billable.
*
* @return the time billable
*/
public int getTimeBillable() {
return timeBillable;
}
/**
* Sets time billable.
*
* @param timeBillable the time billable
* @return the time billable
*/
public TicketTimeTrack setTimeBillable(int timeBillable) {
this.timeBillable = timeBillable;
return this;
}
/**
* Sets time billable.
*
* @param time the time
* @return the time billable
*/
public TicketTimeTrack setTimeBillable(String time) {
this.setTimeBillable(stringToSeconds(time));
return this;
}
/**
* Gets bill date.
*
* @return the bill date
*/
public int getBillDate() {
return billDate;
}
/**
* Sets bill date.
*
* @param billDate the bill date
* @return the bill date
*/
public TicketTimeTrack setBillDate(int billDate) {
this.billDate = billDate;
return this;
}
/**
* Gets work date.
*
* @return the work date
*/
public int getWorkDate() {
return workDate;
}
/**
* Sets work date.
*
* @param workDate the work date
* @return the work date
*/
public TicketTimeTrack setWorkDate(int workDate) {
this.workDate = workDate;
return this;
}
/**
* Gets worker staff id.
*
* @return the worker staff id
*/
public int getWorkerStaffId() {
return workerStaffId;
}
/**
* Sets worker staff id.
*
* @param workerStaffId the worker staff id
* @return the worker staff id
*/
public TicketTimeTrack setWorkerStaffId(int workerStaffId) {
this.workerStaffId = workerStaffId;
this.workerStaff = null;
return this;
}
/**
* Gets worker staff name.
*
* @return the worker staff name
*/
public String getWorkerStaffName() {
return workerStaffName;
}
/**
* Sets worker staff name.
*
* @param workerStaffName the worker staff name
* @return the worker staff name
*/
public TicketTimeTrack setWorkerStaffName(String workerStaffName) {
this.workerStaffName = workerStaffName;
return this;
}
/**
* Gets note color.
*
* @return the note color
*/
public ColorEnum getNoteColor() {
return noteColor;
}
/**
* Sets note color.
*
* @param noteColor the note color
* @return the note color
*/
public TicketTimeTrack setNoteColor(ColorEnum noteColor) {
this.noteColor = noteColor;
return this;
}
/**
* Gets contents.
*
* @return the contents
*/
public String getContents() {
return contents;
}
/**
* Sets contents.
*
* @param contents the contents
* @return the contents
*/
public TicketTimeTrack setContents(String contents) {
this.contents = contents;
return this;
}
/**
* Gets worker staff.
*
* @return the worker staff
* @throws KayakoException the kayako exception
*/
public Staff getWorkerStaff() throws KayakoException {
return this.getWorkerStaff(false);
}
/**
* Gets worker staff.
*
* @param refresh the refresh
* @return the worker staff
* @throws KayakoException the kayako exception
*/
public Staff getWorkerStaff(Boolean refresh) throws KayakoException {
if (this.workerStaff == null || refresh) {
this.workerStaff = Staff.get(this.getWorkerStaffId());
this.setWorkerStaffName(this.workerStaff.getFullName());
}
return workerStaff;
}
/**
* Sets worker staff.
*
* @param workerStaff the worker staff
* @return the worker staff
*/
public TicketTimeTrack setWorkerStaff(Staff workerStaff) {
this.workerStaff = workerStaff;
this.setWorkerStaffId(workerStaff.getId());
return this;
}
/**
* Gets all.
*
* @param ticketId the ticket id
* @return the all
*/
public static RawArrayElement getAll(int ticketId) {
ArrayList<String> searchParams = new ArrayList<String>();
searchParams.add("ListAll");
searchParams.add(Integer.toString(ticketId));
return getAll(controller, searchParams);
}
private static ArrayList<TicketTimeTrack> refineToArray(RawArrayElement element) throws KayakoException {
ArrayList<TicketTimeTrack> TicketTimeTracks = new ArrayList<TicketTimeTrack>();
for (RawArrayElement rawArrayElementTicketTimeTrack : element.getComponents()) {
TicketTimeTracks.add(new TicketTimeTrack().populate(rawArrayElementTicketTimeTrack));
}
return TicketTimeTracks;
}
/**
* Gets all time tracks.
*
* @param ticketId the ticket id
* @return the all time tracks
* @throws KayakoException the kayako exception
*/
public static ArrayList<TicketTimeTrack> getAllTimeTracks(int ticketId) throws KayakoException {
return refineToArray(getAll(ticketId));
}
/**
* Get ticket time track.
*
* @param ticketId the ticket id
* @param id the id
* @return the ticket time track
* @throws KayakoException the kayako exception
*/
public static TicketTimeTrack get(int ticketId, int id) throws KayakoException {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(Integer.toString(ticketId));
arrayList.add(Integer.toString(id));
return new TicketTimeTrack().populate(get(controller, arrayList));
}
@Override
public KEntity update(String controller) throws KayakoException {
throw new KayakoException("This method is not available on this type of objects.");
}
/**
* Create ticket time track.
*
* @return the ticket time track
* @throws KayakoException the kayako exception
*/
public TicketTimeTrack create() throws KayakoException {
return (TicketTimeTrack) super.create(controller);
}
//this function will populate the data of the ticket time track instance when supplied with RawArrayElement derived from the xml
@Override
public TicketTimeTrack populate(RawArrayElement element) throws KayakoException {
if (!element.getElementName().equals(objectXmlName)) {
throw new KayakoException();
}
this.setId(Helper.parseInt(element.getAttribute("id"))).setTicketId(Helper.parseInt(element.getAttribute("ticketid")));
this.setTimeWorked(Helper.parseInt(element.getAttribute("timeworked"))).setTimeBillable(Helper.parseInt(element.getAttribute("timebillable")));
this.setBillDate(Helper.parseInt(element.getAttribute("billdate"))).setWorkDate(Helper.parseInt(element.getAttribute("workdate")));
this.setNoteColor(ColorEnum.getEnum(element.getAttribute("notecolor")));
this.setCreatorStaffName(element.getAttribute("creatorstaffname")).setCreatorStaffId(Helper.parseInt(element.getAttribute("creatorstaffid")));
this.setWorkerStaffName(element.getAttribute("workerstaffname")).setWorkerStaffId(Helper.parseInt(element.getAttribute("workerstaffid")));
this.setContents(element.getContent());
return this;
}
public HashMap<String, String> buildHashMap() {
return buildHashMap(false);
}
/**
* Build hash map.
*
* @param newTicketTimeTrack the new ticket time track
* @return the hash map
*/
public HashMap<String, String> buildHashMap(Boolean newTicketTimeTrack) {
HashMap<String, String> ticketTimeTrackHashMap = new HashMap<String, String>();
ticketTimeTrackHashMap.put("ticketid", Integer.toString(this.getTicketId()));
ticketTimeTrackHashMap.put("staffid", Integer.toString(this.getCreatorStaffId()));
ticketTimeTrackHashMap.put("contents", this.getContents());
ticketTimeTrackHashMap.put("worktimeline", Integer.toString(this.getWorkDate()));
ticketTimeTrackHashMap.put("billtimeline", Integer.toString(this.getBillDate()));
ticketTimeTrackHashMap.put("timespent", Integer.toString(this.getTimeWorked()));
ticketTimeTrackHashMap.put("timebillable", Integer.toString(this.getTimeBillable()));
if (this.getWorkerStaffId() != 0) {
ticketTimeTrackHashMap.put("workerstaffid", Integer.toString(this.getWorkerStaffId()));
}
ticketTimeTrackHashMap.put("notecolor", this.getNoteColor().getString());
return ticketTimeTrackHashMap;
}
@Override
public String toString() {
return super.toString();
}
/**
* Get raw array element.
*
* @param controller the controller
* @param parameters ArrayList of Parameters (TicketID and TicketTimeTrackID)
* @return the raw array element
* @throws KayakoException the kayako exception
*/
public static RawArrayElement get(String controller, ArrayList<String> parameters) throws KayakoException {
return KEntity.getRESTClient().get(controller, parameters).getFirstComponent();
}
}
|
UTF-8
|
Java
| 19,626 |
java
|
TicketTimeTrack.java
|
Java
|
[
{
"context": "kage com.kayako.api.ticket;\n\n/*\nCopyright (c) 2013 Kayako\n\nPermission is hereby granted, free of charge,",
"end": 57,
"score": 0.5963864326477051,
"start": 54,
"tag": "NAME",
"value": "Kay"
},
{
"context": " com.kayako.api.ticket;\n\n/*\nCopyright (c) 2013 Kayako\n\nPermission is hereby granted, free of charge, to",
"end": 60,
"score": 0.6443750858306885,
"start": 57,
"tag": "USERNAME",
"value": "ako"
}
] | null |
[] |
package com.kayako.api.ticket;
/*
Copyright (c) 2013 Kayako
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
import com.kayako.api.enums.ColorEnum;
import com.kayako.api.exception.KayakoException;
import com.kayako.api.rest.KEntity;
import com.kayako.api.rest.RawArrayElement;
import com.kayako.api.user.Staff;
import com.kayako.api.util.Helper;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The type Ticket time track.
*/
public class TicketTimeTrack extends KEntity {
/**
* The Controller.
*/
static protected String controller = "/Tickets/TicketTimeTrack";
/**
* The Object xml name.
*/
static protected String objectXmlName = "timetrack";
/**
* Ticket timetrack identifier.
*
* @apiField
* @var int
*/
protected int id;
/**
* Ticket identifier - if this timetrack is associated with ticket.
*
* @apiField required_create =true
* @var int
*/
protected int ticketId;
/**
* Time worked (in seconds) in this ticket time track.
*
* @apiField required_create =true alias=timespent
* @var int
*/
protected int timeWorked;
/**
* Billable time (in seconds) in this ticket time track.
*
* @apiField required_create =true
* @var int
*/
protected int timeBillable;
/**
* Bill timestamp of this ticket time track.
*
* @apiField required_create =true alias=billtimeline
* @var int
*/
protected int billDate;
/**
* Work timestamp of this ticket time track.
*
* @apiField required_create =true alias=worktimeline
* @var int
*/
protected int workDate;
/**
* Worker staff identifier.
*
* @apiField
* @var int
*/
protected int workerStaffId = 0;
/**
* Worker staff full name.
*
* @apiField
* @var string
*/
protected String workerStaffName;
/**
* Creator staff identifier.
*
* @apiField required_create =true alias=staffid
* @var int
*/
protected int creatorStaffId;
/**
* Creator staff full name.
*
* @apiField
* @var string
*/
protected String creatorStaffName;
/**
* Ticket time track note color.
*/
protected ColorEnum noteColor;
/**
* Note contents of this ticket time track.
*
* @apiField required_create =true
* @var String
*/
protected String contents;
/**
* The ticket that this time track will be connected with.
*
* @var Ticket
*/
private Ticket ticket;
/**
* Worker staff.
*
* @var Staff
*/
private Staff workerStaff = null;
/**
* Creator staff.
*
* @var Staff
*/
private Staff creatorStaff = null;
/**
* Instantiates a new Ticket time track.
*/
public TicketTimeTrack() {
}
/**
* Instantiates a new Ticket time track.
*
* @param ticket the ticket
* @param contents the contents
* @param staff the staff
* @param timeWorked the time worked
* @param timeBillable the time billable
*/
public TicketTimeTrack(Ticket ticket, String contents, Staff staff, int timeWorked, int timeBillable) {
this.setTicketId(ticket.getId()).setContents(contents).setCreatorStaffId(staff.getId());
this.setTimeWorked(timeWorked).setTimeBillable(timeBillable).setWorkerStaff(staff);
}
/**
* Instantiates a new Ticket time track.
*
* @param ticket the ticket
* @param contents the contents
* @param staff the staff
* @param timeWorked the time worked
* @param timeBillable the time billable
*/
public TicketTimeTrack(Ticket ticket, String contents, Staff staff, String timeWorked, String timeBillable) {
this.setTicketId(ticket.getId()).setContents(contents).setCreatorStaffId(staff.getId());
this.setTimeWorked(timeWorked).setTimeBillable(timeBillable).setWorkerStaff(staff);
}
public int getId() {
return id;
}
/**
* Sets id.
*
* @param id the id
* @return the id
*/
public TicketTimeTrack setId(int id) {
this.id = id;
return this;
}
@Override
public Boolean getReadOnly() {
return readOnly;
}
@Override
public TicketTimeTrack setReadOnly(Boolean readOnly) {
this.readOnly = readOnly;
return this;
}
/**
* Gets object xml name.
*
* @return the object xml name
*/
public static String getObjectXmlName() {
return objectXmlName;
}
/**
* Sets object xml name.
*
* @param objectXmlName the object xml name
*/
public static void setObjectXmlName(String objectXmlName) {
TicketTimeTrack.objectXmlName = objectXmlName;
}
/**
* Gets controller.
*
* @return the controller
*/
public static String getController() {
return controller;
}
/**
* Sets controller.
*
* @param controller the controller
*/
public static void setController(String controller) {
TicketTimeTrack.controller = controller;
}
/**
* Gets ticket id.
*
* @return the ticket id
*/
public int getTicketId() {
return ticketId;
}
/**
* Sets ticket id.
*
* @param ticketId the ticket id
* @return the ticket id
*/
public TicketTimeTrack setTicketId(int ticketId) {
this.ticketId = ticketId;
this.ticket = null;
return this;
}
/**
* Gets ticket.
*
* @return the ticket
* @throws com.kayako.api.exception.KayakoException
* the kayako exception
*/
public Ticket getTicket() throws KayakoException {
return this.getTicket(false);
}
/**
* Gets ticket.
*
* @param refresh the refresh
* @return the ticket
* @throws KayakoException the kayako exception
*/
public Ticket getTicket(Boolean refresh) throws KayakoException {
if (this.ticket == null || refresh) {
if (this.getTicketId() == 0) {
return null;
}
this.ticket = new Ticket().populate(get(Ticket.getController(), this.getTicketId()));
}
return ticket;
}
/**
* Sets ticket.
*
* @param ticket the ticket
* @return the ticket
*/
public TicketTimeTrack setTicket(Ticket ticket) {
this.ticket = ticket;
this.ticketId = ticket.getId();
return this;
}
/**
* Gets creator staff id.
*
* @return the creator staff id
*/
public int getCreatorStaffId() {
return creatorStaffId;
}
/**
* Sets creator staff id.
*
* @param creatorStaffId the creator staff id
* @return the creator staff id
*/
public TicketTimeTrack setCreatorStaffId(int creatorStaffId) {
this.creatorStaffId = creatorStaffId;
return this;
}
/**
* Gets creator staff name.
*
* @return the creator staff name
*/
public String getCreatorStaffName() {
return creatorStaffName;
}
/**
* Sets creator staff name.
*
* @param creatorStaffName the creator staff name
* @return the creator staff name
*/
public TicketTimeTrack setCreatorStaffName(String creatorStaffName) {
this.creatorStaffName = creatorStaffName;
return this;
}
/**
* Gets creator staff.
*
* @return the creator staff
* @throws KayakoException the kayako exception
*/
public Staff getCreatorStaff() throws KayakoException {
if (this.getCreatorStaffId() == 0) {
return null;
}
if (this.creatorStaff == null) {
this.creatorStaff = (Staff) Staff.get(this.getCreatorStaffId());
}
return this.creatorStaff;
}
/**
* Sets creator staff.
*
* @param creatorStaff the creator staff
* @return the creator staff
*/
public TicketTimeTrack setCreatorStaff(Staff creatorStaff) {
this.creatorStaff = creatorStaff;
this.setCreatorStaffId(creatorStaff.getId());
this.setCreatorStaffName(creatorStaff.getFullName());
return this;
}
/**
* Gets time worked.
*
* @return the time worked
*/
public int getTimeWorked() {
return timeWorked;
}
/**
* Sets time worked.
*
* @param timeWorked the time worked
* @return the time worked
*/
public TicketTimeTrack setTimeWorked(int timeWorked) {
this.timeWorked = timeWorked;
return this;
}
/**
* Sets time worked.
*
* @param timeWorked the time worked
* @return the time worked
*/
public TicketTimeTrack setTimeWorked(String timeWorked) {
this.setTimeWorked(stringToSeconds(timeWorked));
return this;
}
//input String as "12:10" (hh:mm)
private static int stringToSeconds(String timeWorked) {
String[] timeArray = timeWorked.split(":");
return (Helper.parseInt(timeArray[0]) * 60 * 60) + (Helper.parseInt(timeArray[1]) * 60);
}
/**
* Gets time billable.
*
* @return the time billable
*/
public int getTimeBillable() {
return timeBillable;
}
/**
* Sets time billable.
*
* @param timeBillable the time billable
* @return the time billable
*/
public TicketTimeTrack setTimeBillable(int timeBillable) {
this.timeBillable = timeBillable;
return this;
}
/**
* Sets time billable.
*
* @param time the time
* @return the time billable
*/
public TicketTimeTrack setTimeBillable(String time) {
this.setTimeBillable(stringToSeconds(time));
return this;
}
/**
* Gets bill date.
*
* @return the bill date
*/
public int getBillDate() {
return billDate;
}
/**
* Sets bill date.
*
* @param billDate the bill date
* @return the bill date
*/
public TicketTimeTrack setBillDate(int billDate) {
this.billDate = billDate;
return this;
}
/**
* Gets work date.
*
* @return the work date
*/
public int getWorkDate() {
return workDate;
}
/**
* Sets work date.
*
* @param workDate the work date
* @return the work date
*/
public TicketTimeTrack setWorkDate(int workDate) {
this.workDate = workDate;
return this;
}
/**
* Gets worker staff id.
*
* @return the worker staff id
*/
public int getWorkerStaffId() {
return workerStaffId;
}
/**
* Sets worker staff id.
*
* @param workerStaffId the worker staff id
* @return the worker staff id
*/
public TicketTimeTrack setWorkerStaffId(int workerStaffId) {
this.workerStaffId = workerStaffId;
this.workerStaff = null;
return this;
}
/**
* Gets worker staff name.
*
* @return the worker staff name
*/
public String getWorkerStaffName() {
return workerStaffName;
}
/**
* Sets worker staff name.
*
* @param workerStaffName the worker staff name
* @return the worker staff name
*/
public TicketTimeTrack setWorkerStaffName(String workerStaffName) {
this.workerStaffName = workerStaffName;
return this;
}
/**
* Gets note color.
*
* @return the note color
*/
public ColorEnum getNoteColor() {
return noteColor;
}
/**
* Sets note color.
*
* @param noteColor the note color
* @return the note color
*/
public TicketTimeTrack setNoteColor(ColorEnum noteColor) {
this.noteColor = noteColor;
return this;
}
/**
* Gets contents.
*
* @return the contents
*/
public String getContents() {
return contents;
}
/**
* Sets contents.
*
* @param contents the contents
* @return the contents
*/
public TicketTimeTrack setContents(String contents) {
this.contents = contents;
return this;
}
/**
* Gets worker staff.
*
* @return the worker staff
* @throws KayakoException the kayako exception
*/
public Staff getWorkerStaff() throws KayakoException {
return this.getWorkerStaff(false);
}
/**
* Gets worker staff.
*
* @param refresh the refresh
* @return the worker staff
* @throws KayakoException the kayako exception
*/
public Staff getWorkerStaff(Boolean refresh) throws KayakoException {
if (this.workerStaff == null || refresh) {
this.workerStaff = Staff.get(this.getWorkerStaffId());
this.setWorkerStaffName(this.workerStaff.getFullName());
}
return workerStaff;
}
/**
* Sets worker staff.
*
* @param workerStaff the worker staff
* @return the worker staff
*/
public TicketTimeTrack setWorkerStaff(Staff workerStaff) {
this.workerStaff = workerStaff;
this.setWorkerStaffId(workerStaff.getId());
return this;
}
/**
* Gets all.
*
* @param ticketId the ticket id
* @return the all
*/
public static RawArrayElement getAll(int ticketId) {
ArrayList<String> searchParams = new ArrayList<String>();
searchParams.add("ListAll");
searchParams.add(Integer.toString(ticketId));
return getAll(controller, searchParams);
}
private static ArrayList<TicketTimeTrack> refineToArray(RawArrayElement element) throws KayakoException {
ArrayList<TicketTimeTrack> TicketTimeTracks = new ArrayList<TicketTimeTrack>();
for (RawArrayElement rawArrayElementTicketTimeTrack : element.getComponents()) {
TicketTimeTracks.add(new TicketTimeTrack().populate(rawArrayElementTicketTimeTrack));
}
return TicketTimeTracks;
}
/**
* Gets all time tracks.
*
* @param ticketId the ticket id
* @return the all time tracks
* @throws KayakoException the kayako exception
*/
public static ArrayList<TicketTimeTrack> getAllTimeTracks(int ticketId) throws KayakoException {
return refineToArray(getAll(ticketId));
}
/**
* Get ticket time track.
*
* @param ticketId the ticket id
* @param id the id
* @return the ticket time track
* @throws KayakoException the kayako exception
*/
public static TicketTimeTrack get(int ticketId, int id) throws KayakoException {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(Integer.toString(ticketId));
arrayList.add(Integer.toString(id));
return new TicketTimeTrack().populate(get(controller, arrayList));
}
@Override
public KEntity update(String controller) throws KayakoException {
throw new KayakoException("This method is not available on this type of objects.");
}
/**
* Create ticket time track.
*
* @return the ticket time track
* @throws KayakoException the kayako exception
*/
public TicketTimeTrack create() throws KayakoException {
return (TicketTimeTrack) super.create(controller);
}
//this function will populate the data of the ticket time track instance when supplied with RawArrayElement derived from the xml
@Override
public TicketTimeTrack populate(RawArrayElement element) throws KayakoException {
if (!element.getElementName().equals(objectXmlName)) {
throw new KayakoException();
}
this.setId(Helper.parseInt(element.getAttribute("id"))).setTicketId(Helper.parseInt(element.getAttribute("ticketid")));
this.setTimeWorked(Helper.parseInt(element.getAttribute("timeworked"))).setTimeBillable(Helper.parseInt(element.getAttribute("timebillable")));
this.setBillDate(Helper.parseInt(element.getAttribute("billdate"))).setWorkDate(Helper.parseInt(element.getAttribute("workdate")));
this.setNoteColor(ColorEnum.getEnum(element.getAttribute("notecolor")));
this.setCreatorStaffName(element.getAttribute("creatorstaffname")).setCreatorStaffId(Helper.parseInt(element.getAttribute("creatorstaffid")));
this.setWorkerStaffName(element.getAttribute("workerstaffname")).setWorkerStaffId(Helper.parseInt(element.getAttribute("workerstaffid")));
this.setContents(element.getContent());
return this;
}
public HashMap<String, String> buildHashMap() {
return buildHashMap(false);
}
/**
* Build hash map.
*
* @param newTicketTimeTrack the new ticket time track
* @return the hash map
*/
public HashMap<String, String> buildHashMap(Boolean newTicketTimeTrack) {
HashMap<String, String> ticketTimeTrackHashMap = new HashMap<String, String>();
ticketTimeTrackHashMap.put("ticketid", Integer.toString(this.getTicketId()));
ticketTimeTrackHashMap.put("staffid", Integer.toString(this.getCreatorStaffId()));
ticketTimeTrackHashMap.put("contents", this.getContents());
ticketTimeTrackHashMap.put("worktimeline", Integer.toString(this.getWorkDate()));
ticketTimeTrackHashMap.put("billtimeline", Integer.toString(this.getBillDate()));
ticketTimeTrackHashMap.put("timespent", Integer.toString(this.getTimeWorked()));
ticketTimeTrackHashMap.put("timebillable", Integer.toString(this.getTimeBillable()));
if (this.getWorkerStaffId() != 0) {
ticketTimeTrackHashMap.put("workerstaffid", Integer.toString(this.getWorkerStaffId()));
}
ticketTimeTrackHashMap.put("notecolor", this.getNoteColor().getString());
return ticketTimeTrackHashMap;
}
@Override
public String toString() {
return super.toString();
}
/**
* Get raw array element.
*
* @param controller the controller
* @param parameters ArrayList of Parameters (TicketID and TicketTimeTrackID)
* @return the raw array element
* @throws KayakoException the kayako exception
*/
public static RawArrayElement get(String controller, ArrayList<String> parameters) throws KayakoException {
return KEntity.getRESTClient().get(controller, parameters).getFirstComponent();
}
}
| 19,626 | 0.623917 | 0.622898 | 742 | 25.450134 | 25.715782 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25876 | false | false |
15
|
2a990d003654360633566326e22d888d54d52c85
| 3,393,024,193,112 |
1fbbb281a217f18dd7e523b97d74aceccc6177d3
|
/libs/marmotta-worker/src/test/java/at/newmedialab/lmf/worker/test/MockWorkerRuntime.java
|
a6e970a8345d212934c26c0a2afeeeb3937e09c6
|
[
"Apache-2.0"
] |
permissive
|
nimble-platform/catalog-service-backend
|
https://github.com/nimble-platform/catalog-service-backend
|
604cde5f5b13cead469491543650ba9129735562
|
87f4d6e1628b5b271774956fe0217a9e2645bc18
|
refs/heads/master
| 2022-10-20T10:29:09.253000 | 2022-02-10T13:45:43 | 2022-02-10T13:45:43 | 82,173,338 | 2 | 3 |
Apache-2.0
| false | 2023-04-18T22:41:45 | 2017-02-16T11:24:53 | 2022-05-15T12:43:55 | 2023-04-18T22:41:41 | 2,558 | 2 | 2 | 14 |
Java
| false | false |
package at.newmedialab.lmf.worker.test;
import at.newmedialab.lmf.worker.model.WorkerConfiguration;
import at.newmedialab.lmf.worker.services.WorkerRuntime;
import org.apache.marmotta.platform.core.api.task.TaskManagerService;
import org.openrdf.model.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Add file description here!
*
* @author Sebastian Schaffert (sschaffert@apache.org)
*/
public class MockWorkerRuntime extends WorkerRuntime<MockWorkerConfiguration> {
private List<String> processed = new ArrayList<String>();
public MockWorkerRuntime(MockWorkerConfiguration config) {
super(config);
}
@Override
protected void execute(Resource resource) {
processed.add(resource.stringValue());
}
@Override
protected TaskManagerService getTaskManagerService() {
return new MockTaskManagerService();
}
public List<String> getProcessed() {
return processed;
}
}
|
UTF-8
|
Java
| 965 |
java
|
MockWorkerRuntime.java
|
Java
|
[
{
"context": ";\n\n/**\n * Add file description here!\n *\n * @author Sebastian Schaffert (sschaffert@apache.org)\n */\npublic class MockWork",
"end": 383,
"score": 0.9998705983161926,
"start": 364,
"tag": "NAME",
"value": "Sebastian Schaffert"
},
{
"context": "cription here!\n *\n * @author Sebastian Schaffert (sschaffert@apache.org)\n */\npublic class MockWorkerRuntime extends Worke",
"end": 406,
"score": 0.9999308586120605,
"start": 385,
"tag": "EMAIL",
"value": "sschaffert@apache.org"
}
] | null |
[] |
package at.newmedialab.lmf.worker.test;
import at.newmedialab.lmf.worker.model.WorkerConfiguration;
import at.newmedialab.lmf.worker.services.WorkerRuntime;
import org.apache.marmotta.platform.core.api.task.TaskManagerService;
import org.openrdf.model.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Add file description here!
*
* @author <NAME> (<EMAIL>)
*/
public class MockWorkerRuntime extends WorkerRuntime<MockWorkerConfiguration> {
private List<String> processed = new ArrayList<String>();
public MockWorkerRuntime(MockWorkerConfiguration config) {
super(config);
}
@Override
protected void execute(Resource resource) {
processed.add(resource.stringValue());
}
@Override
protected TaskManagerService getTaskManagerService() {
return new MockTaskManagerService();
}
public List<String> getProcessed() {
return processed;
}
}
| 938 | 0.737824 | 0.737824 | 37 | 25.081081 | 24.577927 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324324 | false | false |
15
|
a52895f88cb1a367a37415d6e9d66cfe1f5870e3
| 35,107,062,681,495 |
a826bdb3ef985aeca67d93925b71f1b25cdb16a1
|
/src/com/mr_faton/panel/SouthPanel.java
|
c1b3884e173569269ff3a294dc86d14697b6abed
|
[] |
no_license
|
MrFaton/PhotoSorter_Project
|
https://github.com/MrFaton/PhotoSorter_Project
|
e3c453adc682a9fd501b8775471e74b16d20491d
|
b82ea5f00c1ad630a3ee2a5f3ffc289637654556
|
refs/heads/master
| 2021-01-19T07:57:24.109000 | 2015-05-11T19:20:09 | 2015-05-11T19:20:09 | 35,015,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mr_faton.panel;
import com.mr_faton.handler.HandleButtonHandler;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Mr_Faton on 04.05.2015.
*/
public class SouthPanel {
private static SouthPanel southPanel;
private JPanel panel;
private JButton handleButton;
private JProgressBar progressBar;
public static SouthPanel getInstance() {
if (southPanel == null) {
southPanel = new SouthPanel();
}
return southPanel;
}
private SouthPanel() {
panel = new JPanel();
panel.setLayout(new GridLayout(2, 1, 0, 10));
Border progressBorder = BorderFactory.createTitledBorder("Прогресс обработки");
progressBar = new JProgressBar();
progressBar.setBorder(progressBorder);
progressBar.setStringPainted(true);//для отображения прогресса числом
progressBar.setVisible(false);//чтобы при старте был невидимым
handleButton = new JButton("Обработать");
handleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
HandleButtonHandler handleButtonHandler = new HandleButtonHandler();
handleButtonHandler.handle();
}
}).start();
}
});
//если сделать так, то кнопка не будет растянутой
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(handleButton);
panel.add(progressBar);
panel.add(handleButton);
// panel.add(buttonPanel);//добавляет на панель новую панель, всё для того же, чтобы не была растянута кнопка
}
public void setProgressBarVisible(boolean isVisible) {
progressBar.setVisible(isVisible);
}
public void setProgressBarValue(int value) {
progressBar.setValue(value);
}
public void clickableHandleButton(boolean isClickable) {
handleButton.setEnabled(isClickable);
}
public JPanel getPanel() {
return panel;
}
}
|
UTF-8
|
Java
| 2,472 |
java
|
SouthPanel.java
|
Java
|
[
{
"context": " java.awt.event.ActionListener;\n\n/**\n * Created by Mr_Faton on 04.05.2015.\n */\npublic class SouthPanel {\n ",
"end": 254,
"score": 0.9995846152305603,
"start": 246,
"tag": "USERNAME",
"value": "Mr_Faton"
}
] | null |
[] |
package com.mr_faton.panel;
import com.mr_faton.handler.HandleButtonHandler;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Mr_Faton on 04.05.2015.
*/
public class SouthPanel {
private static SouthPanel southPanel;
private JPanel panel;
private JButton handleButton;
private JProgressBar progressBar;
public static SouthPanel getInstance() {
if (southPanel == null) {
southPanel = new SouthPanel();
}
return southPanel;
}
private SouthPanel() {
panel = new JPanel();
panel.setLayout(new GridLayout(2, 1, 0, 10));
Border progressBorder = BorderFactory.createTitledBorder("Прогресс обработки");
progressBar = new JProgressBar();
progressBar.setBorder(progressBorder);
progressBar.setStringPainted(true);//для отображения прогресса числом
progressBar.setVisible(false);//чтобы при старте был невидимым
handleButton = new JButton("Обработать");
handleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
@Override
public void run() {
HandleButtonHandler handleButtonHandler = new HandleButtonHandler();
handleButtonHandler.handle();
}
}).start();
}
});
//если сделать так, то кнопка не будет растянутой
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(handleButton);
panel.add(progressBar);
panel.add(handleButton);
// panel.add(buttonPanel);//добавляет на панель новую панель, всё для того же, чтобы не была растянута кнопка
}
public void setProgressBarVisible(boolean isVisible) {
progressBar.setVisible(isVisible);
}
public void setProgressBarValue(int value) {
progressBar.setValue(value);
}
public void clickableHandleButton(boolean isClickable) {
handleButton.setEnabled(isClickable);
}
public JPanel getPanel() {
return panel;
}
}
| 2,472 | 0.63326 | 0.627571 | 74 | 29.878378 | 24.634602 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false |
15
|
6c396c687366f0da49fc48dbded70ada3b2dacf1
| 15,831,249,480,814 |
a1f248670f307a3b19e7fd06d33d208855cf197b
|
/org.aion.avm.core/src/org/aion/avm/core/util/SoftCache.java
|
f413e60a870bf7cc35ae4cce6615bd0c557d0e87
|
[
"MIT"
] |
permissive
|
fulldecent/AVM
|
https://github.com/fulldecent/AVM
|
748b16116273c7b39c494901a2c4b0affde65ee3
|
cd2e8d4fbe5b5098a74486a23bb45107f3b39912
|
refs/heads/master
| 2020-06-03T15:36:39.481000 | 2019-06-04T19:31:48 | 2019-06-12T18:29:30 | 191,631,334 | 0 | 1 | null | true | 2019-06-12T19:20:45 | 2019-06-12T19:20:45 | 2019-06-12T18:47:19 | 2019-06-12T19:09:23 | 10,982 | 0 | 0 | 0 | null | false | false |
package org.aion.avm.core.util;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import i.RuntimeAssertionError;
/**
* A simple concurrent cache, based on SoftReferences. There is currently no maximum size.
* NOTE: Keys in this implementation are NOT cleaned up when the values are cleared. We could change this, in the future, by introducing
* a clearing thread.
*
* @param <K> The key type (should have sensible hashCode() and equals() implementations).
* @param <V> The value type.
*/
public class SoftCache<K, V> {
private final ConcurrentHashMap<K, SoftReference<V>> underlyingMap;
public SoftCache() {
this.underlyingMap = new ConcurrentHashMap<>();
}
public V checkout(K key) {
SoftReference<V> wrapper = this.underlyingMap.remove(key);
return (null != wrapper)
? wrapper.get()
: null;
}
public void checkin(K key, V value) {
SoftReference<V> previous = this.underlyingMap.put(key, new SoftReference<>(value));
// We don't expect collisions in this cache - that would imply that consumers disagree about cache state.
// (in the future, we probably want to change this).
RuntimeAssertionError.assertTrue(null == previous);
}
public void removeKeyIf(Predicate<K> condition){
this.underlyingMap.keySet().removeIf(condition);
}
public void removeValueIf(Predicate<SoftReference<V>> condition){
this.underlyingMap.values().removeIf(condition);
}
}
|
UTF-8
|
Java
| 1,588 |
java
|
SoftCache.java
|
Java
|
[] | null |
[] |
package org.aion.avm.core.util;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import i.RuntimeAssertionError;
/**
* A simple concurrent cache, based on SoftReferences. There is currently no maximum size.
* NOTE: Keys in this implementation are NOT cleaned up when the values are cleared. We could change this, in the future, by introducing
* a clearing thread.
*
* @param <K> The key type (should have sensible hashCode() and equals() implementations).
* @param <V> The value type.
*/
public class SoftCache<K, V> {
private final ConcurrentHashMap<K, SoftReference<V>> underlyingMap;
public SoftCache() {
this.underlyingMap = new ConcurrentHashMap<>();
}
public V checkout(K key) {
SoftReference<V> wrapper = this.underlyingMap.remove(key);
return (null != wrapper)
? wrapper.get()
: null;
}
public void checkin(K key, V value) {
SoftReference<V> previous = this.underlyingMap.put(key, new SoftReference<>(value));
// We don't expect collisions in this cache - that would imply that consumers disagree about cache state.
// (in the future, we probably want to change this).
RuntimeAssertionError.assertTrue(null == previous);
}
public void removeKeyIf(Predicate<K> condition){
this.underlyingMap.keySet().removeIf(condition);
}
public void removeValueIf(Predicate<SoftReference<V>> condition){
this.underlyingMap.values().removeIf(condition);
}
}
| 1,588 | 0.687657 | 0.687657 | 46 | 33.52174 | 33.869148 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false |
15
|
510667ba72938ffbfd9876cd98a9047d1cc031b7
| 34,471,407,522,116 |
bde50f8a25e90be638409af6b704ff25b7b25a56
|
/src/utils/Connection.java
|
7e282194a04c04dd950c171d7c144cdacc16ad33
|
[] |
no_license
|
pokapanxio/Leego-Mastermind
|
https://github.com/pokapanxio/Leego-Mastermind
|
d789ccc08a250454ee15485bfcdf50d27e289a2b
|
617ddc8d6281c9ae2a8536552debea28b589936d
|
refs/heads/master
| 2019-06-15T07:35:32.986000 | 2014-07-14T05:39:37 | 2014-07-14T05:39:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package utils;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connection {
private java.sql.Connection conn;
public ResultSet localRS;
public Statement localST;
public Connection() {
setUp("", "", "", "");
}
public Connection(String server, String schema, String user, String pass) {
setUp(server, schema, user, pass);
}
private void setUp(String server, String schema, String user, String pass) {
this.conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection("jdbc:mysql://" + server + "/" + schema, user, pass);
} catch (Exception e) {
log("Error al crear conexion " + e.getMessage() + "\nError: "+e);
e.printStackTrace();
}
}
public void free() {
this.conn = null;
}
public boolean connected() {
return this.conn != null;
}
public boolean execute(String sql) {
boolean resultado = false;
if (connected()) {
try {
Statement st = this.conn.createStatement();
st.executeUpdate(sql);
resultado = true;
st.close();
} catch (Exception e) {
log("Error al ejecutar \"" + sql + "\" \nError: "+e);
}
}
return resultado;
}
public void QueryScrollableRS(String query) {
if (connected()) {
try {
Statement stmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
this.localRS = stmt.executeQuery(query);
} catch (Exception e) {
log("Error al ejecutar \"" + "ERROR" + "\"");
}
}
}
public boolean query(String sql) {
closeQuery();
boolean resultado = false;
if (connected()) {
try {
this.localST = this.conn.createStatement();
this.localRS = this.localST.executeQuery(sql);
resultado = true;
} catch (Exception e) {
log("Error al ejecutar query \"" + sql + "\"");
e.printStackTrace();
}
}
return resultado;
}
public boolean next() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.next();
} catch (Exception e) {
log("Error al buscar el siguiente registro ");
}
}
return salida;
}
public boolean first() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.first();
} catch (Exception e) {
log("Error al buscar el primer registro ");
}
}
return salida;
}
public boolean previous() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.previous();
} catch (Exception e) {
log("Error al buscar el registro anterior");
}
}
return salida;
}
public boolean last() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.last();
} catch (Exception e) {
log("Error al buscar el ultimo registro");
}
}
return salida;
}
public void closeQuery() {
if (this.localRS != null) {
try {
this.localRS.close();
} catch (Exception e) {
}
}
if (this.localST != null) {
try {
this.localST.close();
} catch (Exception e) {
}
}
this.localRS = null;
this.localST = null;
}
public Object getObject(int columna) {
Object salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getObject(columna);
} catch (Exception e) {
log("Error al traer el registro de la columna \"" + columna + "\"");
}
}
return salida;
}
public Object getObject(String nombreColumna) {
Object salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getObject(nombreColumna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public String getString(int columna) {
String salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getString(columna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + columna + "\"");
}
}
return salida;
}
public String getString(String nombreColumna) {
String salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getString(nombreColumna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public int getInt(int columna) {
int salida = 0;
if (this.localRS != null) {
try {
salida = this.localRS.getInt(columna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + columna + "\"");
e.printStackTrace();
}
}
return salida;
}
public int getInt(String nombreColumna) {
int salida = 0;
if (this.localRS != null) {
try {
salida = this.localRS.getInt(nombreColumna);
} catch (Exception e) {
log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public void close() {
if (connected()) {
try {
this.conn.close();
} catch (Exception e) {
log("Error al cerrar la conexion");
}
}
}
public void log(Object msg) {
Config tabla = new Config();
if (tabla.getString("debug").compareTo("true") == 0) {
System.out.println(msg);
}
}
}
/* Location: C:\Users\Poka\Desktop\ConectorTwitter.jar
* Qualified Name: stti.util.sql.Connection
* JD-Core Version: 0.6.2
*/
|
UTF-8
|
Java
| 7,072 |
java
|
Connection.java
|
Java
|
[] | null |
[] |
package utils;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connection {
private java.sql.Connection conn;
public ResultSet localRS;
public Statement localST;
public Connection() {
setUp("", "", "", "");
}
public Connection(String server, String schema, String user, String pass) {
setUp(server, schema, user, pass);
}
private void setUp(String server, String schema, String user, String pass) {
this.conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection("jdbc:mysql://" + server + "/" + schema, user, pass);
} catch (Exception e) {
log("Error al crear conexion " + e.getMessage() + "\nError: "+e);
e.printStackTrace();
}
}
public void free() {
this.conn = null;
}
public boolean connected() {
return this.conn != null;
}
public boolean execute(String sql) {
boolean resultado = false;
if (connected()) {
try {
Statement st = this.conn.createStatement();
st.executeUpdate(sql);
resultado = true;
st.close();
} catch (Exception e) {
log("Error al ejecutar \"" + sql + "\" \nError: "+e);
}
}
return resultado;
}
public void QueryScrollableRS(String query) {
if (connected()) {
try {
Statement stmt = this.conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
this.localRS = stmt.executeQuery(query);
} catch (Exception e) {
log("Error al ejecutar \"" + "ERROR" + "\"");
}
}
}
public boolean query(String sql) {
closeQuery();
boolean resultado = false;
if (connected()) {
try {
this.localST = this.conn.createStatement();
this.localRS = this.localST.executeQuery(sql);
resultado = true;
} catch (Exception e) {
log("Error al ejecutar query \"" + sql + "\"");
e.printStackTrace();
}
}
return resultado;
}
public boolean next() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.next();
} catch (Exception e) {
log("Error al buscar el siguiente registro ");
}
}
return salida;
}
public boolean first() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.first();
} catch (Exception e) {
log("Error al buscar el primer registro ");
}
}
return salida;
}
public boolean previous() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.previous();
} catch (Exception e) {
log("Error al buscar el registro anterior");
}
}
return salida;
}
public boolean last() {
boolean salida = false;
if (this.localRS != null) {
try {
salida = this.localRS.last();
} catch (Exception e) {
log("Error al buscar el ultimo registro");
}
}
return salida;
}
public void closeQuery() {
if (this.localRS != null) {
try {
this.localRS.close();
} catch (Exception e) {
}
}
if (this.localST != null) {
try {
this.localST.close();
} catch (Exception e) {
}
}
this.localRS = null;
this.localST = null;
}
public Object getObject(int columna) {
Object salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getObject(columna);
} catch (Exception e) {
log("Error al traer el registro de la columna \"" + columna + "\"");
}
}
return salida;
}
public Object getObject(String nombreColumna) {
Object salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getObject(nombreColumna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public String getString(int columna) {
String salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getString(columna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + columna + "\"");
}
}
return salida;
}
public String getString(String nombreColumna) {
String salida = null;
if (this.localRS != null) {
try {
salida = this.localRS.getString(nombreColumna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public int getInt(int columna) {
int salida = 0;
if (this.localRS != null) {
try {
salida = this.localRS.getInt(columna);
} catch (Exception e) {
//log("Error al traer el registro de la columna \"" + columna + "\"");
e.printStackTrace();
}
}
return salida;
}
public int getInt(String nombreColumna) {
int salida = 0;
if (this.localRS != null) {
try {
salida = this.localRS.getInt(nombreColumna);
} catch (Exception e) {
log("Error al traer el registro de la columna \"" + nombreColumna + "\"");
}
}
return salida;
}
public void close() {
if (connected()) {
try {
this.conn.close();
} catch (Exception e) {
log("Error al cerrar la conexion");
}
}
}
public void log(Object msg) {
Config tabla = new Config();
if (tabla.getString("debug").compareTo("true") == 0) {
System.out.println(msg);
}
}
}
/* Location: C:\Users\Poka\Desktop\ConectorTwitter.jar
* Qualified Name: stti.util.sql.Connection
* JD-Core Version: 0.6.2
*/
| 7,072 | 0.462104 | 0.461256 | 253 | 25.95257 | 22.261244 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.387352 | false | false |
15
|
f12072da69c734cb38772e663e8556bafc687087
| 34,471,407,524,973 |
236b2da5d748ef26a90d66316b1ad80f3319d01e
|
/trunk/core/src/test/java/org/marketcetera/marketdata/SimulatedExchangeTest.java
|
c2094848378a6a09227ad47be116552b833909f5
|
[
"Apache-2.0"
] |
permissive
|
nagyist/marketcetera
|
https://github.com/nagyist/marketcetera
|
a5bd70a0369ce06feab89cd8c62c63d9406b42fd
|
4f3cc0d4755ee3730518709412e7d6ec6c1e89bd
|
refs/heads/master
| 2023-08-03T10:57:43.504000 | 2023-07-25T08:37:53 | 2023-07-25T08:37:53 | 19,530,179 | 0 | 2 |
Apache-2.0
| false | 2023-07-25T08:37:54 | 2014-05-07T10:22:59 | 2014-05-07T10:58:12 | 2023-07-25T08:37:53 | 40,348 | 0 | 0 | 0 |
Java
| false | false |
package org.marketcetera.marketdata;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.marketcetera.core.LoggerConfiguration;
import org.marketcetera.core.publisher.ISubscriber;
import org.marketcetera.event.*;
import org.marketcetera.event.impl.QuoteEventBuilder;
import org.marketcetera.event.impl.TradeEventBuilder;
import org.marketcetera.marketdata.SimulatedExchange.Token;
import org.marketcetera.marketdata.SimulatedExchange.TopOfBook;
import org.marketcetera.module.ExpectedFailure;
import org.marketcetera.options.ExpirationType;
import org.marketcetera.trade.*;
import org.marketcetera.trade.Currency;
import org.marketcetera.util.test.CollectionAssert;
import org.marketcetera.util.test.TestCaseBase;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
/* $License$ */
/**
* Tests {@link SimulatedExchange}.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
public class SimulatedExchangeTest
extends TestCaseBase
{
private SimulatedExchange exchange;
private final Equity metc = new Equity("METC");
private final Equity goog = new Equity("GOOG");
private final Option metc1Put = new Option(metc.getSymbol(),
"20100319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option metc1Call = new Option(metc1Put.getSymbol(),
metc1Put.getExpiry(),
metc1Put.getStrikePrice(),
OptionType.Call);
private final Option metc2Put = new Option(metc.getSymbol(),
"20110319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option metc2Call = new Option(metc2Put.getSymbol(),
metc2Put.getExpiry(),
metc2Put.getStrikePrice(),
OptionType.Call);
private final Option goog1Put = new Option(goog.getSymbol(),
"20100319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option goog1Call = new Option(goog1Put.getSymbol(),
goog1Put.getExpiry(),
goog1Put.getStrikePrice(),
OptionType.Call);
private final Future brn201212 = new Future("BRN",
FutureExpirationMonth.DECEMBER,
2012);
private final Currency testCCY = new Currency("USD","INR","","");
private final Currency anotherCCY = new Currency("USD","GBP","","");
private BidEvent bid;
private AskEvent ask;
private BidEvent bidCCY;
private AskEvent askCCY;
private static final AtomicLong counter = new AtomicLong(0);
/**
* Executed once before all tests.
*
* @throws Exception if an error occurs
*/
@BeforeClass
public static void once()
throws Exception
{
LoggerConfiguration.logSetup();
}
/**
* Executed before each test.
*
* @throws Exception if an error occurs
*/
@Before
public void setup()
throws Exception
{
exchange = new SimulatedExchange("Test exchange",
"TEST");
assertFalse(metc.equals(goog));
bid = EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal("100"),
new BigDecimal("1000"));
// intentionally creating a large spread to make sure no trades get executed
ask = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
bidCCY = EventTestBase.generateCurrencyBidEvent(testCCY,
new BigDecimal("150"));
// intentionally creating a large spread to make sure no trades get executed
askCCY = EventTestBase.generateCurrencyAskEvent(testCCY,
new BigDecimal("500"));
}
/**
* Execute after each test.
*
* @throws Exception if an error occurs
*/
@After
public void teardown()
throws Exception
{
try {
exchange.stop();
} catch (Exception e) {}
}
/**
* Tests starting and stopping exchange already started and stopped.
*
* @throws Exception if an error occurs
*/
@Test
public void redundantStartAndStop()
throws Exception
{
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.stop();
}
};
exchange.start();
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.start();
}
};
}
/**
* Tests the <code>SimulatedExchange</code> constructors.
*
* @throws Exception if an error occurs
*/
@Test
public void constructors()
throws Exception
{
final String name = "name";
final String code = "code";
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(null,
code);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(null,
code,
1);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
null,
1);
}
};
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
code,
-2);
}
};
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
code,
0);
}
};
verifyExchange(new SimulatedExchange(name,
code),
name,
code);
verifyExchange(new SimulatedExchange(name,
code,
100),
name,
code);
verifyExchange(new SimulatedExchange(name,
code,
OrderBook.UNLIMITED_DEPTH),
name,
code);
}
/**
* Tests snapshot requests.
*
* @throws Exception if an error occurs
*/
@Test
public void snapshots()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(null);
}
};
// exchange is not started yet
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
// start the exchange with a script with only one event for each side of the book
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bid);
script.add(ask);
exchange.start(script);
// get the depth-of-book for the symbol
List<AskEvent> asks = new ArrayList<AskEvent>();
asks.add(ask);
List<BidEvent> bids = new ArrayList<BidEvent>();
bids.add(bid);
verifySnapshots(exchange,
metc,
null,
asks,
bids,
null);
// re-execute the same query (book already exists, make sure we're reading from the already existing book)
verifySnapshots(exchange,
metc,
null,
asks,
bids,
null);
// execute a request for an empty book
verifySnapshots(exchange,
goog,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
null);
exchange.stop();
// start the exchange again in scripted mode, this time with events in opposition to each other
script.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
ask.getPrice(),
ask.getSize()));
script.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.start(script);
// verify that the book is empty (but there should be an existing trade)
verifySnapshots(exchange,
metc,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
EventTestBase.generateEquityTradeEvent(1,
1,
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.stop();
// restart exchange in random mode
exchange.start();
// books are empty
doRandomBookCheck(exchange,
metc, null);
// re-execute (this time the book exists)
doRandomBookCheck(exchange,
metc, null);
}
/**
* Tests snapshot requests for currency.
*
* @throws Exception if an error occurs
*/
@Test
public void snapshotsWithCurrency()
throws Exception
{
// exchange is not started yet
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
// start the exchange with a script with only one event for each side of the book
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bidCCY);
script.add(askCCY);
exchange.start(script);
// get the depth-of-book for the symbol
List<AskEvent> asks = new ArrayList<AskEvent>();
asks.add(askCCY);
List<BidEvent> bids = new ArrayList<BidEvent>();
bids.add(bidCCY);
verifySnapshots(exchange,
testCCY,
null,
asks,
bids,
null);
// re-execute the same query (book already exists, make sure we're reading from the already existing book)
verifySnapshots(exchange,
testCCY,
null,
asks,
bids,
null);
// execute a request for an empty book
verifySnapshots(exchange,
anotherCCY,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
null);
exchange.stop();
// start the exchange again in scripted mode, this time with events in opposition to each other
script.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
ask.getPrice(),
ask.getSize()));
script.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.start(script);
// verify that the book is empty (but there should be an existing trade)
verifySnapshots(exchange,
metc,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
EventTestBase.generateEquityTradeEvent(1,
1,
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.stop();
// restart exchange in random mode
exchange.start();
// books are empty
doRandomBookCheck(exchange,
metc, null);
// re-execute (this time the book exists)
doRandomBookCheck(exchange,
metc, null);
}
/**
* Tests snapshots using options instead of equities.
*
* <p>Note that this method doesn't have to re-execute all
* the equity tests - most of the code is identical.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void snapshotWithOptions()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateOptionBidEvent(metc1Put,
metc,
exchange.getCode());
BidEvent bid2 = EventTestBase.generateOptionBidEvent(metc1Call,
metc,
exchange.getCode());
BidEvent bid3 = EventTestBase.generateOptionBidEvent(metc2Put,
metc,
exchange.getCode());
BidEvent bid4 = EventTestBase.generateOptionBidEvent(metc2Call,
metc,
exchange.getCode());
script.add(bid1);
script.add(bid2);
script.add(bid3);
script.add(bid4);
// set up a few asks, too
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.optionAskEvent();
askBuilder.withExchange(exchange.getCode())
.withExpirationType(ExpirationType.AMERICAN)
.withQuoteDate(DateUtils.dateToString(new Date()))
.withUnderlyingInstrument(metc);
askBuilder.withInstrument(metc1Put);
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid1.getPrice().add(BigDecimal.ONE)).withSize(bid1.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1);
// and an ask that does cause a trade
askBuilder.withInstrument(metc2Put);
askBuilder.withPrice(bid3.getPrice()).withSize(bid3.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2);
// there should now be books for the underlying (metc) and 4 entries in the chain (metc1Put, metc1Call, metc2Put, and metc2Call)
exchange.start(script);
// verify the state of the options
verifySnapshots(exchange,
metc1Put,
metc,
Arrays.asList(new AskEvent[] { ask1 } ),
Arrays.asList(new BidEvent[] { bid1 } ),
null);
verifySnapshots(exchange,
metc1Call,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { bid2 } ),
null);
TradeEvent trade = TradeEventBuilder.tradeEvent(metc2Put).withExchange(bid3.getExchange())
.withExpirationType(((OptionEvent)bid3).getExpirationType())
.withPrice(bid3.getPrice())
.withSize(bid3.getSize())
.withTradeDate(bid3.getQuoteDate())
.withUnderlyingInstrument(metc).create();
verifySnapshots(exchange,
metc2Put,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { } ),
trade);
verifySnapshots(exchange,
metc2Call,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { bid4 } ),
null);
// generate expected results for verifying snapshots for the underlying instrument
Map<Instrument,InstrumentState> expectedResults = new HashMap<Instrument,InstrumentState>();
expectedResults.put(metc1Put,
new InstrumentState(Arrays.asList(new BidEvent[] { bid1 }),
Arrays.asList(new AskEvent[] { ask1 }),
null));
expectedResults.put(metc1Call,
new InstrumentState(Arrays.asList(new BidEvent[] { bid2 }),
Arrays.asList(new AskEvent[] { }),
null));
expectedResults.put(metc2Put,
new InstrumentState(Arrays.asList(new BidEvent[] { }),
Arrays.asList(new AskEvent[] { }),
trade));
expectedResults.put(metc2Call,
new InstrumentState(Arrays.asList(new BidEvent[] { bid4 }),
Arrays.asList(new AskEvent[] { }),
null));
verifyUnderlyingSnapshots(exchange,
metc,
expectedResults);
// restart exchange in random mode
exchange.stop();
exchange.start();
// books are empty
// start traffic for each of the options in the metc chain
doRandomBookCheck(exchange,
metc1Put,
metc);
doRandomBookCheck(exchange,
metc1Call,
metc);
doRandomBookCheck(exchange,
metc2Put,
metc);
doRandomBookCheck(exchange,
metc2Call,
metc);
doRandomBookCheck(exchange,
goog1Put,
goog);
doRandomBookCheck(exchange,
goog1Call,
goog);
// re-execute (this time the books exist)
doRandomBookCheck(exchange,
metc1Put,
metc);
doRandomBookCheck(exchange,
metc1Call,
metc);
doRandomBookCheck(exchange,
metc2Put,
metc);
doRandomBookCheck(exchange,
metc2Call,
metc);
doRandomBookCheck(exchange,
goog1Put,
goog);
doRandomBookCheck(exchange,
goog1Call,
goog);
exchange.stop();
}
/**
* Tests that the <code>FilteringSubscriber</code> correctly tracks top-of-book state for Currency
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void subscriptionsWithCurrency()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateCurrencyBidEvent(testCCY, new BigDecimal(95));
BidEvent bid2 = EventTestBase.generateCurrencyBidEvent(testCCY, new BigDecimal(100));
script.add(bid1); // top1
script.add(bid2); // top2
// there are two entries for currency
// add an ask for just one instrument - make sure the bid and the ask don't match
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.currencyAskEvent();
askBuilder.withExchange(exchange.getCode())
.withQuoteDate(DateUtils.dateToString(new Date()))
.withInstrument(testCCY)
.withExchange(exchange.getCode());
askBuilder.withInstrument(bid2.getInstrument());
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.ONE)).withSize(bid2.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1); // top3
// this creates a nice, two-sided top-of-book for the instrument
// create a new ask for the same instrument that *won't* change the top - a new top should not be generated
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.TEN)).withSize(bid2.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2); // no top4!
// set up a subscriber to top-of-book for the underlying instrument metc
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create(),
topOfBook);
// start the exchange
exchange.start(script);
exchange.stop();
// measure the tops collected by the subscriber
// should have:
// a top for the bid1 instrument with just bid1
// a top for the bid2 instrument with just bid2
// a top for the bid2 instrument bid2-ask1
// no new top for ask2 - a total of three tops
assertEquals(3,topOfBook.getTops().size());
}
/**
* Tests that the <code>FilteringSubscriber</code> correctly tracks top-of-book state for
* different option chain members of the same underlying instrument.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void subscriptionsWithOptions()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateOptionBidEvent(metc1Put,
metc,
exchange.getCode());
BidEvent bid2 = EventTestBase.generateOptionBidEvent(metc1Call,
metc,
exchange.getCode());
script.add(bid1); // top1
script.add(bid2); // top2
// there are two entries in the option chain for metc
// add an ask for just one instrument in the option chain - make sure the bid and the ask don't match
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.optionAskEvent();
askBuilder.withExchange(exchange.getCode())
.withExpirationType(ExpirationType.AMERICAN)
.withQuoteDate(DateUtils.dateToString(new Date()))
.withUnderlyingInstrument(metc);
askBuilder.withInstrument(bid2.getInstrument());
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.ONE)).withSize(bid2.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1); // top3
// this creates a nice, two-sided top-of-book for the instrument
// create a new ask for the same instrument that *won't* change the top - a new top should not be generated
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.TEN)).withSize(bid2.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2); // no top4!
// set up a subscriber to top-of-book for the underlying instrument metc
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(metc).create(),
topOfBook);
// start the exchange
exchange.start(script);
exchange.stop();
// measure the tops collected by the subscriber
// should have:
// a top for the bid1 instrument with just bid1
// a top for the bid2 instrument with just bid2
// a top for the bid2 instrument bid2-ask1
// no new top for ask2 - a total of three tops
assertEquals(3,
topOfBook.getTops().size());
}
/**
* Tests the ability to generate symbol statistics data.
*
* <p>Note that testing this is made challenging by the random nature of data generation
* for statistics.
*
* @throws Exception if an error occurs
*/
@Test
public void statistics()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getStatistics(null);
}
};
// exchange not started
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
// done with error conditions
exchange.start();
// quantities are random, even for subsequent calls and scripted mode, but
// there are some conditions we can expect the values to adhere to
for(int i=0;i<25000;i++) {
verifyStatistics(exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()));
}
for(int i=0;i<25000;i++) {
verifyStatistics(exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create()));
}
}
/**
* Tests the ability to receive statistics in a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void statisticSubscriber()
throws Exception
{
final AllEventsSubscriber equityStream = new AllEventsSubscriber();
final AllEventsSubscriber optionStream = new AllEventsSubscriber();
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
equityStream);
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create(),
optionStream);
exchange.start();
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return equityStream.events.size() >= 15 &&
optionStream.events.size() >= 15;
}
});
List<MarketstatEvent> stats = new ArrayList<MarketstatEvent>();
for(Event event : equityStream.events) {
if(event instanceof MarketstatEvent) {
stats.add((MarketstatEvent)event);
}
}
for(Event event : optionStream.events) {
if(event instanceof MarketstatEvent) {
stats.add((MarketstatEvent)event);
}
}
verifyStatistics(stats);
}
/**
* Tests the ability to generate symbol dividends data.
*
* <p>Note that testing this is made challenging by the random nature of data generation
* for dividends.
*
* @throws Exception if an error occurs
*/
@Test
public void dividends()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(null);
}
};
// exchange not started
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
exchange.start();
// dividends for an option
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create());
}
};
// dividends by underlying
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(metc).create());
}
};
for(int i=0;i<1000;i++) {
Equity e = new Equity(String.format("equity-%s",
i));
verifyDividends(exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(e).create()),
e);
}
}
/**
* Tests the ability to receive dividends in a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void dividendSubscriber()
throws Exception
{
final AllEventsSubscriber dividendStream = new AllEventsSubscriber();
exchange.start();
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Equity e = new Equity("e-" + counter.incrementAndGet());
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(e).create(),
dividendStream);
return dividendStream.events.size() >= 20;
}
});
// sleep for a couple of ticks to make sure we don't get extra dividends (the same dividends sent more than once)
Thread.sleep(5000);
Multimap<Equity,DividendEvent> dividends = LinkedListMultimap.create();
for(Event event : dividendStream.events) {
DividendEvent dividendEvent = (DividendEvent)event;
dividends.put(dividendEvent.getEquity(),
dividendEvent);
}
for(Equity equity : dividends.keySet()) {
verifyDividends(new ArrayList<DividendEvent>(dividends.get(equity)),
equity);
}
}
/**
* Tests subscribing to market data from an exchange.
*
* <p>This is a very complicated test due to the problem of generating complex expected
* results. Apologies in advance to anyone who has to review or modify this method. The general
* approach is to compile data structures that mimic the result (top-of-book, depth-of-book, etc)
* using {@link QuantityTuple} objects that mirror {@link QuoteEvent} objects.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptions()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
null);
}
};
// generate a script with a number of bids and asks
BigDecimal baseValue = new BigDecimal("100.00");
BigDecimal bidSize = new BigDecimal("100");
BigDecimal askSize = new BigDecimal("50");
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
List<BidEvent> bids = new ArrayList<BidEvent>();
List<AskEvent> asks = new ArrayList<AskEvent>();
for(int i=0;i<5;i++) {
bids.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
baseValue.add(BigDecimal.ONE.multiply(new BigDecimal(i))),
bidSize));
}
for(int i=4;i>=0;i--) {
asks.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
baseValue.add(BigDecimal.ONE.multiply(new BigDecimal(i))),
askSize));
}
script.addAll(bids);
script.addAll(asks);
// add one outrageous ask to make the book interesting
AskEvent bigAsk = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(1000),
new BigDecimal(1000));
script.add(bigAsk);
// set up the subscriptions
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
topOfBook);
AllEventsSubscriber tick = new AllEventsSubscriber();
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
tick);
AllEventsSubscriber depthOfBook = new AllEventsSubscriber();
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
depthOfBook);
// start the script
exchange.start(script);
// we can predict that the exchange will send 10 quote adds which will result in 5 trades and
// 10 quote corrections (bid/ask del/chg), 25 events altogether
// verify the results
// this list will hold all the expected events
List<QuantityTuple> allExpectedEvents = new ArrayList<QuantityTuple>();
List<BookEntryTuple> expectedTopOfBook = new ArrayList<BookEntryTuple>();
// the first events will be the bids
for(BidEvent bid : bids) {
QuantityTuple convertedBid = OrderBookTest.convertEvent(bid);
allExpectedEvents.add(convertedBid);
expectedTopOfBook.add(new BookEntryTuple(convertedBid,
null));
}
/*
bid | ask
-----------+---------
100 104.00 |
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
// next will be the asks interleaved with trades and corrections as the books are settled after each ask
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // 1st of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 104.00 | 104.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // bid correction (change)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 | 104.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // ask correction (delete)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 |
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // 2nd of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 | 103.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // bid correction (delete of fully consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 | 103.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // 3rd of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 | 102.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // bid correction (change of partially consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 | 102.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // 4th of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 | 101.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // bid correction (delete of fully consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 | 101.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // 5th of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 | 100.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // bid correction (change of partially consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 102.00 | 100.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(bigAsk.getPrice(), // big ask
bigAsk.getSize(),
AskEvent.class));
/*
bid | ask
-----------+-------------
50 102.00 | 1000.00 1000
100 101.00 |
100 100.00 |
*/
// prepare the expected top-of-book results
expectedTopOfBook.addAll(Arrays.asList(new BookEntryTuple[] {
/* 100 104.00 | 104.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 104.00 | 104.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 104.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 104.00 | 103.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 103.00 | 103.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 103.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
null),
/* 100 103.00 | 102.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 103.00 | 102.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 103.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 103.00 | 101.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("101.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 102.00 | 101.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("101.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 102.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
null),
/* 100 102.00 | 100.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("100.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 102.00 | 100.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("100.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 102.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 102.00 | 1000 1000 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("1000"),
new BigDecimal("1000"),
AskEvent.class)),
}));
// prepare the expected latest tick results
List<QuantityTuple> expectedLatestTicks = new ArrayList<QuantityTuple>();
// prepare the expected depth-of-book results
List<QuantityTuple> expectedDepthOfBook = new ArrayList<QuantityTuple>();
for(QuantityTuple tuple : allExpectedEvents) {
if(tuple.getType().equals(TradeEvent.class)) {
expectedLatestTicks.add(tuple);
} else {
expectedDepthOfBook.add(tuple);
}
}
// ready to verify results
verifySubscriptions(topOfBook.getTops(),
expectedTopOfBook,
tick.events,
expectedLatestTicks,
depthOfBook.events,
expectedDepthOfBook);
}
/**
* Tests that subscribers to different exchanges for the same type of data
* get only the data they are supposed to.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptionTargeting()
throws Exception
{
// create two different exchanges (one already exists, of course)
SimulatedExchange exchange2 = new SimulatedExchange("Test exchange 2",
"TEST2");
assertFalse(exchange.equals(exchange2));
// create two different subscribers
AllEventsSubscriber sub1 = new AllEventsSubscriber();
AllEventsSubscriber sub2 = new AllEventsSubscriber();
// set up the subscriptions
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
sub1);
exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
sub2);
// create an event targeted to the second exchange
AskEvent ask2 = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange2.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
// create an event targeted to the second exchange but with the wrong symbol
AskEvent ask3 = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
goog,
exchange2.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
// create two different scripts
// the events that are targeted to the wrong exchange or symbol should get skipped
List<QuoteEvent> script1 = new ArrayList<QuoteEvent>();
script1.add(bid);
script1.add(ask2);
script1.add(ask3);
List<QuoteEvent> script2 = new ArrayList<QuoteEvent>();
script2.add(ask2);
script2.add(bid);
script2.add(ask3);
// start the exchanges
exchange.start(script1);
exchange2.start(script2);
// measure the results
assertEquals(1,
sub1.events.size());
assertEquals(bid,
sub1.events.get(0));
assertEquals(1,
sub2.events.size());
assertEquals(ask2,
sub2.events.get(0));
}
/**
* Tests that an over-filled (according to its max depth) order book gets pruned.
*
* @throws Exception if an error occurs
*/
@Test
public void bookPruning()
throws Exception
{
// create an exchange with a small maximum depth (2)
exchange = new SimulatedExchange("Test exchange",
"TEST",
2);
// create a script of events that will exceed the max on both sides of the book
// note that the spread is intentionally large in order to prevent any trades
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
List<AskEvent> asks = new ArrayList<AskEvent>();
List<BidEvent> bids = new ArrayList<BidEvent>();
for(int i=0;i<3;i++) {
bids.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(10-i),
new BigDecimal("1000")));
asks.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(100+i),
new BigDecimal("1000")));
}
script.addAll(bids);
script.addAll(asks);
exchange.start(script);
// now, trim the oldest (first) bid and ask from each list to simulate the pruning
bids.remove(0);
asks.remove(0);
// check the results
verifyDepthOfBook(exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()),
asks,
bids);
}
/**
* Tests canceling a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptionCanceling()
throws Exception
{
final AllEventsSubscriber stream1 = new AllEventsSubscriber();
final AllEventsSubscriber stream2 = new AllEventsSubscriber();
SimulatedExchange.Token t1 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream1);
SimulatedExchange.Token t2 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream2);
assertFalse(t1.equals(t2));
assertFalse(t1.hashCode() == t2.hashCode());
exchange.start();
// start the exchange in random mode (wait until a reasonable number of events comes in)
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream1.events.size() >= 10;
}
});
// t2 should have received at least the same number of events (won't be deterministically in
// sync)
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream2.events.size() >= 10;
}
});
// both subscribers have now received at least 10 events (this shows us that they're
// both receiving events)
// now, cancel one subscription - note that since it's async, we can't guarantee that
// no more than 10 events will come (one may have come in even while you read this
// comment)
t1.cancel();
// some time very shortly (certainly in the next minute), updates should stop coming in
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
int currentCount = stream1.events.size();
// at least 2 events should come in every second, so by waiting 2.5 seconds,
// we should be able to tell with a reasonable degree of confidence that
// no new events are coming in
Thread.sleep(2500);
return stream1.events.size() == currentCount;
}
});
int stream1Count = stream1.events.size();
int stream2Count = stream2.events.size();
// stream2 is still receiving events, but stream1 is not
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream2.events.size() >= 20;
}
});
// the size of stream2 has grown
assertTrue(stream2.events.size() >= stream2Count);
// the size of stream1 has not
assertEquals(stream1Count,
stream1.events.size());
// cancel the same thing again just to make sure nothing flies off the handle
t1.cancel();
}
/**
* Tests the ability to subscribe before and after the exchange starts.
*
* @throws Exception if an error occurs
*/
@Test
public void subscribeBeforeAndAfterStart()
throws Exception
{
final AllEventsSubscriber stream1 = new AllEventsSubscriber();
final AllEventsSubscriber stream2 = new AllEventsSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream1);
exchange.start();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream2);
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream1.events.size() >= 10 &&
stream2.events.size() >= 10;
}
});
}
/**
* Tests that a scripted exchange doesn't start new activity after running its
* script.
*
* @throws Exception if an error occurs
*/
@Test
public void otherSymbolsFromScriptedExchange()
throws Exception
{
// start the exchange in scripted mode with two events for METC
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bid);
script.add(ask);
exchange.start(script);
// allow the exchange the opportunity to do something off the script, if it's going to
Thread.sleep(5000);
// verify the top for METC
verifyTopOfBook(makeTopOfBook(exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create())),
ask,
bid);
// verify that nothing's there for GOOG
assertTrue(exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(goog).create()).isEmpty());
}
/**
* Tests that exchanges initially have closely grouped values for the same symbol.
*
* @throws Exception if an error occurs
*/
@Test
public void valueSync()
throws Exception
{
// create two extra exchanges
final SimulatedExchange exchange2 = new SimulatedExchange("Test Exchange2",
"TEST2");
final SimulatedExchange exchange3 = new SimulatedExchange("Test Exchange3",
"TEST3");
// start all three in random mode (note that exchange-sync behavior does not apply to scripted mode)
exchange.start();
exchange2.start();
exchange3.start();
// all three are ticking over, but the books are not yet populated
// wait until the book is populated for METC
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
// the book for METC has at least an ask and bid in it, grab the value
List<QuoteEvent> top1 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// now, issue the same request for exchange2
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
List<QuoteEvent> top2 = exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// and exchange3
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange3.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
List<QuoteEvent> top3 = exchange3.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// we cannot guarantee how many ticks (if any) have happened during the course of these
// instructions. regardless, each of the exchanges has
// a book for METC with at least a bid and ask. it's unlikely they're exactly the same, but
// they can have varied by no more than .01/second. the absolute maximum that is possible is limited
// by about 3 minutes (each of the wait calls could take just under 60 seconds without failing).
// so, we'll say that the most the values could have changed is 2.50 (that's equivalent to
// a bit over 4 minutes of run time with one tick/second).
// the default book start values vary between (0.01,99.99), the odds of three values hitting the
// same 5.00 interval randomly without sync are not large, about 1.25 in 10,000). the worst case for
// this test is a false negative, that is, sync isn't working and all three books randomly start
// in the same interval. since this should happen a little more often than once in 10,000, that
// makes this test effective enough.
assertTrue(((MarketDataEvent)top1.get(0)).getPrice().subtract(((MarketDataEvent)top2.get(0)).getPrice()).abs().intValue() < 3);
assertTrue(((MarketDataEvent)top1.get(0)).getPrice().subtract(((MarketDataEvent)top3.get(0)).getPrice()).abs().intValue() < 3);
}
/**
* Tests the output of the exchange in random mode.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void randomModeOutput()
throws Exception
{
exchange.start();
// start the exchange in random mode
final AllEventsSubscriber all = new AllEventsSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
all);
// this block should actually take less than 30s - there are 2 new events/sec and every now and then
// a trade will create a few extras
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 60;
}
});
exchange.stop();
}
/**
* Tests the ability of the exchange to deliver a non-zero and non-one contract size.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void testFutureContractSize()
throws Exception
{
exchange.start();
final AllEventsSubscriber all = new AllEventsSubscriber();
Token token = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
}
/**
* Executes a test to make sure that the given <code>Instrument</code> and underlying <code>Instrument</code>
* get order books created for them.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inInstrument an <code>Instrument</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value
* @throws Exception if an unexpected error occurs
*/
private void doRandomBookCheck(SimulatedExchange inExchange,
Instrument inInstrument,
Instrument inUnderlyingInstrument)
throws Exception
{
List<QuoteEvent> dob = inExchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(inInstrument)
.withUnderlyingInstrument(inUnderlyingInstrument).create());
// note that since the exchange was started this time in random mode we don't know exactly what the
// values will be, but there should be at least one entry on each side of the book
assertFalse(dob.isEmpty());
boolean foundAsk = false;
boolean foundBid = false;
for(Event event : dob) {
if(event instanceof BidEvent) {
foundBid = true;
} else if(event instanceof AskEvent) {
foundAsk = true;
}
}
assertTrue(foundBid);
assertTrue(foundAsk);
// repeat, checking by underlying instrument only
if(inUnderlyingInstrument != null) {
dob = inExchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(inUnderlyingInstrument).create());
assertFalse(dob.isEmpty());
foundAsk = false;
foundBid = false;
for(Event event : dob) {
if(event instanceof BidEvent) {
foundBid = true;
} else if(event instanceof AskEvent) {
foundAsk = true;
}
}
assertTrue(foundBid);
assertTrue(foundAsk);
}
}
/**
* Verifies the given actual subscriptions against the expected results.
*
* @param inActualTopOfBook a <code>List<Pair<BidEvent,AskEvent>></code> value
* @param inExpectedTopOfBook a <code>List<BookEntryTuple></code> value
* @param inActualTicks a <code>List<EventBase></code> value
* @param inExpectedTicks a <code>List<QuantityTuple></code> value
* @param inActualDepthOfBook a <code>List<EventBase></code> value
* @param inExpectedDepthOfBook a <code>List<QuantityTuple></code> value
* @throws Exception if an error occurs
*/
private void verifySubscriptions(List<TopOfBook> inActualTopOfBook,
List<BookEntryTuple> inExpectedTopOfBook,
List<Event> inActualTicks,
List<QuantityTuple> inExpectedTicks,
List<Event> inActualDepthOfBook,
List<QuantityTuple> inExpectedDepthOfBook)
throws Exception
{
// test top-of-book
assertEquals(inExpectedTopOfBook.size(),
inActualTopOfBook.size());
List<BookEntryTuple> actualTopOfBook = new ArrayList<BookEntryTuple>();
for(TopOfBook top : inActualTopOfBook) {
actualTopOfBook.add(new BookEntryTuple(OrderBookTest.convertEvent(top.getFirstMember()),
OrderBookTest.convertEvent(top.getSecondMember())));
}
assertEquals(inExpectedTopOfBook,
actualTopOfBook);
// test latest-tick
assertEquals(inExpectedTicks,
OrderBookTest.convertEvents(inActualTicks));
// test depth-of-book
assertEquals(inExpectedDepthOfBook.size(),
inActualDepthOfBook.size());
assertEquals(inExpectedDepthOfBook,
OrderBookTest.convertEvents(inActualDepthOfBook));
}
/**
* Verifies symbol statistical data.
*
* @param inStatistics a <code>List<MarketstatEvent></code> value containing the actual value
* @throws Exception if an error occurs
*/
private void verifyStatistics(List<MarketstatEvent> inStatistics)
throws Exception
{
for(MarketstatEvent stat : inStatistics) {
assertNotNull(stat.getOpen());
assertNotNull(stat.getHigh());
assertNotNull(stat.getLow());
assertNotNull(stat.getClose());
assertNotNull(stat.getPreviousClose());
assertNotNull(stat.getVolume());
assertNotNull(stat.getCloseDate());
assertNotNull(stat.getPreviousCloseDate());
assertNotNull(stat.getTradeHighTime());
assertNotNull(stat.getTradeLowTime());
assertNotNull(stat.getOpenExchange());
assertNotNull(stat.getCloseExchange());
assertNotNull(stat.getHighExchange());
assertNotNull(stat.getLowExchange());
Instrument instrument = stat.getInstrument();
if(instrument instanceof Option) {
assertNotNull(((OptionMarketstatEvent)stat).getInterestChange());
assertNotNull(((OptionMarketstatEvent)stat).getVolumeChange());
}
}
}
/**
* Verifies symbol dividends.
*
* @param inDividends a <code>List<Marketstatevent></code> value
* @param inEquity an <code>Equity</code> value
* @throws Exception if an unexpected error occurs
*/
private void verifyDividends(List<DividendEvent> inDividends,
Equity inEquity)
throws Exception
{
// make sure that the dividends we got match the dividends we get a second
// time for the same equity
assertEquals(inDividends,
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(inEquity).create()));
if(!inDividends.isEmpty()) {
assertEquals(4,
inDividends.size());
DividendEvent currentDividend = inDividends.get(0);
assertTrue(currentDividend.getAmount().compareTo(BigDecimal.ZERO) == 1);
assertEquals("USD",
currentDividend.getCurrency());
assertEquals(inEquity,
currentDividend.getEquity());
Date today = new Date();
assertNotNull(currentDividend.getDeclareDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getDeclareDate())));
assertNotNull(currentDividend.getExecutionDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getExecutionDate())));
assertNotNull(currentDividend.getPaymentDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getPaymentDate())));
assertNotNull(currentDividend.getRecordDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getRecordDate())));
assertEquals(DividendFrequency.QUARTERLY,
currentDividend.getFrequency());
assertEquals(DividendStatus.OFFICIAL,
currentDividend.getStatus());
assertEquals(DividendType.CURRENT,
currentDividend.getType());
// now check future dividends
for(int counter=1;counter<=3;counter++) {
DividendEvent futureDividend = inDividends.get(counter);
assertTrue(futureDividend.getAmount().compareTo(BigDecimal.ZERO) == 1);
assertEquals("USD",
futureDividend.getCurrency());
assertEquals(inEquity,
futureDividend.getEquity());
assertEquals(DividendFrequency.QUARTERLY,
futureDividend.getFrequency());
assertEquals(DividendStatus.UNOFFICIAL,
futureDividend.getStatus());
assertEquals(DividendType.FUTURE,
futureDividend.getType());
assertNull(futureDividend.getDeclareDate());
assertNull(futureDividend.getPaymentDate());
assertNull(futureDividend.getRecordDate());
String executionDate = futureDividend.getExecutionDate();
assertNotNull(executionDate);
assertTrue(today.before(DateUtils.stringToDate(executionDate)));
}
}
}
/**
* Verifies that the given exchange and symbol will produce the expected snapshots.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inInstrument an <code>Instrument</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value or <code>null</code>
* @param inExpectedAsks a <code>List<AskEvent></code> value
* @param inExpectedBids a <code>List<BidEvent></code> value
* @throws Exception if an error occurs
*/
private void verifySnapshots(SimulatedExchange inExchange,
Instrument inInstrument,
Instrument inUnderlyingInstrument,
List<AskEvent> inExpectedAsks,
List<BidEvent> inExpectedBids,
TradeEvent inExpectedLatestTick)
throws Exception
{
ExchangeRequest request = ExchangeRequestBuilder.newRequest().withInstrument(inInstrument)
.withUnderlyingInstrument(inUnderlyingInstrument).create();
verifyDepthOfBook(inExchange.getDepthOfBook(request),
inExpectedAsks,
inExpectedBids);
verifyTopOfBook(makeTopOfBook(inExchange.getTopOfBook(request)),
inExpectedAsks.isEmpty() ? null : inExpectedAsks.get(0),
inExpectedBids.isEmpty() ? null : inExpectedBids.get(0));
assertEquals(OrderBookTest.convertEvent(inExpectedLatestTick),
OrderBookTest.convertEvent(exchange.getLatestTick(request).get(0)));
}
/**
* Verifies that the underlying instrument leads to the given expected states in the
* given exchange.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value
* @param inExpectedStates a <code>Map<Instrument,InstrumentState></code> value
* @throws Exception if an unexpected error occurs
*/
private void verifyUnderlyingSnapshots(SimulatedExchange inExchange,
Instrument inUnderlyingInstrument,
Map<Instrument,InstrumentState> inExpectedStates)
throws Exception
{
ExchangeRequest request = ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(inUnderlyingInstrument).create();
EventOrganizer.process(inExchange.getTopOfBook(request),
EventOrganizer.RequestType.TOP_OF_BOOK);
EventOrganizer.process(inExchange.getDepthOfBook(request),
EventOrganizer.RequestType.DEPTH_OF_BOOK);
EventOrganizer.process(inExchange.getLatestTick(request),
EventOrganizer.RequestType.LATEST_TICK);
EventOrganizer.process(inExchange.getStatistics(request),
EventOrganizer.RequestType.MARKET_STAT);
// all the actual events have been collected and organized, examine them
for(Map.Entry<Instrument,InstrumentState> entry : inExpectedStates.entrySet()) {
InstrumentState expectedState = inExpectedStates.get(entry.getKey());
EventOrganizer organizer = EventOrganizer.organizers.remove(entry.getKey());
assertNotNull("No actual results for " + entry.getKey(),
organizer);
verifyTopOfBook(organizer.getTop(),
expectedState.asks.isEmpty() ? null : expectedState.asks.get(0),
expectedState.bids.isEmpty() ? null : expectedState.bids.get(0));
verifyDepthOfBook(organizer.depthOfBook,
expectedState.asks,
expectedState.bids);
verifyStatistics(Arrays.asList(new MarketstatEvent[] { organizer.marketstat } ));
assertEquals(OrderBookTest.convertEvent(organizer.latestTrade),
OrderBookTest.convertEvent(expectedState.latestTrade));
}
}
/**
* Creates a <code>TopOfBook</code> object from the given list.
*
* @param inEvents a <code>List<QuoteEvent></code> value
* @return a <code>TopOfBook</code> value
* @throws Exception if an unexpected error occurs
*/
private static TopOfBook makeTopOfBook(List<QuoteEvent> inEvents)
throws Exception
{
assertTrue("An instrument should have a single top-of-book",
inEvents.size() <= 2);
BidEvent bid = null;
AskEvent ask = null;
if(inEvents.size() == 2) {
bid = (BidEvent)inEvents.get(0);
ask = (AskEvent)inEvents.get(1);
} else if(inEvents.size() == 1) {
Event e = inEvents.get(0);
if(e instanceof BidEvent) {
bid = (BidEvent)e;
} else if(e instanceof AskEvent) {
ask = (AskEvent)e;
} else {
fail("Unknown contents in top-of-book: " + e);
}
}
return new TopOfBook(bid,
ask);
}
/**
* Verifies the given actual<code>TopOfBook</code> contains the expected values.
*
* @param inActualTopOfBook a <code>TopOfBook</code> value
* @param inAsk a <code>AskEvent</code> value
* @param inBid a <code>BidEvent</code> value
* @throws Exception if an error occurs
*/
private void verifyTopOfBook(TopOfBook inActualTopOfBook,
AskEvent inExpectedAsk,
BidEvent inExpectedBid)
throws Exception
{
assertEquals(OrderBookTest.convertEvent(inExpectedBid),
OrderBookTest.convertEvent(inActualTopOfBook.getBid()));
assertEquals(OrderBookTest.convertEvent(inExpectedAsk),
OrderBookTest.convertEvent(inActualTopOfBook.getAsk()));
}
/**
* Verifies that the given exchange has the given expected attributes.
*
* @param inActualExchange a <code>SimulatedExchange</code> value
* @param inExpectedName a <code>String</code> value
* @param inExpectedCode a <code>String</code> value
* @throws Exception if an error occurs
*/
private void verifyExchange(SimulatedExchange inActualExchange,
String inExpectedName,
String inExpectedCode)
throws Exception
{
assertEquals(inExpectedName,
inActualExchange.getName());
assertEquals(inExpectedCode,
inActualExchange.getCode());
}
/**
* Verifies that the given <code>AggregateEvent</code> decomposes into the
* given expected events.
*
* <p>No guarantee is made as to the order of the events.
*
* @param inActualEvent an <code>AggregateEvent</code> value
* @param inExpectedEvents a <code>List<Event></code> value
* @throws Exception if an error occurs
*/
final static void verifyDecomposedEvents(AggregateEvent inActualEvent,
List<Event> inExpectedEvents)
throws Exception
{
CollectionAssert.assertArrayPermutation(inExpectedEvents.toArray(),
inActualEvent.decompose().toArray());
}
/**
* Verifies the given actual <code>DepthOfBook</code> contains the expected values.
*
* @param inActualDepthOfBook a <code>List<QuoteEvent></code> value
* @param inExpectedAsks a <code>List<AskEvent></code> value
* @param inExpectedBids a <code>List<BidEvent></code> value
* @throws Exception if an error occurs
*/
public static void verifyDepthOfBook(List<QuoteEvent> inActualDepthOfBook,
List<AskEvent> inExpectedAsks,
List<BidEvent> inExpectedBids)
throws Exception
{
List<BidEvent> actualBids = new ArrayList<BidEvent>();
List<AskEvent> actualAsks = new ArrayList<AskEvent>();
for(Event event : inActualDepthOfBook) {
if(event instanceof BidEvent) {
actualBids.add((BidEvent)event);
} else if(event instanceof AskEvent) {
actualAsks.add((AskEvent)event);
}
}
assertEquals(OrderBookTest.convertEvents(inExpectedAsks),
OrderBookTest.convertEvents(actualAsks));
assertEquals(OrderBookTest.convertEvents(inExpectedBids),
OrderBookTest.convertEvents(actualBids));
}
/**
* Subscribes to top-of-book and captures the state of the exchange top every time it changes.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
@ThreadSafe
private static class TopOfBookSubscriber
implements ISubscriber
{
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#isInteresting(java.lang.Object)
*/
@Override
public boolean isInteresting(Object inData)
{
return inData instanceof QuoteEvent;
}
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#publishTo(java.lang.Object)
*/
@Override
public synchronized void publishTo(Object inData)
{
QuoteEvent quote = (QuoteEvent)inData;
BidEvent lastBid = lastBids.get(quote.getInstrument());
AskEvent lastAsk = lastAsks.get(quote.getInstrument());
BidEvent newBid = (quote instanceof BidEvent ? quote.getAction() == QuoteAction.DELETE ? null : (BidEvent)quote : lastBid);
AskEvent newAsk = (quote instanceof AskEvent ? quote.getAction() == QuoteAction.DELETE ? null : (AskEvent)quote : lastAsk);
tops.add(new TopOfBook(newBid,
newAsk));
lastBids.put(quote.getInstrument(),
newBid);
lastAsks.put(quote.getInstrument(),
newAsk);
}
/**
*
*
*
* @return
*/
private List<TopOfBook> getTops()
{
return Collections.unmodifiableList(tops);
}
/**
* the events received
*/
@GuardedBy("this")
private final List<TopOfBook> tops = new ArrayList<TopOfBook>();
/**
* the latest ask received, may be <code>null</code>
*/
@GuardedBy("this")
private final Map<Instrument,AskEvent> lastAsks = new HashMap<Instrument,AskEvent>();
/**
* the latest bid received, may be <code>null</code>
*/
@GuardedBy("this")
private final Map<Instrument,BidEvent> lastBids = new HashMap<Instrument,BidEvent>();
}
/**
* Captures any events from a <code>SimulatedExchange</code>.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
private static class AllEventsSubscriber
implements ISubscriber
{
/**
* the events received
*/
private final List<Event> events = new ArrayList<Event>();
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#isInteresting(java.lang.Object)
*/
@Override
public boolean isInteresting(Object inData)
{
return true;
}
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#publishTo(java.lang.Object)
*/
@Override
public void publishTo(Object inData)
{
events.add((Event)inData);
}
}
/**
* Describes the expected state of a given <code>Instrument</code> in an unspecified exchange
* at an unspecified point in time.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static class InstrumentState
{
/**
* Create a new InstrumentState instance.
*
* @param inBids a <code>List<BidEvent></code> value
* @param inAsks a <code>List<AskEvent></code> value
* @param inTrade a <code>TradeEvent</code> value
*/
private InstrumentState(List<BidEvent> inBids,
List<AskEvent> inAsks,
TradeEvent inTrade)
{
bids = inBids;
asks = inAsks;
latestTrade = inTrade;
}
/**
* the expected bids, may be empty
*/
private final List<BidEvent> bids;
/**
* the expected asks, may be empty
*/
private final List<AskEvent> asks;
/**
* the expected trade, may be <code>null</code>
*/
private final TradeEvent latestTrade;
}
/**
* Organizes actual results from an exchange by <code>Instrument</code>.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static class EventOrganizer
{
/**
* Process the given events to make them available by <code>Instrument</code> and purpose.
*
* @param inEvents a <code>List<? extends Event></code> value
* @param inRequestType a <code>RequestType</code> value
*/
private static void process(List<? extends Event> inEvents,
RequestType inRequestType)
{
Multimap<EventOrganizer,Event> sortedEvents = LinkedHashMultimap.create();
for(Event event : inEvents) {
if(event instanceof HasInstrument) {
Instrument instrument = ((HasInstrument)event).getInstrument();
EventOrganizer organizer = organizers.get(instrument);
if(organizer == null) {
organizer = new EventOrganizer();
organizers.put(instrument,
organizer);
}
sortedEvents.put(organizer,
event);
}
}
for(EventOrganizer organizer : sortedEvents.keySet()) {
Collection<Event> events = sortedEvents.get(organizer);
switch(inRequestType) {
case LATEST_TICK :
organizer.latestTrade = null;
if(events.size() > 1) {
fail("Unable to translate " + events + " as latest tick (should be one event)");
}
if(!events.isEmpty()) {
organizer.latestTrade = (TradeEvent)events.iterator().next();
}
break;
case MARKET_STAT :
organizer.marketstat = null;
if(events.size() > 1) {
fail("Unable to translate " + events + " as marketstat (should be one event)");
}
if(!events.isEmpty()) {
organizer.marketstat = (MarketstatEvent)events.iterator().next();
}
break;
case TOP_OF_BOOK :
organizer.topOfBook.clear();
for(Event event : events) {
if(event instanceof QuoteEvent) {
organizer.topOfBook.add((QuoteEvent)event);
}
}
break;
case DEPTH_OF_BOOK :
organizer.depthOfBook.clear();
for(Event event : events) {
if(event instanceof QuoteEvent) {
organizer.depthOfBook.add((QuoteEvent)event);
}
}
break;
default :
fail("Unexpected request type");
}
}
}
/**
* Gets the <code>TopOfBook</code> that represents the current state of {@link #topOfBook}.
*
* @return a <code>TopOfBook</code> value
*/
private TopOfBook getTop()
{
assertTrue("There are too many events in the top-of-book collection",
topOfBook.size() <= 2);
BidEvent bid = null;
AskEvent ask = null;
while(!topOfBook.isEmpty()) {
Event event = topOfBook.remove(0);
if(event instanceof BidEvent) {
bid = (BidEvent)event;
} else if(event instanceof AskEvent) {
ask = (AskEvent)event;
}
}
return new TopOfBook(bid,
ask);
}
/**
* the set of event organizers by instrument
*/
private static Map<Instrument,EventOrganizer> organizers = new HashMap<Instrument,EventOrganizer>();
/**
* the current depth-of-book for this instrument
*/
private final List<QuoteEvent> depthOfBook = new ArrayList<QuoteEvent>();
/**
* the current top-of-book for this instrument
*/
private final List<QuoteEvent> topOfBook = new ArrayList<QuoteEvent>();
/**
* the current lates trade for this instrument
*/
private TradeEvent latestTrade = null;
/**
* the current marketstat for this instrument
*/
private MarketstatEvent marketstat;
/**
* Indicates the type of request made to the exchange.
*
* @author <a href="mailto:colin@marketcetera.com">Colin DuPlantis</a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static enum RequestType
{
LATEST_TICK,
TOP_OF_BOOK,
MARKET_STAT,
DEPTH_OF_BOOK
}
}
}
|
UTF-8
|
Java
| 103,733 |
java
|
SimulatedExchangeTest.java
|
Java
|
[
{
"context": "SimulatedExchange}.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedEx",
"end": 1300,
"score": 0.9999058842658997,
"start": 1278,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest.java 1",
"end": 1317,
"score": 0.9998809695243835,
"start": 1302,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 1.5.0\n */\npublic class SimulatedExcha",
"end": 1398,
"score": 0.6413566470146179,
"start": 1393,
"tag": "USERNAME",
"value": "colin"
},
{
"context": "rows Exception\n {\n final String name = \"name\";\n final String code = \"code\";\n new",
"end": 6778,
"score": 0.5267893075942993,
"start": 6774,
"tag": "NAME",
"value": "name"
},
{
"context": "it changes.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: Simulat",
"end": 94011,
"score": 0.9999300837516785,
"start": 93989,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest.ja",
"end": 94028,
"score": 0.999862551689148,
"start": 94013,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 1.5.0\n */\n @ThreadSafe\n ",
"end": 94113,
"score": 0.997748851776123,
"start": 94108,
"tag": "USERNAME",
"value": "colin"
},
{
"context": "hange</code>.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: Simulate",
"end": 96340,
"score": 0.9999293088912964,
"start": 96318,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest.jav",
"end": 96357,
"score": 0.9998871684074402,
"start": 96342,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 1.5.0\n */\n private static cla",
"end": 96441,
"score": 0.9986147880554199,
"start": 96436,
"tag": "USERNAME",
"value": "colin"
},
{
"context": "oint in time.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: Simulate",
"end": 97348,
"score": 0.9999314546585083,
"start": 97326,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest.jav",
"end": 97365,
"score": 0.9998927116394043,
"start": 97350,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 2.0.0\n */\n private static cla",
"end": 97449,
"score": 0.9988930225372314,
"start": 97444,
"tag": "USERNAME",
"value": "colin"
},
{
"context": "ument</code>.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: Simulate",
"end": 98536,
"score": 0.9999279379844666,
"start": 98514,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest.jav",
"end": 98553,
"score": 0.9998739361763,
"start": 98538,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 2.0.0\n */\n private static cla",
"end": 98637,
"score": 0.9729995727539062,
"start": 98632,
"tag": "USERNAME",
"value": "colin"
},
{
"context": "ange.\n *\n * @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: Simu",
"end": 103430,
"score": 0.9999305009841919,
"start": 103408,
"tag": "EMAIL",
"value": "colin@marketcetera.com"
},
{
"context": "* @author <a href=\"mailto:colin@marketcetera.com\">Colin DuPlantis</a>\n * @version $Id: SimulatedExchangeTest",
"end": 103447,
"score": 0.9998671412467957,
"start": 103432,
"tag": "NAME",
"value": "Colin DuPlantis"
},
{
"context": "ulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $\n * @since 2.0.0\n */\n privat",
"end": 103535,
"score": 0.9992938041687012,
"start": 103530,
"tag": "USERNAME",
"value": "colin"
}
] | null |
[] |
package org.marketcetera.marketdata;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.marketcetera.core.LoggerConfiguration;
import org.marketcetera.core.publisher.ISubscriber;
import org.marketcetera.event.*;
import org.marketcetera.event.impl.QuoteEventBuilder;
import org.marketcetera.event.impl.TradeEventBuilder;
import org.marketcetera.marketdata.SimulatedExchange.Token;
import org.marketcetera.marketdata.SimulatedExchange.TopOfBook;
import org.marketcetera.module.ExpectedFailure;
import org.marketcetera.options.ExpirationType;
import org.marketcetera.trade.*;
import org.marketcetera.trade.Currency;
import org.marketcetera.util.test.CollectionAssert;
import org.marketcetera.util.test.TestCaseBase;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
/* $License$ */
/**
* Tests {@link SimulatedExchange}.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
public class SimulatedExchangeTest
extends TestCaseBase
{
private SimulatedExchange exchange;
private final Equity metc = new Equity("METC");
private final Equity goog = new Equity("GOOG");
private final Option metc1Put = new Option(metc.getSymbol(),
"20100319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option metc1Call = new Option(metc1Put.getSymbol(),
metc1Put.getExpiry(),
metc1Put.getStrikePrice(),
OptionType.Call);
private final Option metc2Put = new Option(metc.getSymbol(),
"20110319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option metc2Call = new Option(metc2Put.getSymbol(),
metc2Put.getExpiry(),
metc2Put.getStrikePrice(),
OptionType.Call);
private final Option goog1Put = new Option(goog.getSymbol(),
"20100319",
EventTestBase.generateDecimalValue(),
OptionType.Put);
private final Option goog1Call = new Option(goog1Put.getSymbol(),
goog1Put.getExpiry(),
goog1Put.getStrikePrice(),
OptionType.Call);
private final Future brn201212 = new Future("BRN",
FutureExpirationMonth.DECEMBER,
2012);
private final Currency testCCY = new Currency("USD","INR","","");
private final Currency anotherCCY = new Currency("USD","GBP","","");
private BidEvent bid;
private AskEvent ask;
private BidEvent bidCCY;
private AskEvent askCCY;
private static final AtomicLong counter = new AtomicLong(0);
/**
* Executed once before all tests.
*
* @throws Exception if an error occurs
*/
@BeforeClass
public static void once()
throws Exception
{
LoggerConfiguration.logSetup();
}
/**
* Executed before each test.
*
* @throws Exception if an error occurs
*/
@Before
public void setup()
throws Exception
{
exchange = new SimulatedExchange("Test exchange",
"TEST");
assertFalse(metc.equals(goog));
bid = EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal("100"),
new BigDecimal("1000"));
// intentionally creating a large spread to make sure no trades get executed
ask = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
bidCCY = EventTestBase.generateCurrencyBidEvent(testCCY,
new BigDecimal("150"));
// intentionally creating a large spread to make sure no trades get executed
askCCY = EventTestBase.generateCurrencyAskEvent(testCCY,
new BigDecimal("500"));
}
/**
* Execute after each test.
*
* @throws Exception if an error occurs
*/
@After
public void teardown()
throws Exception
{
try {
exchange.stop();
} catch (Exception e) {}
}
/**
* Tests starting and stopping exchange already started and stopped.
*
* @throws Exception if an error occurs
*/
@Test
public void redundantStartAndStop()
throws Exception
{
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.stop();
}
};
exchange.start();
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.start();
}
};
}
/**
* Tests the <code>SimulatedExchange</code> constructors.
*
* @throws Exception if an error occurs
*/
@Test
public void constructors()
throws Exception
{
final String name = "name";
final String code = "code";
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(null,
code);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(null,
code,
1);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
null,
1);
}
};
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
code,
-2);
}
};
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
new SimulatedExchange(name,
code,
0);
}
};
verifyExchange(new SimulatedExchange(name,
code),
name,
code);
verifyExchange(new SimulatedExchange(name,
code,
100),
name,
code);
verifyExchange(new SimulatedExchange(name,
code,
OrderBook.UNLIMITED_DEPTH),
name,
code);
}
/**
* Tests snapshot requests.
*
* @throws Exception if an error occurs
*/
@Test
public void snapshots()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(null);
}
};
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(null);
}
};
// exchange is not started yet
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
// start the exchange with a script with only one event for each side of the book
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bid);
script.add(ask);
exchange.start(script);
// get the depth-of-book for the symbol
List<AskEvent> asks = new ArrayList<AskEvent>();
asks.add(ask);
List<BidEvent> bids = new ArrayList<BidEvent>();
bids.add(bid);
verifySnapshots(exchange,
metc,
null,
asks,
bids,
null);
// re-execute the same query (book already exists, make sure we're reading from the already existing book)
verifySnapshots(exchange,
metc,
null,
asks,
bids,
null);
// execute a request for an empty book
verifySnapshots(exchange,
goog,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
null);
exchange.stop();
// start the exchange again in scripted mode, this time with events in opposition to each other
script.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
ask.getPrice(),
ask.getSize()));
script.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.start(script);
// verify that the book is empty (but there should be an existing trade)
verifySnapshots(exchange,
metc,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
EventTestBase.generateEquityTradeEvent(1,
1,
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.stop();
// restart exchange in random mode
exchange.start();
// books are empty
doRandomBookCheck(exchange,
metc, null);
// re-execute (this time the book exists)
doRandomBookCheck(exchange,
metc, null);
}
/**
* Tests snapshot requests for currency.
*
* @throws Exception if an error occurs
*/
@Test
public void snapshotsWithCurrency()
throws Exception
{
// exchange is not started yet
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create());
}
};
// start the exchange with a script with only one event for each side of the book
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bidCCY);
script.add(askCCY);
exchange.start(script);
// get the depth-of-book for the symbol
List<AskEvent> asks = new ArrayList<AskEvent>();
asks.add(askCCY);
List<BidEvent> bids = new ArrayList<BidEvent>();
bids.add(bidCCY);
verifySnapshots(exchange,
testCCY,
null,
asks,
bids,
null);
// re-execute the same query (book already exists, make sure we're reading from the already existing book)
verifySnapshots(exchange,
testCCY,
null,
asks,
bids,
null);
// execute a request for an empty book
verifySnapshots(exchange,
anotherCCY,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
null);
exchange.stop();
// start the exchange again in scripted mode, this time with events in opposition to each other
script.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
ask.getPrice(),
ask.getSize()));
script.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.start(script);
// verify that the book is empty (but there should be an existing trade)
verifySnapshots(exchange,
metc,
null,
new ArrayList<AskEvent>(),
new ArrayList<BidEvent>(),
EventTestBase.generateEquityTradeEvent(1,
1,
metc,
exchange.getCode(),
bid.getPrice(),
bid.getSize()));
exchange.stop();
// restart exchange in random mode
exchange.start();
// books are empty
doRandomBookCheck(exchange,
metc, null);
// re-execute (this time the book exists)
doRandomBookCheck(exchange,
metc, null);
}
/**
* Tests snapshots using options instead of equities.
*
* <p>Note that this method doesn't have to re-execute all
* the equity tests - most of the code is identical.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void snapshotWithOptions()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateOptionBidEvent(metc1Put,
metc,
exchange.getCode());
BidEvent bid2 = EventTestBase.generateOptionBidEvent(metc1Call,
metc,
exchange.getCode());
BidEvent bid3 = EventTestBase.generateOptionBidEvent(metc2Put,
metc,
exchange.getCode());
BidEvent bid4 = EventTestBase.generateOptionBidEvent(metc2Call,
metc,
exchange.getCode());
script.add(bid1);
script.add(bid2);
script.add(bid3);
script.add(bid4);
// set up a few asks, too
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.optionAskEvent();
askBuilder.withExchange(exchange.getCode())
.withExpirationType(ExpirationType.AMERICAN)
.withQuoteDate(DateUtils.dateToString(new Date()))
.withUnderlyingInstrument(metc);
askBuilder.withInstrument(metc1Put);
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid1.getPrice().add(BigDecimal.ONE)).withSize(bid1.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1);
// and an ask that does cause a trade
askBuilder.withInstrument(metc2Put);
askBuilder.withPrice(bid3.getPrice()).withSize(bid3.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2);
// there should now be books for the underlying (metc) and 4 entries in the chain (metc1Put, metc1Call, metc2Put, and metc2Call)
exchange.start(script);
// verify the state of the options
verifySnapshots(exchange,
metc1Put,
metc,
Arrays.asList(new AskEvent[] { ask1 } ),
Arrays.asList(new BidEvent[] { bid1 } ),
null);
verifySnapshots(exchange,
metc1Call,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { bid2 } ),
null);
TradeEvent trade = TradeEventBuilder.tradeEvent(metc2Put).withExchange(bid3.getExchange())
.withExpirationType(((OptionEvent)bid3).getExpirationType())
.withPrice(bid3.getPrice())
.withSize(bid3.getSize())
.withTradeDate(bid3.getQuoteDate())
.withUnderlyingInstrument(metc).create();
verifySnapshots(exchange,
metc2Put,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { } ),
trade);
verifySnapshots(exchange,
metc2Call,
metc,
Arrays.asList(new AskEvent[] { } ),
Arrays.asList(new BidEvent[] { bid4 } ),
null);
// generate expected results for verifying snapshots for the underlying instrument
Map<Instrument,InstrumentState> expectedResults = new HashMap<Instrument,InstrumentState>();
expectedResults.put(metc1Put,
new InstrumentState(Arrays.asList(new BidEvent[] { bid1 }),
Arrays.asList(new AskEvent[] { ask1 }),
null));
expectedResults.put(metc1Call,
new InstrumentState(Arrays.asList(new BidEvent[] { bid2 }),
Arrays.asList(new AskEvent[] { }),
null));
expectedResults.put(metc2Put,
new InstrumentState(Arrays.asList(new BidEvent[] { }),
Arrays.asList(new AskEvent[] { }),
trade));
expectedResults.put(metc2Call,
new InstrumentState(Arrays.asList(new BidEvent[] { bid4 }),
Arrays.asList(new AskEvent[] { }),
null));
verifyUnderlyingSnapshots(exchange,
metc,
expectedResults);
// restart exchange in random mode
exchange.stop();
exchange.start();
// books are empty
// start traffic for each of the options in the metc chain
doRandomBookCheck(exchange,
metc1Put,
metc);
doRandomBookCheck(exchange,
metc1Call,
metc);
doRandomBookCheck(exchange,
metc2Put,
metc);
doRandomBookCheck(exchange,
metc2Call,
metc);
doRandomBookCheck(exchange,
goog1Put,
goog);
doRandomBookCheck(exchange,
goog1Call,
goog);
// re-execute (this time the books exist)
doRandomBookCheck(exchange,
metc1Put,
metc);
doRandomBookCheck(exchange,
metc1Call,
metc);
doRandomBookCheck(exchange,
metc2Put,
metc);
doRandomBookCheck(exchange,
metc2Call,
metc);
doRandomBookCheck(exchange,
goog1Put,
goog);
doRandomBookCheck(exchange,
goog1Call,
goog);
exchange.stop();
}
/**
* Tests that the <code>FilteringSubscriber</code> correctly tracks top-of-book state for Currency
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void subscriptionsWithCurrency()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateCurrencyBidEvent(testCCY, new BigDecimal(95));
BidEvent bid2 = EventTestBase.generateCurrencyBidEvent(testCCY, new BigDecimal(100));
script.add(bid1); // top1
script.add(bid2); // top2
// there are two entries for currency
// add an ask for just one instrument - make sure the bid and the ask don't match
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.currencyAskEvent();
askBuilder.withExchange(exchange.getCode())
.withQuoteDate(DateUtils.dateToString(new Date()))
.withInstrument(testCCY)
.withExchange(exchange.getCode());
askBuilder.withInstrument(bid2.getInstrument());
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.ONE)).withSize(bid2.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1); // top3
// this creates a nice, two-sided top-of-book for the instrument
// create a new ask for the same instrument that *won't* change the top - a new top should not be generated
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.TEN)).withSize(bid2.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2); // no top4!
// set up a subscriber to top-of-book for the underlying instrument metc
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(testCCY).create(),
topOfBook);
// start the exchange
exchange.start(script);
exchange.stop();
// measure the tops collected by the subscriber
// should have:
// a top for the bid1 instrument with just bid1
// a top for the bid2 instrument with just bid2
// a top for the bid2 instrument bid2-ask1
// no new top for ask2 - a total of three tops
assertEquals(3,topOfBook.getTops().size());
}
/**
* Tests that the <code>FilteringSubscriber</code> correctly tracks top-of-book state for
* different option chain members of the same underlying instrument.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void subscriptionsWithOptions()
throws Exception
{
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
// set up a book for a few options in a chain
BidEvent bid1 = EventTestBase.generateOptionBidEvent(metc1Put,
metc,
exchange.getCode());
BidEvent bid2 = EventTestBase.generateOptionBidEvent(metc1Call,
metc,
exchange.getCode());
script.add(bid1); // top1
script.add(bid2); // top2
// there are two entries in the option chain for metc
// add an ask for just one instrument in the option chain - make sure the bid and the ask don't match
QuoteEventBuilder<AskEvent> askBuilder = QuoteEventBuilder.optionAskEvent();
askBuilder.withExchange(exchange.getCode())
.withExpirationType(ExpirationType.AMERICAN)
.withQuoteDate(DateUtils.dateToString(new Date()))
.withUnderlyingInstrument(metc);
askBuilder.withInstrument(bid2.getInstrument());
// create an ask that is more than the bid to prevent a trade occurring (keeps the top populated)
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.ONE)).withSize(bid2.getSize());
AskEvent ask1 = askBuilder.create();
script.add(ask1); // top3
// this creates a nice, two-sided top-of-book for the instrument
// create a new ask for the same instrument that *won't* change the top - a new top should not be generated
askBuilder.withPrice(bid2.getPrice().add(BigDecimal.TEN)).withSize(bid2.getSize());
AskEvent ask2 = askBuilder.create();
script.add(ask2); // no top4!
// set up a subscriber to top-of-book for the underlying instrument metc
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(metc).create(),
topOfBook);
// start the exchange
exchange.start(script);
exchange.stop();
// measure the tops collected by the subscriber
// should have:
// a top for the bid1 instrument with just bid1
// a top for the bid2 instrument with just bid2
// a top for the bid2 instrument bid2-ask1
// no new top for ask2 - a total of three tops
assertEquals(3,
topOfBook.getTops().size());
}
/**
* Tests the ability to generate symbol statistics data.
*
* <p>Note that testing this is made challenging by the random nature of data generation
* for statistics.
*
* @throws Exception if an error occurs
*/
@Test
public void statistics()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getStatistics(null);
}
};
// exchange not started
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
// done with error conditions
exchange.start();
// quantities are random, even for subsequent calls and scripted mode, but
// there are some conditions we can expect the values to adhere to
for(int i=0;i<25000;i++) {
verifyStatistics(exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()));
}
for(int i=0;i<25000;i++) {
verifyStatistics(exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create()));
}
}
/**
* Tests the ability to receive statistics in a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void statisticSubscriber()
throws Exception
{
final AllEventsSubscriber equityStream = new AllEventsSubscriber();
final AllEventsSubscriber optionStream = new AllEventsSubscriber();
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
equityStream);
exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create(),
optionStream);
exchange.start();
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return equityStream.events.size() >= 15 &&
optionStream.events.size() >= 15;
}
});
List<MarketstatEvent> stats = new ArrayList<MarketstatEvent>();
for(Event event : equityStream.events) {
if(event instanceof MarketstatEvent) {
stats.add((MarketstatEvent)event);
}
}
for(Event event : optionStream.events) {
if(event instanceof MarketstatEvent) {
stats.add((MarketstatEvent)event);
}
}
verifyStatistics(stats);
}
/**
* Tests the ability to generate symbol dividends data.
*
* <p>Note that testing this is made challenging by the random nature of data generation
* for dividends.
*
* @throws Exception if an error occurs
*/
@Test
public void dividends()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(null);
}
};
// exchange not started
new ExpectedFailure<IllegalStateException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
}
};
exchange.start();
// dividends for an option
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(metc1Put)
.withUnderlyingInstrument(metc).create());
}
};
// dividends by underlying
new ExpectedFailure<IllegalArgumentException>() {
@Override
protected void run()
throws Exception
{
exchange.getDividends(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(metc).create());
}
};
for(int i=0;i<1000;i++) {
Equity e = new Equity(String.format("equity-%s",
i));
verifyDividends(exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(e).create()),
e);
}
}
/**
* Tests the ability to receive dividends in a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void dividendSubscriber()
throws Exception
{
final AllEventsSubscriber dividendStream = new AllEventsSubscriber();
exchange.start();
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Equity e = new Equity("e-" + counter.incrementAndGet());
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(e).create(),
dividendStream);
return dividendStream.events.size() >= 20;
}
});
// sleep for a couple of ticks to make sure we don't get extra dividends (the same dividends sent more than once)
Thread.sleep(5000);
Multimap<Equity,DividendEvent> dividends = LinkedListMultimap.create();
for(Event event : dividendStream.events) {
DividendEvent dividendEvent = (DividendEvent)event;
dividends.put(dividendEvent.getEquity(),
dividendEvent);
}
for(Equity equity : dividends.keySet()) {
verifyDividends(new ArrayList<DividendEvent>(dividends.get(equity)),
equity);
}
}
/**
* Tests subscribing to market data from an exchange.
*
* <p>This is a very complicated test due to the problem of generating complex expected
* results. Apologies in advance to anyone who has to review or modify this method. The general
* approach is to compile data structures that mimic the result (top-of-book, depth-of-book, etc)
* using {@link QuantityTuple} objects that mirror {@link QuoteEvent} objects.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptions()
throws Exception
{
new ExpectedFailure<NullPointerException>() {
@Override
protected void run()
throws Exception
{
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
null);
}
};
// generate a script with a number of bids and asks
BigDecimal baseValue = new BigDecimal("100.00");
BigDecimal bidSize = new BigDecimal("100");
BigDecimal askSize = new BigDecimal("50");
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
List<BidEvent> bids = new ArrayList<BidEvent>();
List<AskEvent> asks = new ArrayList<AskEvent>();
for(int i=0;i<5;i++) {
bids.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
baseValue.add(BigDecimal.ONE.multiply(new BigDecimal(i))),
bidSize));
}
for(int i=4;i>=0;i--) {
asks.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
baseValue.add(BigDecimal.ONE.multiply(new BigDecimal(i))),
askSize));
}
script.addAll(bids);
script.addAll(asks);
// add one outrageous ask to make the book interesting
AskEvent bigAsk = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(1000),
new BigDecimal(1000));
script.add(bigAsk);
// set up the subscriptions
TopOfBookSubscriber topOfBook = new TopOfBookSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
topOfBook);
AllEventsSubscriber tick = new AllEventsSubscriber();
exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
tick);
AllEventsSubscriber depthOfBook = new AllEventsSubscriber();
exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
depthOfBook);
// start the script
exchange.start(script);
// we can predict that the exchange will send 10 quote adds which will result in 5 trades and
// 10 quote corrections (bid/ask del/chg), 25 events altogether
// verify the results
// this list will hold all the expected events
List<QuantityTuple> allExpectedEvents = new ArrayList<QuantityTuple>();
List<BookEntryTuple> expectedTopOfBook = new ArrayList<BookEntryTuple>();
// the first events will be the bids
for(BidEvent bid : bids) {
QuantityTuple convertedBid = OrderBookTest.convertEvent(bid);
allExpectedEvents.add(convertedBid);
expectedTopOfBook.add(new BookEntryTuple(convertedBid,
null));
}
/*
bid | ask
-----------+---------
100 104.00 |
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
// next will be the asks interleaved with trades and corrections as the books are settled after each ask
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // 1st of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 104.00 | 104.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // bid correction (change)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 | 104.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // ask correction (delete)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 |
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // 2nd of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 104.00 | 103.00 50
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("104.00"), // bid correction (delete of fully consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 | 103.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // 3rd of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 103.00 | 102.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // bid correction (change of partially consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 | 102.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 |
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // 4th of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 103.00 | 101.00 50
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("103.00"), // bid correction (delete of fully consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 | 101.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("101.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // 5th of 5 asks
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
100 102.00 | 100.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // resulting trade
new BigDecimal("50"),
TradeEvent.class));
allExpectedEvents.add(new QuantityTuple(new BigDecimal("102.00"), // bid correction (change of partially consumed bid)
new BigDecimal("50"),
BidEvent.class));
/*
bid | ask
-----------+-----------
50 102.00 | 100.00 50
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(new BigDecimal("100.00"), // ask correction (delete of fully consumed ask)
new BigDecimal("50"),
AskEvent.class));
/*
bid | ask
-----------+-----------
50 102.00 |
100 101.00 |
100 100.00 |
*/
allExpectedEvents.add(new QuantityTuple(bigAsk.getPrice(), // big ask
bigAsk.getSize(),
AskEvent.class));
/*
bid | ask
-----------+-------------
50 102.00 | 1000.00 1000
100 101.00 |
100 100.00 |
*/
// prepare the expected top-of-book results
expectedTopOfBook.addAll(Arrays.asList(new BookEntryTuple[] {
/* 100 104.00 | 104.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 104.00 | 104.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 104.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 104.00 | 103.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("104.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 103.00 | 103.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 103.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
null),
/* 100 103.00 | 102.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 103.00 | 102.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 103.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 103.00 | 101.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("103.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("101.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 102.00 | 101.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("101.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 100 102.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
null),
/* 100 102.00 | 100.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("100"),
BidEvent.class),
new QuantityTuple(new BigDecimal("100.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 102.00 | 100.00 50 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("100.00"),
new BigDecimal("50"),
AskEvent.class)),
/* 50 102.00 | */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
null),
/* 50 102.00 | 1000 1000 */
new BookEntryTuple(new QuantityTuple(new BigDecimal("102.00"),
new BigDecimal("50"),
BidEvent.class),
new QuantityTuple(new BigDecimal("1000"),
new BigDecimal("1000"),
AskEvent.class)),
}));
// prepare the expected latest tick results
List<QuantityTuple> expectedLatestTicks = new ArrayList<QuantityTuple>();
// prepare the expected depth-of-book results
List<QuantityTuple> expectedDepthOfBook = new ArrayList<QuantityTuple>();
for(QuantityTuple tuple : allExpectedEvents) {
if(tuple.getType().equals(TradeEvent.class)) {
expectedLatestTicks.add(tuple);
} else {
expectedDepthOfBook.add(tuple);
}
}
// ready to verify results
verifySubscriptions(topOfBook.getTops(),
expectedTopOfBook,
tick.events,
expectedLatestTicks,
depthOfBook.events,
expectedDepthOfBook);
}
/**
* Tests that subscribers to different exchanges for the same type of data
* get only the data they are supposed to.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptionTargeting()
throws Exception
{
// create two different exchanges (one already exists, of course)
SimulatedExchange exchange2 = new SimulatedExchange("Test exchange 2",
"TEST2");
assertFalse(exchange.equals(exchange2));
// create two different subscribers
AllEventsSubscriber sub1 = new AllEventsSubscriber();
AllEventsSubscriber sub2 = new AllEventsSubscriber();
// set up the subscriptions
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
sub1);
exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
sub2);
// create an event targeted to the second exchange
AskEvent ask2 = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange2.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
// create an event targeted to the second exchange but with the wrong symbol
AskEvent ask3 = EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
goog,
exchange2.getCode(),
new BigDecimal("150"),
new BigDecimal("500"));
// create two different scripts
// the events that are targeted to the wrong exchange or symbol should get skipped
List<QuoteEvent> script1 = new ArrayList<QuoteEvent>();
script1.add(bid);
script1.add(ask2);
script1.add(ask3);
List<QuoteEvent> script2 = new ArrayList<QuoteEvent>();
script2.add(ask2);
script2.add(bid);
script2.add(ask3);
// start the exchanges
exchange.start(script1);
exchange2.start(script2);
// measure the results
assertEquals(1,
sub1.events.size());
assertEquals(bid,
sub1.events.get(0));
assertEquals(1,
sub2.events.size());
assertEquals(ask2,
sub2.events.get(0));
}
/**
* Tests that an over-filled (according to its max depth) order book gets pruned.
*
* @throws Exception if an error occurs
*/
@Test
public void bookPruning()
throws Exception
{
// create an exchange with a small maximum depth (2)
exchange = new SimulatedExchange("Test exchange",
"TEST",
2);
// create a script of events that will exceed the max on both sides of the book
// note that the spread is intentionally large in order to prevent any trades
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
List<AskEvent> asks = new ArrayList<AskEvent>();
List<BidEvent> bids = new ArrayList<BidEvent>();
for(int i=0;i<3;i++) {
bids.add(EventTestBase.generateEquityBidEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(10-i),
new BigDecimal("1000")));
asks.add(EventTestBase.generateEquityAskEvent(counter.incrementAndGet(),
System.currentTimeMillis(),
metc,
exchange.getCode(),
new BigDecimal(100+i),
new BigDecimal("1000")));
}
script.addAll(bids);
script.addAll(asks);
exchange.start(script);
// now, trim the oldest (first) bid and ask from each list to simulate the pruning
bids.remove(0);
asks.remove(0);
// check the results
verifyDepthOfBook(exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()),
asks,
bids);
}
/**
* Tests canceling a subscription.
*
* @throws Exception if an error occurs
*/
@Test
public void subscriptionCanceling()
throws Exception
{
final AllEventsSubscriber stream1 = new AllEventsSubscriber();
final AllEventsSubscriber stream2 = new AllEventsSubscriber();
SimulatedExchange.Token t1 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream1);
SimulatedExchange.Token t2 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream2);
assertFalse(t1.equals(t2));
assertFalse(t1.hashCode() == t2.hashCode());
exchange.start();
// start the exchange in random mode (wait until a reasonable number of events comes in)
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream1.events.size() >= 10;
}
});
// t2 should have received at least the same number of events (won't be deterministically in
// sync)
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream2.events.size() >= 10;
}
});
// both subscribers have now received at least 10 events (this shows us that they're
// both receiving events)
// now, cancel one subscription - note that since it's async, we can't guarantee that
// no more than 10 events will come (one may have come in even while you read this
// comment)
t1.cancel();
// some time very shortly (certainly in the next minute), updates should stop coming in
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
int currentCount = stream1.events.size();
// at least 2 events should come in every second, so by waiting 2.5 seconds,
// we should be able to tell with a reasonable degree of confidence that
// no new events are coming in
Thread.sleep(2500);
return stream1.events.size() == currentCount;
}
});
int stream1Count = stream1.events.size();
int stream2Count = stream2.events.size();
// stream2 is still receiving events, but stream1 is not
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream2.events.size() >= 20;
}
});
// the size of stream2 has grown
assertTrue(stream2.events.size() >= stream2Count);
// the size of stream1 has not
assertEquals(stream1Count,
stream1.events.size());
// cancel the same thing again just to make sure nothing flies off the handle
t1.cancel();
}
/**
* Tests the ability to subscribe before and after the exchange starts.
*
* @throws Exception if an error occurs
*/
@Test
public void subscribeBeforeAndAfterStart()
throws Exception
{
final AllEventsSubscriber stream1 = new AllEventsSubscriber();
final AllEventsSubscriber stream2 = new AllEventsSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream1);
exchange.start();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
stream2);
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
Thread.sleep(250);
return stream1.events.size() >= 10 &&
stream2.events.size() >= 10;
}
});
}
/**
* Tests that a scripted exchange doesn't start new activity after running its
* script.
*
* @throws Exception if an error occurs
*/
@Test
public void otherSymbolsFromScriptedExchange()
throws Exception
{
// start the exchange in scripted mode with two events for METC
List<QuoteEvent> script = new ArrayList<QuoteEvent>();
script.add(bid);
script.add(ask);
exchange.start(script);
// allow the exchange the opportunity to do something off the script, if it's going to
Thread.sleep(5000);
// verify the top for METC
verifyTopOfBook(makeTopOfBook(exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create())),
ask,
bid);
// verify that nothing's there for GOOG
assertTrue(exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(goog).create()).isEmpty());
}
/**
* Tests that exchanges initially have closely grouped values for the same symbol.
*
* @throws Exception if an error occurs
*/
@Test
public void valueSync()
throws Exception
{
// create two extra exchanges
final SimulatedExchange exchange2 = new SimulatedExchange("Test Exchange2",
"TEST2");
final SimulatedExchange exchange3 = new SimulatedExchange("Test Exchange3",
"TEST3");
// start all three in random mode (note that exchange-sync behavior does not apply to scripted mode)
exchange.start();
exchange2.start();
exchange3.start();
// all three are ticking over, but the books are not yet populated
// wait until the book is populated for METC
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
// the book for METC has at least an ask and bid in it, grab the value
List<QuoteEvent> top1 = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// now, issue the same request for exchange2
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
List<QuoteEvent> top2 = exchange2.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// and exchange3
MarketDataFeedTestBase.wait(new Callable<Boolean>() {
@Override
public Boolean call()
throws Exception
{
return exchange3.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create()).size() == 2;
}
});
List<QuoteEvent> top3 = exchange3.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create());
// we cannot guarantee how many ticks (if any) have happened during the course of these
// instructions. regardless, each of the exchanges has
// a book for METC with at least a bid and ask. it's unlikely they're exactly the same, but
// they can have varied by no more than .01/second. the absolute maximum that is possible is limited
// by about 3 minutes (each of the wait calls could take just under 60 seconds without failing).
// so, we'll say that the most the values could have changed is 2.50 (that's equivalent to
// a bit over 4 minutes of run time with one tick/second).
// the default book start values vary between (0.01,99.99), the odds of three values hitting the
// same 5.00 interval randomly without sync are not large, about 1.25 in 10,000). the worst case for
// this test is a false negative, that is, sync isn't working and all three books randomly start
// in the same interval. since this should happen a little more often than once in 10,000, that
// makes this test effective enough.
assertTrue(((MarketDataEvent)top1.get(0)).getPrice().subtract(((MarketDataEvent)top2.get(0)).getPrice()).abs().intValue() < 3);
assertTrue(((MarketDataEvent)top1.get(0)).getPrice().subtract(((MarketDataEvent)top3.get(0)).getPrice()).abs().intValue() < 3);
}
/**
* Tests the output of the exchange in random mode.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void randomModeOutput()
throws Exception
{
exchange.start();
// start the exchange in random mode
final AllEventsSubscriber all = new AllEventsSubscriber();
exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(metc).create(),
all);
// this block should actually take less than 30s - there are 2 new events/sec and every now and then
// a trade will create a few extras
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 60;
}
});
exchange.stop();
}
/**
* Tests the ability of the exchange to deliver a non-zero and non-one contract size.
*
* @throws Exception if an unexpected error occurs
*/
@Test
public void testFutureContractSize()
throws Exception
{
exchange.start();
final AllEventsSubscriber all = new AllEventsSubscriber();
Token token = exchange.getTopOfBook(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getLatestTick(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
exchange.cancel(token);
all.events.clear();
token = exchange.getStatistics(ExchangeRequestBuilder.newRequest().withInstrument(brn201212).create(),
all);
MarketDataFeedTestBase.wait(new Callable<Boolean>(){
@Override
public Boolean call()
throws Exception
{
return all.events.size() >= 10;
}
});
for(Event event : all.events) {
assertTrue(event instanceof FutureEvent);
assertEquals(100,
((FutureEvent)event).getContractSize());
}
}
/**
* Executes a test to make sure that the given <code>Instrument</code> and underlying <code>Instrument</code>
* get order books created for them.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inInstrument an <code>Instrument</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value
* @throws Exception if an unexpected error occurs
*/
private void doRandomBookCheck(SimulatedExchange inExchange,
Instrument inInstrument,
Instrument inUnderlyingInstrument)
throws Exception
{
List<QuoteEvent> dob = inExchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withInstrument(inInstrument)
.withUnderlyingInstrument(inUnderlyingInstrument).create());
// note that since the exchange was started this time in random mode we don't know exactly what the
// values will be, but there should be at least one entry on each side of the book
assertFalse(dob.isEmpty());
boolean foundAsk = false;
boolean foundBid = false;
for(Event event : dob) {
if(event instanceof BidEvent) {
foundBid = true;
} else if(event instanceof AskEvent) {
foundAsk = true;
}
}
assertTrue(foundBid);
assertTrue(foundAsk);
// repeat, checking by underlying instrument only
if(inUnderlyingInstrument != null) {
dob = inExchange.getDepthOfBook(ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(inUnderlyingInstrument).create());
assertFalse(dob.isEmpty());
foundAsk = false;
foundBid = false;
for(Event event : dob) {
if(event instanceof BidEvent) {
foundBid = true;
} else if(event instanceof AskEvent) {
foundAsk = true;
}
}
assertTrue(foundBid);
assertTrue(foundAsk);
}
}
/**
* Verifies the given actual subscriptions against the expected results.
*
* @param inActualTopOfBook a <code>List<Pair<BidEvent,AskEvent>></code> value
* @param inExpectedTopOfBook a <code>List<BookEntryTuple></code> value
* @param inActualTicks a <code>List<EventBase></code> value
* @param inExpectedTicks a <code>List<QuantityTuple></code> value
* @param inActualDepthOfBook a <code>List<EventBase></code> value
* @param inExpectedDepthOfBook a <code>List<QuantityTuple></code> value
* @throws Exception if an error occurs
*/
private void verifySubscriptions(List<TopOfBook> inActualTopOfBook,
List<BookEntryTuple> inExpectedTopOfBook,
List<Event> inActualTicks,
List<QuantityTuple> inExpectedTicks,
List<Event> inActualDepthOfBook,
List<QuantityTuple> inExpectedDepthOfBook)
throws Exception
{
// test top-of-book
assertEquals(inExpectedTopOfBook.size(),
inActualTopOfBook.size());
List<BookEntryTuple> actualTopOfBook = new ArrayList<BookEntryTuple>();
for(TopOfBook top : inActualTopOfBook) {
actualTopOfBook.add(new BookEntryTuple(OrderBookTest.convertEvent(top.getFirstMember()),
OrderBookTest.convertEvent(top.getSecondMember())));
}
assertEquals(inExpectedTopOfBook,
actualTopOfBook);
// test latest-tick
assertEquals(inExpectedTicks,
OrderBookTest.convertEvents(inActualTicks));
// test depth-of-book
assertEquals(inExpectedDepthOfBook.size(),
inActualDepthOfBook.size());
assertEquals(inExpectedDepthOfBook,
OrderBookTest.convertEvents(inActualDepthOfBook));
}
/**
* Verifies symbol statistical data.
*
* @param inStatistics a <code>List<MarketstatEvent></code> value containing the actual value
* @throws Exception if an error occurs
*/
private void verifyStatistics(List<MarketstatEvent> inStatistics)
throws Exception
{
for(MarketstatEvent stat : inStatistics) {
assertNotNull(stat.getOpen());
assertNotNull(stat.getHigh());
assertNotNull(stat.getLow());
assertNotNull(stat.getClose());
assertNotNull(stat.getPreviousClose());
assertNotNull(stat.getVolume());
assertNotNull(stat.getCloseDate());
assertNotNull(stat.getPreviousCloseDate());
assertNotNull(stat.getTradeHighTime());
assertNotNull(stat.getTradeLowTime());
assertNotNull(stat.getOpenExchange());
assertNotNull(stat.getCloseExchange());
assertNotNull(stat.getHighExchange());
assertNotNull(stat.getLowExchange());
Instrument instrument = stat.getInstrument();
if(instrument instanceof Option) {
assertNotNull(((OptionMarketstatEvent)stat).getInterestChange());
assertNotNull(((OptionMarketstatEvent)stat).getVolumeChange());
}
}
}
/**
* Verifies symbol dividends.
*
* @param inDividends a <code>List<Marketstatevent></code> value
* @param inEquity an <code>Equity</code> value
* @throws Exception if an unexpected error occurs
*/
private void verifyDividends(List<DividendEvent> inDividends,
Equity inEquity)
throws Exception
{
// make sure that the dividends we got match the dividends we get a second
// time for the same equity
assertEquals(inDividends,
exchange.getDividends(ExchangeRequestBuilder.newRequest().withInstrument(inEquity).create()));
if(!inDividends.isEmpty()) {
assertEquals(4,
inDividends.size());
DividendEvent currentDividend = inDividends.get(0);
assertTrue(currentDividend.getAmount().compareTo(BigDecimal.ZERO) == 1);
assertEquals("USD",
currentDividend.getCurrency());
assertEquals(inEquity,
currentDividend.getEquity());
Date today = new Date();
assertNotNull(currentDividend.getDeclareDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getDeclareDate())));
assertNotNull(currentDividend.getExecutionDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getExecutionDate())));
assertNotNull(currentDividend.getPaymentDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getPaymentDate())));
assertNotNull(currentDividend.getRecordDate());
assertTrue(today.after(DateUtils.stringToDate(currentDividend.getRecordDate())));
assertEquals(DividendFrequency.QUARTERLY,
currentDividend.getFrequency());
assertEquals(DividendStatus.OFFICIAL,
currentDividend.getStatus());
assertEquals(DividendType.CURRENT,
currentDividend.getType());
// now check future dividends
for(int counter=1;counter<=3;counter++) {
DividendEvent futureDividend = inDividends.get(counter);
assertTrue(futureDividend.getAmount().compareTo(BigDecimal.ZERO) == 1);
assertEquals("USD",
futureDividend.getCurrency());
assertEquals(inEquity,
futureDividend.getEquity());
assertEquals(DividendFrequency.QUARTERLY,
futureDividend.getFrequency());
assertEquals(DividendStatus.UNOFFICIAL,
futureDividend.getStatus());
assertEquals(DividendType.FUTURE,
futureDividend.getType());
assertNull(futureDividend.getDeclareDate());
assertNull(futureDividend.getPaymentDate());
assertNull(futureDividend.getRecordDate());
String executionDate = futureDividend.getExecutionDate();
assertNotNull(executionDate);
assertTrue(today.before(DateUtils.stringToDate(executionDate)));
}
}
}
/**
* Verifies that the given exchange and symbol will produce the expected snapshots.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inInstrument an <code>Instrument</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value or <code>null</code>
* @param inExpectedAsks a <code>List<AskEvent></code> value
* @param inExpectedBids a <code>List<BidEvent></code> value
* @throws Exception if an error occurs
*/
private void verifySnapshots(SimulatedExchange inExchange,
Instrument inInstrument,
Instrument inUnderlyingInstrument,
List<AskEvent> inExpectedAsks,
List<BidEvent> inExpectedBids,
TradeEvent inExpectedLatestTick)
throws Exception
{
ExchangeRequest request = ExchangeRequestBuilder.newRequest().withInstrument(inInstrument)
.withUnderlyingInstrument(inUnderlyingInstrument).create();
verifyDepthOfBook(inExchange.getDepthOfBook(request),
inExpectedAsks,
inExpectedBids);
verifyTopOfBook(makeTopOfBook(inExchange.getTopOfBook(request)),
inExpectedAsks.isEmpty() ? null : inExpectedAsks.get(0),
inExpectedBids.isEmpty() ? null : inExpectedBids.get(0));
assertEquals(OrderBookTest.convertEvent(inExpectedLatestTick),
OrderBookTest.convertEvent(exchange.getLatestTick(request).get(0)));
}
/**
* Verifies that the underlying instrument leads to the given expected states in the
* given exchange.
*
* @param inExchange a <code>SimulatedExchange</code> value
* @param inUnderlyingInstrument an <code>Instrument</code> value
* @param inExpectedStates a <code>Map<Instrument,InstrumentState></code> value
* @throws Exception if an unexpected error occurs
*/
private void verifyUnderlyingSnapshots(SimulatedExchange inExchange,
Instrument inUnderlyingInstrument,
Map<Instrument,InstrumentState> inExpectedStates)
throws Exception
{
ExchangeRequest request = ExchangeRequestBuilder.newRequest().withUnderlyingInstrument(inUnderlyingInstrument).create();
EventOrganizer.process(inExchange.getTopOfBook(request),
EventOrganizer.RequestType.TOP_OF_BOOK);
EventOrganizer.process(inExchange.getDepthOfBook(request),
EventOrganizer.RequestType.DEPTH_OF_BOOK);
EventOrganizer.process(inExchange.getLatestTick(request),
EventOrganizer.RequestType.LATEST_TICK);
EventOrganizer.process(inExchange.getStatistics(request),
EventOrganizer.RequestType.MARKET_STAT);
// all the actual events have been collected and organized, examine them
for(Map.Entry<Instrument,InstrumentState> entry : inExpectedStates.entrySet()) {
InstrumentState expectedState = inExpectedStates.get(entry.getKey());
EventOrganizer organizer = EventOrganizer.organizers.remove(entry.getKey());
assertNotNull("No actual results for " + entry.getKey(),
organizer);
verifyTopOfBook(organizer.getTop(),
expectedState.asks.isEmpty() ? null : expectedState.asks.get(0),
expectedState.bids.isEmpty() ? null : expectedState.bids.get(0));
verifyDepthOfBook(organizer.depthOfBook,
expectedState.asks,
expectedState.bids);
verifyStatistics(Arrays.asList(new MarketstatEvent[] { organizer.marketstat } ));
assertEquals(OrderBookTest.convertEvent(organizer.latestTrade),
OrderBookTest.convertEvent(expectedState.latestTrade));
}
}
/**
* Creates a <code>TopOfBook</code> object from the given list.
*
* @param inEvents a <code>List<QuoteEvent></code> value
* @return a <code>TopOfBook</code> value
* @throws Exception if an unexpected error occurs
*/
private static TopOfBook makeTopOfBook(List<QuoteEvent> inEvents)
throws Exception
{
assertTrue("An instrument should have a single top-of-book",
inEvents.size() <= 2);
BidEvent bid = null;
AskEvent ask = null;
if(inEvents.size() == 2) {
bid = (BidEvent)inEvents.get(0);
ask = (AskEvent)inEvents.get(1);
} else if(inEvents.size() == 1) {
Event e = inEvents.get(0);
if(e instanceof BidEvent) {
bid = (BidEvent)e;
} else if(e instanceof AskEvent) {
ask = (AskEvent)e;
} else {
fail("Unknown contents in top-of-book: " + e);
}
}
return new TopOfBook(bid,
ask);
}
/**
* Verifies the given actual<code>TopOfBook</code> contains the expected values.
*
* @param inActualTopOfBook a <code>TopOfBook</code> value
* @param inAsk a <code>AskEvent</code> value
* @param inBid a <code>BidEvent</code> value
* @throws Exception if an error occurs
*/
private void verifyTopOfBook(TopOfBook inActualTopOfBook,
AskEvent inExpectedAsk,
BidEvent inExpectedBid)
throws Exception
{
assertEquals(OrderBookTest.convertEvent(inExpectedBid),
OrderBookTest.convertEvent(inActualTopOfBook.getBid()));
assertEquals(OrderBookTest.convertEvent(inExpectedAsk),
OrderBookTest.convertEvent(inActualTopOfBook.getAsk()));
}
/**
* Verifies that the given exchange has the given expected attributes.
*
* @param inActualExchange a <code>SimulatedExchange</code> value
* @param inExpectedName a <code>String</code> value
* @param inExpectedCode a <code>String</code> value
* @throws Exception if an error occurs
*/
private void verifyExchange(SimulatedExchange inActualExchange,
String inExpectedName,
String inExpectedCode)
throws Exception
{
assertEquals(inExpectedName,
inActualExchange.getName());
assertEquals(inExpectedCode,
inActualExchange.getCode());
}
/**
* Verifies that the given <code>AggregateEvent</code> decomposes into the
* given expected events.
*
* <p>No guarantee is made as to the order of the events.
*
* @param inActualEvent an <code>AggregateEvent</code> value
* @param inExpectedEvents a <code>List<Event></code> value
* @throws Exception if an error occurs
*/
final static void verifyDecomposedEvents(AggregateEvent inActualEvent,
List<Event> inExpectedEvents)
throws Exception
{
CollectionAssert.assertArrayPermutation(inExpectedEvents.toArray(),
inActualEvent.decompose().toArray());
}
/**
* Verifies the given actual <code>DepthOfBook</code> contains the expected values.
*
* @param inActualDepthOfBook a <code>List<QuoteEvent></code> value
* @param inExpectedAsks a <code>List<AskEvent></code> value
* @param inExpectedBids a <code>List<BidEvent></code> value
* @throws Exception if an error occurs
*/
public static void verifyDepthOfBook(List<QuoteEvent> inActualDepthOfBook,
List<AskEvent> inExpectedAsks,
List<BidEvent> inExpectedBids)
throws Exception
{
List<BidEvent> actualBids = new ArrayList<BidEvent>();
List<AskEvent> actualAsks = new ArrayList<AskEvent>();
for(Event event : inActualDepthOfBook) {
if(event instanceof BidEvent) {
actualBids.add((BidEvent)event);
} else if(event instanceof AskEvent) {
actualAsks.add((AskEvent)event);
}
}
assertEquals(OrderBookTest.convertEvents(inExpectedAsks),
OrderBookTest.convertEvents(actualAsks));
assertEquals(OrderBookTest.convertEvents(inExpectedBids),
OrderBookTest.convertEvents(actualBids));
}
/**
* Subscribes to top-of-book and captures the state of the exchange top every time it changes.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
@ThreadSafe
private static class TopOfBookSubscriber
implements ISubscriber
{
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#isInteresting(java.lang.Object)
*/
@Override
public boolean isInteresting(Object inData)
{
return inData instanceof QuoteEvent;
}
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#publishTo(java.lang.Object)
*/
@Override
public synchronized void publishTo(Object inData)
{
QuoteEvent quote = (QuoteEvent)inData;
BidEvent lastBid = lastBids.get(quote.getInstrument());
AskEvent lastAsk = lastAsks.get(quote.getInstrument());
BidEvent newBid = (quote instanceof BidEvent ? quote.getAction() == QuoteAction.DELETE ? null : (BidEvent)quote : lastBid);
AskEvent newAsk = (quote instanceof AskEvent ? quote.getAction() == QuoteAction.DELETE ? null : (AskEvent)quote : lastAsk);
tops.add(new TopOfBook(newBid,
newAsk));
lastBids.put(quote.getInstrument(),
newBid);
lastAsks.put(quote.getInstrument(),
newAsk);
}
/**
*
*
*
* @return
*/
private List<TopOfBook> getTops()
{
return Collections.unmodifiableList(tops);
}
/**
* the events received
*/
@GuardedBy("this")
private final List<TopOfBook> tops = new ArrayList<TopOfBook>();
/**
* the latest ask received, may be <code>null</code>
*/
@GuardedBy("this")
private final Map<Instrument,AskEvent> lastAsks = new HashMap<Instrument,AskEvent>();
/**
* the latest bid received, may be <code>null</code>
*/
@GuardedBy("this")
private final Map<Instrument,BidEvent> lastBids = new HashMap<Instrument,BidEvent>();
}
/**
* Captures any events from a <code>SimulatedExchange</code>.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 1.5.0
*/
private static class AllEventsSubscriber
implements ISubscriber
{
/**
* the events received
*/
private final List<Event> events = new ArrayList<Event>();
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#isInteresting(java.lang.Object)
*/
@Override
public boolean isInteresting(Object inData)
{
return true;
}
/* (non-Javadoc)
* @see org.marketcetera.core.publisher.ISubscriber#publishTo(java.lang.Object)
*/
@Override
public void publishTo(Object inData)
{
events.add((Event)inData);
}
}
/**
* Describes the expected state of a given <code>Instrument</code> in an unspecified exchange
* at an unspecified point in time.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static class InstrumentState
{
/**
* Create a new InstrumentState instance.
*
* @param inBids a <code>List<BidEvent></code> value
* @param inAsks a <code>List<AskEvent></code> value
* @param inTrade a <code>TradeEvent</code> value
*/
private InstrumentState(List<BidEvent> inBids,
List<AskEvent> inAsks,
TradeEvent inTrade)
{
bids = inBids;
asks = inAsks;
latestTrade = inTrade;
}
/**
* the expected bids, may be empty
*/
private final List<BidEvent> bids;
/**
* the expected asks, may be empty
*/
private final List<AskEvent> asks;
/**
* the expected trade, may be <code>null</code>
*/
private final TradeEvent latestTrade;
}
/**
* Organizes actual results from an exchange by <code>Instrument</code>.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static class EventOrganizer
{
/**
* Process the given events to make them available by <code>Instrument</code> and purpose.
*
* @param inEvents a <code>List<? extends Event></code> value
* @param inRequestType a <code>RequestType</code> value
*/
private static void process(List<? extends Event> inEvents,
RequestType inRequestType)
{
Multimap<EventOrganizer,Event> sortedEvents = LinkedHashMultimap.create();
for(Event event : inEvents) {
if(event instanceof HasInstrument) {
Instrument instrument = ((HasInstrument)event).getInstrument();
EventOrganizer organizer = organizers.get(instrument);
if(organizer == null) {
organizer = new EventOrganizer();
organizers.put(instrument,
organizer);
}
sortedEvents.put(organizer,
event);
}
}
for(EventOrganizer organizer : sortedEvents.keySet()) {
Collection<Event> events = sortedEvents.get(organizer);
switch(inRequestType) {
case LATEST_TICK :
organizer.latestTrade = null;
if(events.size() > 1) {
fail("Unable to translate " + events + " as latest tick (should be one event)");
}
if(!events.isEmpty()) {
organizer.latestTrade = (TradeEvent)events.iterator().next();
}
break;
case MARKET_STAT :
organizer.marketstat = null;
if(events.size() > 1) {
fail("Unable to translate " + events + " as marketstat (should be one event)");
}
if(!events.isEmpty()) {
organizer.marketstat = (MarketstatEvent)events.iterator().next();
}
break;
case TOP_OF_BOOK :
organizer.topOfBook.clear();
for(Event event : events) {
if(event instanceof QuoteEvent) {
organizer.topOfBook.add((QuoteEvent)event);
}
}
break;
case DEPTH_OF_BOOK :
organizer.depthOfBook.clear();
for(Event event : events) {
if(event instanceof QuoteEvent) {
organizer.depthOfBook.add((QuoteEvent)event);
}
}
break;
default :
fail("Unexpected request type");
}
}
}
/**
* Gets the <code>TopOfBook</code> that represents the current state of {@link #topOfBook}.
*
* @return a <code>TopOfBook</code> value
*/
private TopOfBook getTop()
{
assertTrue("There are too many events in the top-of-book collection",
topOfBook.size() <= 2);
BidEvent bid = null;
AskEvent ask = null;
while(!topOfBook.isEmpty()) {
Event event = topOfBook.remove(0);
if(event instanceof BidEvent) {
bid = (BidEvent)event;
} else if(event instanceof AskEvent) {
ask = (AskEvent)event;
}
}
return new TopOfBook(bid,
ask);
}
/**
* the set of event organizers by instrument
*/
private static Map<Instrument,EventOrganizer> organizers = new HashMap<Instrument,EventOrganizer>();
/**
* the current depth-of-book for this instrument
*/
private final List<QuoteEvent> depthOfBook = new ArrayList<QuoteEvent>();
/**
* the current top-of-book for this instrument
*/
private final List<QuoteEvent> topOfBook = new ArrayList<QuoteEvent>();
/**
* the current lates trade for this instrument
*/
private TradeEvent latestTrade = null;
/**
* the current marketstat for this instrument
*/
private MarketstatEvent marketstat;
/**
* Indicates the type of request made to the exchange.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: SimulatedExchangeTest.java 16395 2012-12-10 16:29:14Z colin $
* @since 2.0.0
*/
private static enum RequestType
{
LATEST_TICK,
TOP_OF_BOOK,
MARKET_STAT,
DEPTH_OF_BOOK
}
}
}
| 103,589 | 0.503552 | 0.486056 | 2,327 | 43.577999 | 28.684431 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567684 | false | false |
15
|
ef9bfebe9b3960aca800fa58bba31a865e5ac119
| 5,291,399,733,025 |
475f60f76f132f9528fa33d155957d037c2e12f8
|
/app/src/main/java/com/bysj/imageutil/sqlite/ImgSqlHelper.java
|
d4c60f13ade9e36e322d00faa602ec703400f704
|
[
"Apache-2.0"
] |
permissive
|
AivenLi/ImageUtil
|
https://github.com/AivenLi/ImageUtil
|
72d99328ba50e93dfc77c7ce77e576782e7192e1
|
8c887486f87fcb3727027e231ebd6fa629d5f9b6
|
refs/heads/main
| 2023-04-03T14:20:55.530000 | 2021-04-07T03:56:45 | 2021-04-07T03:56:45 | 334,087,237 | 5 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.bysj.imageutil.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
/**
* 操作CacheImgDBHelper中的数据库帮助类
*
* Create on 2021-2-27
*/
public class ImgSqlHelper {
private static final String TAG = "imgSqlHelper";
private static final String tableName = CacheImgDBHelper.TABLE_NAME;
private static ImgSqlHelper mInstance = null;
private CacheImgDBHelper ciDBHelper;
private SQLiteDatabase db;
public static ImgSqlHelper getInstance(Context context) {
if ( mInstance == null ) {
synchronized (ImgSqlHelper.class) {
mInstance = new ImgSqlHelper(context);
}
}
return mInstance;
}
private ImgSqlHelper(Context context) {
ciDBHelper = new CacheImgDBHelper(context, null, 1);
}
}
|
UTF-8
|
Java
| 868 |
java
|
ImgSqlHelper.java
|
Java
|
[] | null |
[] |
package com.bysj.imageutil.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
/**
* 操作CacheImgDBHelper中的数据库帮助类
*
* Create on 2021-2-27
*/
public class ImgSqlHelper {
private static final String TAG = "imgSqlHelper";
private static final String tableName = CacheImgDBHelper.TABLE_NAME;
private static ImgSqlHelper mInstance = null;
private CacheImgDBHelper ciDBHelper;
private SQLiteDatabase db;
public static ImgSqlHelper getInstance(Context context) {
if ( mInstance == null ) {
synchronized (ImgSqlHelper.class) {
mInstance = new ImgSqlHelper(context);
}
}
return mInstance;
}
private ImgSqlHelper(Context context) {
ciDBHelper = new CacheImgDBHelper(context, null, 1);
}
}
| 868 | 0.666274 | 0.65684 | 36 | 22.555555 | 22.675787 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361111 | false | false |
15
|
d500b8bd7ad66dc837599764a3b490a0754ebbdb
| 5,291,399,732,513 |
9c19e7ac5333ac47e3b0792c1c6bcecd9cec0d6a
|
/src/utilities/Excel.java
|
c25d0bb500e9b9be44c3ec8ec6e987b10162d83f
|
[] |
no_license
|
mhdaimi/HybridFrameworkB8
|
https://github.com/mhdaimi/HybridFrameworkB8
|
c2e2630f4b796419520e9d84bebae1be80866868
|
2900d16b41c6be8bf1914331f37cb53ed39d54df
|
refs/heads/master
| 2023-05-11T15:54:03.782000 | 2021-05-23T17:36:13 | 2021-05-23T17:36:13 | 297,033,603 | 0 | 0 | null | false | 2020-09-26T07:49:40 | 2020-09-20T08:30:25 | 2020-09-20T09:20:35 | 2020-09-26T07:49:39 | 13 | 0 | 0 | 0 |
Java
| false | false |
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Excel {
public static HashMap<Integer, ArrayList<String>> getData(String sheetName) throws Exception{
HashMap<Integer, ArrayList<String>> dataMap = new HashMap<Integer, ArrayList<String>>();
File file = new File("E:\\Workspaces\\Batch-8\\HybridFramework\\src\\testData\\Data.xls");
FileInputStream io = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(io);
HSSFSheet sheet = wb.getSheet(sheetName);
int maxRow = sheet.getLastRowNum();
System.out.println(maxRow);
for(int i=0; i<=maxRow; i++) {
ArrayList<String> cellData = new ArrayList<String>();
HSSFRow row = sheet.getRow(i);
int maxCell = row.getLastCellNum();
for(int j=0; j<maxCell; j++) {
HSSFCell cell = row.getCell(j);
if(cell!=null) {
cellData.add(cell.getStringCellValue());
}
}
dataMap.put(i, cellData);
}
return dataMap;
}
public static void updateRow(String sheetName, String inputValue, int rowNumber) throws Exception {
File file = new File("E:\\Workspaces\\Batch-8\\HybridFramework\\src\\testData\\Data.xls");
FileInputStream io = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(io);
HSSFSheet sheet = wb.getSheet(sheetName);
HSSFRow row = sheet.getRow(rowNumber);
int maxCell = row.getLastCellNum();
System.out.println(maxCell + " Max cell number");
System.out.println(sheetName + " " + rowNumber);
HSSFCell cell = row.createCell(maxCell);
cell.setCellValue(inputValue);
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
static void samplemethod() {
}
}
|
UTF-8
|
Java
| 1,993 |
java
|
Excel.java
|
Java
|
[] | null |
[] |
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Excel {
public static HashMap<Integer, ArrayList<String>> getData(String sheetName) throws Exception{
HashMap<Integer, ArrayList<String>> dataMap = new HashMap<Integer, ArrayList<String>>();
File file = new File("E:\\Workspaces\\Batch-8\\HybridFramework\\src\\testData\\Data.xls");
FileInputStream io = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(io);
HSSFSheet sheet = wb.getSheet(sheetName);
int maxRow = sheet.getLastRowNum();
System.out.println(maxRow);
for(int i=0; i<=maxRow; i++) {
ArrayList<String> cellData = new ArrayList<String>();
HSSFRow row = sheet.getRow(i);
int maxCell = row.getLastCellNum();
for(int j=0; j<maxCell; j++) {
HSSFCell cell = row.getCell(j);
if(cell!=null) {
cellData.add(cell.getStringCellValue());
}
}
dataMap.put(i, cellData);
}
return dataMap;
}
public static void updateRow(String sheetName, String inputValue, int rowNumber) throws Exception {
File file = new File("E:\\Workspaces\\Batch-8\\HybridFramework\\src\\testData\\Data.xls");
FileInputStream io = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(io);
HSSFSheet sheet = wb.getSheet(sheetName);
HSSFRow row = sheet.getRow(rowNumber);
int maxCell = row.getLastCellNum();
System.out.println(maxCell + " Max cell number");
System.out.println(sheetName + " " + rowNumber);
HSSFCell cell = row.createCell(maxCell);
cell.setCellValue(inputValue);
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
static void samplemethod() {
}
}
| 1,993 | 0.723532 | 0.721525 | 64 | 30.140625 | 25.594109 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.296875 | false | false |
15
|
d2f886301c3731ff2384531370c186fca3e6bc0f
| 10,024,453,672,803 |
07d9954166ee3cc7891883c3e25d200585cf062f
|
/ted-ui/gwt-ted/src/nu/ted/gwt/client/PageContainerLayout.java
|
9cf5e877ed026e51593746c2fb84ba252c495d34
|
[] |
no_license
|
thisjoshie/ted
|
https://github.com/thisjoshie/ted
|
8780379edd746a8a0d4645ae2a342bd7cb9e9adc
|
584ffed672351619e60fbf5ed9707341fe50a4b1
|
refs/heads/master
| 2021-01-18T08:43:20.190000 | 2010-04-29T00:48:19 | 2010-04-29T00:48:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package nu.ted.gwt.client;
import net.bugsquat.gwtsite.client.PageLoader;
import net.bugsquat.gwtsite.client.layout.DefaultPageContainerLayout;
import nu.ted.gwt.client.i18n.TedMessages;
import nu.ted.gwt.client.image.Images;
import nu.ted.gwt.client.Css.Application;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class PageContainerLayout extends DefaultPageContainerLayout {
public PageContainerLayout()
{
getContent().setStyleName(Application.TED_CONTENT);
}
@Override
protected FlowPanel createHeader() {
FlowPanel header = new FlowPanel();
header.setStyleName(Application.TED_HEADER);
Image headerImage = new Image(Images.INSTANCE.headerLogo());
headerImage.setStyleName(Css.Application.TED_HEADER_LOGO);
headerImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PageLoader.getInstance().loadPage(TedPageId.WATCHED_SERIES);
}
});
header.add(headerImage);
Label title = new Label(TedMessages.INSTANCE.headerTitle());
title.setStyleName(Application.TED_HEADER_TITLE);
header.add(title);
header.add(createMenu());
return header;
}
private FlowPanel createMenu() {
// TODO [MS] Should create a menu widget at some point.
FlowPanel menu = new FlowPanel();
menu.setStyleName(Css.Application.TED_MENU);
menu.add(createMenuItem("Search", TedPageId.SEARCH));
menu.add(createSpacer());
menu.add(createMenuItem("Watching", TedPageId.WATCHED_SERIES));
return menu;
}
private Widget createSpacer() {
Label spacer = new Label("|");
spacer.setStyleName(Css.Application.TED_MENU_SPACER);
return spacer;
}
public Label createMenuItem(final String name, final TedPageId pageToNavigateTo) {
final Label menuItem = new Label(name);
menuItem.setStyleName(Css.Application.TED_MENU_ITEM);
menuItem.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PageLoader.getInstance().loadPage(pageToNavigateTo);
}
});
menuItem.addMouseOverHandler(new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
menuItem.addStyleDependentName(Css.Application.TED_MENU_ITEM_OVER);
}
});
menuItem.addMouseOutHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
menuItem.removeStyleDependentName(Css.Application.TED_MENU_ITEM_OVER);
}
});
return menuItem;
}
}
|
UTF-8
|
Java
| 2,873 |
java
|
PageContainerLayout.java
|
Java
|
[] | null |
[] |
package nu.ted.gwt.client;
import net.bugsquat.gwtsite.client.PageLoader;
import net.bugsquat.gwtsite.client.layout.DefaultPageContainerLayout;
import nu.ted.gwt.client.i18n.TedMessages;
import nu.ted.gwt.client.image.Images;
import nu.ted.gwt.client.Css.Application;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class PageContainerLayout extends DefaultPageContainerLayout {
public PageContainerLayout()
{
getContent().setStyleName(Application.TED_CONTENT);
}
@Override
protected FlowPanel createHeader() {
FlowPanel header = new FlowPanel();
header.setStyleName(Application.TED_HEADER);
Image headerImage = new Image(Images.INSTANCE.headerLogo());
headerImage.setStyleName(Css.Application.TED_HEADER_LOGO);
headerImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PageLoader.getInstance().loadPage(TedPageId.WATCHED_SERIES);
}
});
header.add(headerImage);
Label title = new Label(TedMessages.INSTANCE.headerTitle());
title.setStyleName(Application.TED_HEADER_TITLE);
header.add(title);
header.add(createMenu());
return header;
}
private FlowPanel createMenu() {
// TODO [MS] Should create a menu widget at some point.
FlowPanel menu = new FlowPanel();
menu.setStyleName(Css.Application.TED_MENU);
menu.add(createMenuItem("Search", TedPageId.SEARCH));
menu.add(createSpacer());
menu.add(createMenuItem("Watching", TedPageId.WATCHED_SERIES));
return menu;
}
private Widget createSpacer() {
Label spacer = new Label("|");
spacer.setStyleName(Css.Application.TED_MENU_SPACER);
return spacer;
}
public Label createMenuItem(final String name, final TedPageId pageToNavigateTo) {
final Label menuItem = new Label(name);
menuItem.setStyleName(Css.Application.TED_MENU_ITEM);
menuItem.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
PageLoader.getInstance().loadPage(pageToNavigateTo);
}
});
menuItem.addMouseOverHandler(new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
menuItem.addStyleDependentName(Css.Application.TED_MENU_ITEM_OVER);
}
});
menuItem.addMouseOutHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
menuItem.removeStyleDependentName(Css.Application.TED_MENU_ITEM_OVER);
}
});
return menuItem;
}
}
| 2,873 | 0.76401 | 0.763314 | 96 | 28.927084 | 24.335009 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.864583 | false | false |
15
|
8cc3b6bb4163be182b017066bb1ddf7c90d4f22b
| 18,227,841,251,890 |
e5e99a7631ad637c3822aca2ffa35a7a34b59b00
|
/src/interfaz/Llamada.java
|
ae0f17f8e8e3b2bf45fa528c74c3098dcb9678df
|
[] |
no_license
|
rudypalacios/Arboles
|
https://github.com/rudypalacios/Arboles
|
c9a485d2ee45aea289d6ed4e0d7cf972057a5d3b
|
79bd092ade1a2e9252a93bd7470e2540b63035d9
|
refs/heads/master
| 2018-01-10T22:30:17.230000 | 2016-04-02T00:16:36 | 2016-04-02T00:16:36 | 54,439,056 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package interfaz;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import metodos.MAlumnos;
public class Llamada extends JFrame {
private JSeparator jSeparator1 = new JSeparator();
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JSeparator jSeparator2 = new JSeparator();
private JSeparator jSeparator3 = new JSeparator();
private JTable tablaAlumnos = new JTable();
private JTable tablaEspera = new JTable();
private JScrollPane jScrollPaneAlumnos;
private JScrollPane jScrollPaneEspera;
private JButton jButton1 = new JButton();
public static JPanel jPanel1 = new JPanel();
public Llamada() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
DefaultTableModel aModel = new DefaultTableModel() {
//Tabla read-only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableModel bModel = new DefaultTableModel() {
//Tabla read-only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1100, 800));
this.setResizable(false);
ToolTipManager.sharedInstance().setInitialDelay(0);
jSeparator1.setBounds(new Rectangle(0, 30, 1100, 5));
jLabel1.setText("EN L\u00cdNEA");
jLabel1.setBounds(new Rectangle(10, 10, 80, 15));
jLabel1.setFont(new Font("Tahoma", 1, 14));
jLabel2.setText("ESTUDIANTES");
jLabel2.setBounds(new Rectangle(920, 355, 110, 15));
jLabel2.setFont(new Font("Tahoma", 1, 14));
jLabel3.setText("LISTA DE ESPERA");
jLabel3.setBounds(new Rectangle(910, 35, 130, 15));
jLabel3.setFont(new Font("Tahoma", 1, 14));
jSeparator2.setBounds(new Rectangle(850, 45, 15, 740));
jSeparator2.setOrientation(SwingConstants.VERTICAL);
jSeparator3.setBounds(new Rectangle(863, 340, 225, 10));
String[] columnNames = {"Nombre", "Carnet", "ID" };
//Configuración tabla
tablaAlumnos.setFillsViewportHeight(true);
//Agregar títulos de columnas
aModel.setColumnIdentifiers(columnNames);
//Agregar filas
List listaAlumnos = MAlumnos.getAlumnos();
int tLista = listaAlumnos.size();
if (tLista > 0) {
for (int i = 0; i < tLista; i++) {
Object[] objects = new Object[3];
MAlumnos a = (MAlumnos)listaAlumnos.get(i);
objects[0] = a.nombres+" "+a.apellidos;
objects[1] = a.carnet;
objects[2] = a.id;
aModel.addRow(objects);
}
}else{
tablaAlumnos.setModel(aModel);
}
//Añadir modelo personalizado a tabla
tablaAlumnos.setModel(aModel);
//Esconder IDs
TableColumn idAlumnos= tablaAlumnos.getColumn("ID");
idAlumnos.setMaxWidth(0);
idAlumnos.setMinWidth(0);
idAlumnos.setPreferredWidth(0);
//Inicialización tabla de espera
//Configuración tabla
tablaEspera.setFillsViewportHeight(true);
//Agregar títulos de columnas
bModel.setColumnIdentifiers(columnNames);
//Agregar modelo
tablaEspera.setModel(bModel);
//Esconder IDs
TableColumn idEspera= tablaEspera.getColumn("ID");
idEspera.setMaxWidth(0);
idEspera.setMinWidth(0);
idEspera.setPreferredWidth(0);
//Añadir modelo personalizado a tabla
jPanel1.setBounds(new Rectangle(5, 35, 840, 715));
jButton1.setText("Regresar...");
jButton1.setBounds(new Rectangle(975, 5, 115, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jScrollPaneAlumnos = new JScrollPane(tablaAlumnos);
jScrollPaneAlumnos.setBounds(new Rectangle(868, 385, 215, 360));
jScrollPaneEspera = new JScrollPane(tablaEspera);
jScrollPaneEspera.setBounds(new Rectangle(868, 60, 215, 265));
//
MAlumnos alumnos = new MAlumnos();
alumnos.moverRegistro(tablaAlumnos,aModel,bModel);
alumnos.moverRegistro(tablaEspera,bModel,aModel);
this.getContentPane().add(jPanel1, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPaneEspera, null);
this.getContentPane().add(jScrollPaneAlumnos, null);
this.getContentPane().add(jSeparator3, null);
this.getContentPane().add(jSeparator2, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(jSeparator1, null);
setLocationRelativeTo(null);
}
private void jButton1_actionPerformed(ActionEvent e) {
Inicio in = new Inicio();
in.setVisible(true);
this.dispose();
}
}
|
ISO-8859-1
|
Java
| 6,203 |
java
|
Llamada.java
|
Java
|
[
{
"context": "));\n \n String[] columnNames = {\"Nombre\", \"Carnet\", \"ID\" };\n //Configuración tabla\n ",
"end": 2976,
"score": 0.9994945526123047,
"start": 2970,
"tag": "NAME",
"value": "Carnet"
}
] | null |
[] |
package interfaz;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import metodos.MAlumnos;
public class Llamada extends JFrame {
private JSeparator jSeparator1 = new JSeparator();
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
private JLabel jLabel3 = new JLabel();
private JSeparator jSeparator2 = new JSeparator();
private JSeparator jSeparator3 = new JSeparator();
private JTable tablaAlumnos = new JTable();
private JTable tablaEspera = new JTable();
private JScrollPane jScrollPaneAlumnos;
private JScrollPane jScrollPaneEspera;
private JButton jButton1 = new JButton();
public static JPanel jPanel1 = new JPanel();
public Llamada() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
DefaultTableModel aModel = new DefaultTableModel() {
//Tabla read-only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableModel bModel = new DefaultTableModel() {
//Tabla read-only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
private void jbInit() throws Exception {
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1100, 800));
this.setResizable(false);
ToolTipManager.sharedInstance().setInitialDelay(0);
jSeparator1.setBounds(new Rectangle(0, 30, 1100, 5));
jLabel1.setText("EN L\u00cdNEA");
jLabel1.setBounds(new Rectangle(10, 10, 80, 15));
jLabel1.setFont(new Font("Tahoma", 1, 14));
jLabel2.setText("ESTUDIANTES");
jLabel2.setBounds(new Rectangle(920, 355, 110, 15));
jLabel2.setFont(new Font("Tahoma", 1, 14));
jLabel3.setText("LISTA DE ESPERA");
jLabel3.setBounds(new Rectangle(910, 35, 130, 15));
jLabel3.setFont(new Font("Tahoma", 1, 14));
jSeparator2.setBounds(new Rectangle(850, 45, 15, 740));
jSeparator2.setOrientation(SwingConstants.VERTICAL);
jSeparator3.setBounds(new Rectangle(863, 340, 225, 10));
String[] columnNames = {"Nombre", "Carnet", "ID" };
//Configuración tabla
tablaAlumnos.setFillsViewportHeight(true);
//Agregar títulos de columnas
aModel.setColumnIdentifiers(columnNames);
//Agregar filas
List listaAlumnos = MAlumnos.getAlumnos();
int tLista = listaAlumnos.size();
if (tLista > 0) {
for (int i = 0; i < tLista; i++) {
Object[] objects = new Object[3];
MAlumnos a = (MAlumnos)listaAlumnos.get(i);
objects[0] = a.nombres+" "+a.apellidos;
objects[1] = a.carnet;
objects[2] = a.id;
aModel.addRow(objects);
}
}else{
tablaAlumnos.setModel(aModel);
}
//Añadir modelo personalizado a tabla
tablaAlumnos.setModel(aModel);
//Esconder IDs
TableColumn idAlumnos= tablaAlumnos.getColumn("ID");
idAlumnos.setMaxWidth(0);
idAlumnos.setMinWidth(0);
idAlumnos.setPreferredWidth(0);
//Inicialización tabla de espera
//Configuración tabla
tablaEspera.setFillsViewportHeight(true);
//Agregar títulos de columnas
bModel.setColumnIdentifiers(columnNames);
//Agregar modelo
tablaEspera.setModel(bModel);
//Esconder IDs
TableColumn idEspera= tablaEspera.getColumn("ID");
idEspera.setMaxWidth(0);
idEspera.setMinWidth(0);
idEspera.setPreferredWidth(0);
//Añadir modelo personalizado a tabla
jPanel1.setBounds(new Rectangle(5, 35, 840, 715));
jButton1.setText("Regresar...");
jButton1.setBounds(new Rectangle(975, 5, 115, 20));
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1_actionPerformed(e);
}
});
jScrollPaneAlumnos = new JScrollPane(tablaAlumnos);
jScrollPaneAlumnos.setBounds(new Rectangle(868, 385, 215, 360));
jScrollPaneEspera = new JScrollPane(tablaEspera);
jScrollPaneEspera.setBounds(new Rectangle(868, 60, 215, 265));
//
MAlumnos alumnos = new MAlumnos();
alumnos.moverRegistro(tablaAlumnos,aModel,bModel);
alumnos.moverRegistro(tablaEspera,bModel,aModel);
this.getContentPane().add(jPanel1, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPaneEspera, null);
this.getContentPane().add(jScrollPaneAlumnos, null);
this.getContentPane().add(jSeparator3, null);
this.getContentPane().add(jSeparator2, null);
this.getContentPane().add(jLabel3, null);
this.getContentPane().add(jLabel2, null);
this.getContentPane().add(jLabel1, null);
this.getContentPane().add(jSeparator1, null);
setLocationRelativeTo(null);
}
private void jButton1_actionPerformed(ActionEvent e) {
Inicio in = new Inicio();
in.setVisible(true);
this.dispose();
}
}
| 6,203 | 0.627179 | 0.600387 | 178 | 33.80899 | 19.753468 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.949438 | false | false |
15
|
b11f6942ed0b1d85466a8c0324266020e1c8205c
| 17,033,840,352,335 |
0bd572946c399422e97adf2a31ae9bf52261e5d1
|
/Mediator/WeChatMediator.java
|
e2dbb834aa2cf1299e097137063a03b573fba80f
|
[] |
no_license
|
cai584770/DesignPattern
|
https://github.com/cai584770/DesignPattern
|
a415bf284dc2cb438cbd99d868ded73a5b0ea625
|
4ef9b1eccecf925a5ac1e9f4e1181dc2950e0c1b
|
refs/heads/master
| 2022-06-24T13:45:17.490000 | 2020-05-06T08:52:09 | 2020-05-06T08:52:09 | 255,051,319 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Mediator;
import java.util.ArrayList;
import java.util.List;
public class WeChatMediator implements Mediator {
private List<AbstractColleague> colleagues = new ArrayList<>();
@Override
public void register(AbstractColleague colleague) {
if (!colleagues.contains(colleague)) {
colleagues.add(colleague);
colleague.setMediator(this);
}
}
@Override
public void relay(AbstractColleague colleague) {
AbstractColleague.Message message = colleague.getMessage();
colleagues.forEach(aColleague -> {
if (aColleague.getUsername().equals(message.getReceiver())) {
aColleague.receive(message);
}
});
}
}
|
UTF-8
|
Java
| 737 |
java
|
WeChatMediator.java
|
Java
|
[] | null |
[] |
package Mediator;
import java.util.ArrayList;
import java.util.List;
public class WeChatMediator implements Mediator {
private List<AbstractColleague> colleagues = new ArrayList<>();
@Override
public void register(AbstractColleague colleague) {
if (!colleagues.contains(colleague)) {
colleagues.add(colleague);
colleague.setMediator(this);
}
}
@Override
public void relay(AbstractColleague colleague) {
AbstractColleague.Message message = colleague.getMessage();
colleagues.forEach(aColleague -> {
if (aColleague.getUsername().equals(message.getReceiver())) {
aColleague.receive(message);
}
});
}
}
| 737 | 0.641791 | 0.641791 | 28 | 25.321428 | 23.608494 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false |
15
|
97ae8dbc9fcfec13aa0befc220bf9c324d4af5b4
| 10,342,281,314,260 |
2884c4a591b73868dffe3ee448560ec1d35cb102
|
/app/src/main/java/com/barchart/mpchartdemo/view/BarGroup.java
|
c4ecdc3b8550937b0b8ad603f91924093df98e84
|
[] |
no_license
|
GuangNian10000/MPChart
|
https://github.com/GuangNian10000/MPChart
|
6cc6acd30ea4971002b8ea9f9b8c59b26d0e2be0
|
095ac447e2d34a86eccb8f1696d6d9ede0cff3b7
|
refs/heads/master
| 2023-01-09T15:05:49.396000 | 2020-11-09T03:17:35 | 2020-11-09T03:17:35 | 311,211,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.barchart.mpchartdemo.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.barchart.mpchartdemo.R;
import com.barchart.mpchartdemo.entity.BarEntity;
import com.barchart.mpchartdemo.util.DensityUtil;
import java.text.DecimalFormat;
import java.util.List;
/**
* Created by chenjie05 on 2016/12/14.
*/
public class BarGroup extends LinearLayout {
private List<BarEntity> datas;
public BarGroup(Context context) {
super(context);
init();
}
public BarGroup(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BarGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOrientation(HORIZONTAL);
}
public void setDatas(List<BarEntity> datas) {
if (datas != null) {
this.datas = datas;
// for (int i = 0; i < datas.size(); i++) {
// View view = LayoutInflater.from(getContext()).inflate(R.layout.bar_item, null);
// ((BarView) view.findViewById(R.id.barView)).setData(datas.get(i));
// ((TextView)view.findViewById(R.id.title)).setText(getFeedString(datas.get(i).getTitle()));
// DecimalFormat mFormat=new DecimalFormat("##"); ;
// ((TextView)view.findViewById(R.id.percent)).setText(mFormat.format(datas.get(i).getScale()*100)+"%");
// addView(view);
// }
}
}
public void setHeight(float maxValue,int height) {
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
/*通过柱状图的最大值和相对比例计算出每条柱状图的高度*/
float barHeight = datas.get(i).getAllcount()/maxValue*height;
View view = LayoutInflater.from(getContext()).inflate(R.layout.bar_item, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(getContext(),30),height);
// view.setLayoutParams(lp);
((BarView) view.findViewById(R.id.barView)).setData(datas.get(i));
(view.findViewById(R.id.barView)).setLayoutParams(lp);
((TextView)view.findViewById(R.id.title)).setText(getFeedString(datas.get(i).getTitle()));
DecimalFormat mFormat=new DecimalFormat("##.#");
((TextView)view.findViewById(R.id.percent)).setText(mFormat.format(datas.get(i).getAllcount()));
addView(view);
}
}
}
/*字符串換行*/
private String getFeedString(String text){
StringBuilder sb = new StringBuilder(text);
sb.insert(2,"\n");
return sb.toString();
}
}
|
UTF-8
|
Java
| 2,945 |
java
|
BarGroup.java
|
Java
|
[
{
"context": "Format;\nimport java.util.List;\n\n\n/**\n * Created by chenjie05 on 2016/12/14.\n */\n\npublic class BarGroup extends",
"end": 457,
"score": 0.999523401260376,
"start": 448,
"tag": "USERNAME",
"value": "chenjie05"
}
] | null |
[] |
package com.barchart.mpchartdemo.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.barchart.mpchartdemo.R;
import com.barchart.mpchartdemo.entity.BarEntity;
import com.barchart.mpchartdemo.util.DensityUtil;
import java.text.DecimalFormat;
import java.util.List;
/**
* Created by chenjie05 on 2016/12/14.
*/
public class BarGroup extends LinearLayout {
private List<BarEntity> datas;
public BarGroup(Context context) {
super(context);
init();
}
public BarGroup(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BarGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOrientation(HORIZONTAL);
}
public void setDatas(List<BarEntity> datas) {
if (datas != null) {
this.datas = datas;
// for (int i = 0; i < datas.size(); i++) {
// View view = LayoutInflater.from(getContext()).inflate(R.layout.bar_item, null);
// ((BarView) view.findViewById(R.id.barView)).setData(datas.get(i));
// ((TextView)view.findViewById(R.id.title)).setText(getFeedString(datas.get(i).getTitle()));
// DecimalFormat mFormat=new DecimalFormat("##"); ;
// ((TextView)view.findViewById(R.id.percent)).setText(mFormat.format(datas.get(i).getScale()*100)+"%");
// addView(view);
// }
}
}
public void setHeight(float maxValue,int height) {
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
/*通过柱状图的最大值和相对比例计算出每条柱状图的高度*/
float barHeight = datas.get(i).getAllcount()/maxValue*height;
View view = LayoutInflater.from(getContext()).inflate(R.layout.bar_item, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(getContext(),30),height);
// view.setLayoutParams(lp);
((BarView) view.findViewById(R.id.barView)).setData(datas.get(i));
(view.findViewById(R.id.barView)).setLayoutParams(lp);
((TextView)view.findViewById(R.id.title)).setText(getFeedString(datas.get(i).getTitle()));
DecimalFormat mFormat=new DecimalFormat("##.#");
((TextView)view.findViewById(R.id.percent)).setText(mFormat.format(datas.get(i).getAllcount()));
addView(view);
}
}
}
/*字符串換行*/
private String getFeedString(String text){
StringBuilder sb = new StringBuilder(text);
sb.insert(2,"\n");
return sb.toString();
}
}
| 2,945 | 0.613518 | 0.606932 | 82 | 34.182926 | 31.677925 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.695122 | false | false |
15
|
d85433cb4bb6b16557a5a47b7c5ec6917e5c99ca
| 24,790,551,279,600 |
6bb066ba66395f168e6cf9aae5b6a98dbace9295
|
/Demos/servletDemos/unitDemos/diyAnnotation/TestAnnoRun.java
|
9f126c2eb32d61ebd472118a912734104a1420ba
|
[] |
no_license
|
beyondlov1/JavaAttentions
|
https://github.com/beyondlov1/JavaAttentions
|
cfdb71ba80d7d292c665923c31cd431f2a631512
|
c4199c57cfdf01e8a9274f01e855bc99168626b9
|
refs/heads/master
| 2023-09-01T14:16:18.848000 | 2023-08-29T05:39:59 | 2023-08-29T05:39:59 | 133,447,559 | 2 | 0 | null | false | 2023-02-22T07:10:31 | 2018-05-15T02:25:03 | 2023-01-15T02:56:54 | 2023-02-22T07:10:29 | 201,465 | 3 | 0 | 103 |
Batchfile
| false | false |
package com.beyond.test;
public class TestAnnoRun {
public static void main(String[] args) {
TestAnnoClass test = new TestAnnoClass();
test.run();
}
}
|
UTF-8
|
Java
| 166 |
java
|
TestAnnoRun.java
|
Java
|
[] | null |
[] |
package com.beyond.test;
public class TestAnnoRun {
public static void main(String[] args) {
TestAnnoClass test = new TestAnnoClass();
test.run();
}
}
| 166 | 0.674699 | 0.674699 | 8 | 18.75 | 16.368797 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false |
15
|
2f8c64c7d034d770a1b7756290aece40351d81e6
| 5,480,378,288,914 |
0e09ccd861513af9640534a490e4deadb3834e8d
|
/app/src/main/java/com/example/pwpb_calculator/MainActivity.java
|
7345161a17984bb51580753a6389d93c5e5ae725
|
[] |
no_license
|
syarif-hidayatulloh/Android-Java-Calculator
|
https://github.com/syarif-hidayatulloh/Android-Java-Calculator
|
175a3c01664e7d6116d2cc19ec468047fa689ec5
|
d617a8647bf5eed973a471df4dc8750842a90fed
|
refs/heads/master
| 2022-03-17T03:09:19.787000 | 2019-08-29T02:54:43 | 2019-08-29T02:54:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.pwpb_calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnTambah, btnKurang, btnBagi, btnKali, btnTitik, btnHasil, btnHapus;
TextView labelHasil;
float mValue1, mValue2;
int tambah, kurang, kali, bagi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponent();
initEvent();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn0:
labelHasil.setText(labelHasil.getText().toString().trim() + "0");
break;
case R.id.btn1:
labelHasil.setText(labelHasil.getText().toString().trim() + "1");
break;
case R.id.btn2:
labelHasil.setText(labelHasil.getText().toString().trim() + "2");
break;
case R.id.btn3:
labelHasil.setText(labelHasil.getText().toString().trim() + "3");
break;
case R.id.btn4:
labelHasil.setText(labelHasil.getText().toString().trim() + "4");
break;
case R.id.btn5:
labelHasil.setText(labelHasil.getText().toString().trim() + "5");
break;
case R.id.btn6:
labelHasil.setText(labelHasil.getText().toString().trim() + "6");
break;
case R.id.btn7:
labelHasil.setText(labelHasil.getText().toString().trim() + "7");
break;
case R.id.btn8:
labelHasil.setText(labelHasil.getText().toString().trim() + "8");
break;
case R.id.btn9:
labelHasil.setText(labelHasil.getText().toString().trim() + "9");
break;
case R.id.btnTambah:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
tambah = 1;
labelHasil.setText(null);
}
break;
case R.id.btnKurang:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
kurang = 1;
labelHasil.setText(null);
}
break;
case R.id.btnKali:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
kali = 1;
labelHasil.setText(null);
}
break;
case R.id.btnBagi:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
bagi = 1;
labelHasil.setText(null);
}
break;
case R.id.btnHasil:
System.out.println("Clicked");
mValue2 = Float.parseFloat(labelHasil.getText() + "");
if (tambah == 1) {
labelHasil.setText(mValue1 + mValue2 + "");
tambah = 0;
}else if (kurang == 1) {
labelHasil.setText(mValue1 - mValue2 + "");
kurang = 0;
}else if (kali == 1) {
labelHasil.setText(mValue1 * mValue2 + "");
kali = 0;
}else if (bagi == 1) {
labelHasil.setText(mValue1 / mValue2 + "");
bagi = 0;
}
break;
case R.id.btnHapus:
labelHasil.setText(null);
break;
}
}
private void initComponent() {
labelHasil = findViewById(R.id.labelHasil);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btnTambah = findViewById(R.id.btnTambah);
btnKurang = findViewById(R.id.btnKurang);
btnKali = findViewById(R.id.btnKali);
btnBagi = findViewById(R.id.btnBagi);
btnHasil = findViewById(R.id.btnHasil);
btnTitik = findViewById(R.id.btnTitik);
btnHapus = findViewById(R.id.btnHapus);
}
private void initEvent() {
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnTitik.setOnClickListener(this);
btnTambah.setOnClickListener(this);
btnKurang.setOnClickListener(this);
btnKali.setOnClickListener(this);
btnBagi.setOnClickListener(this);
btnHasil.setOnClickListener(this);
btnHapus.setOnClickListener(this);
}
}
|
UTF-8
|
Java
| 5,902 |
java
|
MainActivity.java
|
Java
|
[] | null |
[] |
package com.example.pwpb_calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnTambah, btnKurang, btnBagi, btnKali, btnTitik, btnHasil, btnHapus;
TextView labelHasil;
float mValue1, mValue2;
int tambah, kurang, kali, bagi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponent();
initEvent();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn0:
labelHasil.setText(labelHasil.getText().toString().trim() + "0");
break;
case R.id.btn1:
labelHasil.setText(labelHasil.getText().toString().trim() + "1");
break;
case R.id.btn2:
labelHasil.setText(labelHasil.getText().toString().trim() + "2");
break;
case R.id.btn3:
labelHasil.setText(labelHasil.getText().toString().trim() + "3");
break;
case R.id.btn4:
labelHasil.setText(labelHasil.getText().toString().trim() + "4");
break;
case R.id.btn5:
labelHasil.setText(labelHasil.getText().toString().trim() + "5");
break;
case R.id.btn6:
labelHasil.setText(labelHasil.getText().toString().trim() + "6");
break;
case R.id.btn7:
labelHasil.setText(labelHasil.getText().toString().trim() + "7");
break;
case R.id.btn8:
labelHasil.setText(labelHasil.getText().toString().trim() + "8");
break;
case R.id.btn9:
labelHasil.setText(labelHasil.getText().toString().trim() + "9");
break;
case R.id.btnTambah:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
tambah = 1;
labelHasil.setText(null);
}
break;
case R.id.btnKurang:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
kurang = 1;
labelHasil.setText(null);
}
break;
case R.id.btnKali:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
kali = 1;
labelHasil.setText(null);
}
break;
case R.id.btnBagi:
if (labelHasil == null) {
labelHasil.setText(null);
} else {
mValue1 = Float.parseFloat(labelHasil.getText() + "");
bagi = 1;
labelHasil.setText(null);
}
break;
case R.id.btnHasil:
System.out.println("Clicked");
mValue2 = Float.parseFloat(labelHasil.getText() + "");
if (tambah == 1) {
labelHasil.setText(mValue1 + mValue2 + "");
tambah = 0;
}else if (kurang == 1) {
labelHasil.setText(mValue1 - mValue2 + "");
kurang = 0;
}else if (kali == 1) {
labelHasil.setText(mValue1 * mValue2 + "");
kali = 0;
}else if (bagi == 1) {
labelHasil.setText(mValue1 / mValue2 + "");
bagi = 0;
}
break;
case R.id.btnHapus:
labelHasil.setText(null);
break;
}
}
private void initComponent() {
labelHasil = findViewById(R.id.labelHasil);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btnTambah = findViewById(R.id.btnTambah);
btnKurang = findViewById(R.id.btnKurang);
btnKali = findViewById(R.id.btnKali);
btnBagi = findViewById(R.id.btnBagi);
btnHasil = findViewById(R.id.btnHasil);
btnTitik = findViewById(R.id.btnTitik);
btnHapus = findViewById(R.id.btnHapus);
}
private void initEvent() {
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnTitik.setOnClickListener(this);
btnTambah.setOnClickListener(this);
btnKurang.setOnClickListener(this);
btnKali.setOnClickListener(this);
btnBagi.setOnClickListener(this);
btnHasil.setOnClickListener(this);
btnHapus.setOnClickListener(this);
}
}
| 5,902 | 0.515419 | 0.500678 | 158 | 36.354431 | 21.448812 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.772152 | false | false |
15
|
3d14b2ae9ac51c8e845c0fa40ff9ed6e187f6672
| 23,794,118,888,377 |
47ed695d8c00485468814cc54e3eb82928882122
|
/leetcode/src/lintcode/dp/CopyBooks.java
|
2b3ace3be90e9a52470ff4b42faad35dc0219e2c
|
[] |
no_license
|
yulongzhou1989/leetcode
|
https://github.com/yulongzhou1989/leetcode
|
b1a51b35487a9f49bc68e57ba10e237fc8d0d4ac
|
faef4a576976d123fe1e7eb68e9395c0062cd147
|
refs/heads/master
| 2020-04-05T11:43:02.950000 | 2019-01-24T20:15:45 | 2019-01-24T20:15:45 | 81,111,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package lintcode.dp;
public class CopyBooks {
public int copyBooks(int[] pages, int k) {
if(k==0 || pages.length==0) return 0;
int n = pages.length;
//dp[i][j] = min(k->0...j max(dp[i][j-k], sum(k->j))) i -> 前i 个人, j->前j本书
int [][] dp = new int [k+1][n+1];
for(int i=1;i<=n;i++){
dp[0][i] = Integer.MAX_VALUE;
}
for(int i=1;i<=k;i++){
for(int j=0;j<=n;j++){
int sum = 0;
dp[i][j] = Integer.MAX_VALUE;
for(int m=j;m>=0;m--){
dp[i][j] = Math.min(Math.max(dp[i-1][m], sum), dp[i][j]);
if(m>0) sum += pages[m-1];
}
}
}
//System.out.println(Arrays.deepToString(dp));
return dp[k][n];
}
}
|
UTF-8
|
Java
| 682 |
java
|
CopyBooks.java
|
Java
|
[] | null |
[] |
package lintcode.dp;
public class CopyBooks {
public int copyBooks(int[] pages, int k) {
if(k==0 || pages.length==0) return 0;
int n = pages.length;
//dp[i][j] = min(k->0...j max(dp[i][j-k], sum(k->j))) i -> 前i 个人, j->前j本书
int [][] dp = new int [k+1][n+1];
for(int i=1;i<=n;i++){
dp[0][i] = Integer.MAX_VALUE;
}
for(int i=1;i<=k;i++){
for(int j=0;j<=n;j++){
int sum = 0;
dp[i][j] = Integer.MAX_VALUE;
for(int m=j;m>=0;m--){
dp[i][j] = Math.min(Math.max(dp[i-1][m], sum), dp[i][j]);
if(m>0) sum += pages[m-1];
}
}
}
//System.out.println(Arrays.deepToString(dp));
return dp[k][n];
}
}
| 682 | 0.497006 | 0.474551 | 29 | 22.034483 | 19.388021 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.931035 | false | false |
15
|
033fd3693d10b082d0e43805d48b1d4b9c485501
| 31,920,197,006,658 |
55d2f66365f8f90c95bfc4126578f1bffc080c0c
|
/src/br/com/botapatrimonio/Localizacao.java
|
2b81221e17289608ec57d463ecf507d86a72ff13
|
[] |
no_license
|
fernandalaiss/BotaPatrimonio
|
https://github.com/fernandalaiss/BotaPatrimonio
|
c1b45727f64bd91af08be565b126e492dafb0cdc
|
2015a0afad4573aaa0bb13a1c1e40fdbfd6c206f
|
refs/heads/master
| 2022-03-05T03:01:40.376000 | 2019-11-19T00:58:32 | 2019-11-19T00:58:32 | 219,784,050 | 0 | 0 | null | false | 2019-11-19T00:58:33 | 2019-11-05T15:53:11 | 2019-11-17T03:48:33 | 2019-11-19T00:58:33 | 739 | 0 | 0 | 0 |
Java
| false | false |
package br.com.botapatrimonio;
import java.util.HashSet;
import java.util.Set;
public class Localizacao {
private String codigo;
private String nome;
private String descricao;
private Set<Bem> bensContidos;
public Localizacao(){
bensContidos = new HashSet<Bem>();
}
public void addBem(Bem bem){
bensContidos.add(bem);
}
public void removeBem(Bem bem) {
bensContidos.remove(bem);
}
public String getBens(){
String list = "Código - Nome";
return list.concat(fgetBens(""));
}
String fgetBens(String prefix) {
String list = "";
for (Bem b:bensContidos) {
list = list.concat("\n"+prefix+b.getCodigo()+" - "+b.getNome());
}
return list;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
|
UTF-8
|
Java
| 1,216 |
java
|
Localizacao.java
|
Java
|
[] | null |
[] |
package br.com.botapatrimonio;
import java.util.HashSet;
import java.util.Set;
public class Localizacao {
private String codigo;
private String nome;
private String descricao;
private Set<Bem> bensContidos;
public Localizacao(){
bensContidos = new HashSet<Bem>();
}
public void addBem(Bem bem){
bensContidos.add(bem);
}
public void removeBem(Bem bem) {
bensContidos.remove(bem);
}
public String getBens(){
String list = "Código - Nome";
return list.concat(fgetBens(""));
}
String fgetBens(String prefix) {
String list = "";
for (Bem b:bensContidos) {
list = list.concat("\n"+prefix+b.getCodigo()+" - "+b.getNome());
}
return list;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
| 1,216 | 0.584362 | 0.584362 | 61 | 18.918034 | 16.667723 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.344262 | false | false |
15
|
204f827b7164e0afb5b95147f070ace617b5d05b
| 33,131,377,780,454 |
755cdb4fc5cc293af43e25b4853358e734b8255b
|
/feature/src/main/java/database/metadata/DatabaseMetaDataTest.java
|
fe74178ee980fbf17ca77e44fddaab178b436f65
|
[] |
no_license
|
weihuanhuan/MiscellaneousTest
|
https://github.com/weihuanhuan/MiscellaneousTest
|
f5e81e399db08a36132e43864929080c46804be6
|
86cb2b74302ebf2c7d5a094223cf30e218024837
|
refs/heads/test
| 2023-08-31T01:54:31.111000 | 2023-08-24T04:14:37 | 2023-08-24T04:14:37 | 124,471,368 | 1 | 2 | null | false | 2022-03-17T11:58:28 | 2018-03-09T01:43:46 | 2021-12-30T05:28:24 | 2022-01-26T19:01:27 | 7,449 | 1 | 2 | 0 |
Java
| false | false |
package database.metadata;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaDataTest {
static String url = "url";
static String username = "username";
static String tableName = "tableName";
public static void main(String[] args) throws SQLException {
//使用 DatabaseMetaData 判断数据库是否存在某个表
Connection connection = DriverManager.getConnection(url);
DatabaseMetaData metaData = connection.getMetaData();
String userName = metaData.getUserName();
metaData.getTables(null, userName, tableName, new String[]{"Table"});
}
}
|
UTF-8
|
Java
| 708 |
java
|
DatabaseMetaDataTest.java
|
Java
|
[
{
"context": "String url = \"url\";\n static String username = \"username\";\n static String tableName = \"tableName\";\n\n ",
"end": 258,
"score": 0.9995574355125427,
"start": 250,
"tag": "USERNAME",
"value": "username"
}
] | null |
[] |
package database.metadata;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaDataTest {
static String url = "url";
static String username = "username";
static String tableName = "tableName";
public static void main(String[] args) throws SQLException {
//使用 DatabaseMetaData 判断数据库是否存在某个表
Connection connection = DriverManager.getConnection(url);
DatabaseMetaData metaData = connection.getMetaData();
String userName = metaData.getUserName();
metaData.getTables(null, userName, tableName, new String[]{"Table"});
}
}
| 708 | 0.720588 | 0.720588 | 24 | 27.333334 | 24.113735 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false |
15
|
74805e1fd0d8c984178389833713146824c565bd
| 3,375,844,339,589 |
edd17a7434cb7f6ad5f557c6b81cbcd5d70c32a2
|
/src/ncsu/vi/treefinder/xml/TreeItemPullParser.java
|
90337d409fc29812a2c610e472cc043c0e12dff6
|
[] |
no_license
|
NCSUMobiles/Spring16-treefinder
|
https://github.com/NCSUMobiles/Spring16-treefinder
|
73ce7b87280b1c2e6ab39c08f13243b61a7844b3
|
7c9390a7d125dee03b3aaa27350d54ba0a15a77b
|
refs/heads/master
| 2021-01-17T15:40:13.596000 | 2016-06-08T16:35:36 | 2016-06-08T16:35:36 | 57,067,305 | 0 | 1 | null | false | 2016-05-03T17:02:54 | 2016-04-25T18:49:29 | 2016-05-02T16:27:29 | 2016-05-03T17:02:54 | 3,855 | 0 | 1 | 0 |
Java
| null | null |
package ncsu.vi.treefinder.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
//import android.R;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.util.Log;
import ncsu.vi.treefinder.model.TreeItem;
public class TreeItemPullParser {
private static final String LOGTAG = "TREEFINDER";
private static final String TREEITEM_ID= "treeItemId";
private static final String TREEITEM_IMAGEURL= "imageUrl" ;
private static final String TREEITEM_ITEMTYPE= "itemType";
private static final String TREEITEM_DESCRIPTION= "treeDesc";
private static final String TREEITEM_QUESTION= "treeQues";
private TreeItem currentTreeItem = null ;
private String currentTag = null ;
List<TreeItem> treeItems = new ArrayList<TreeItem>();
public List<TreeItem> parseXML(Context context){
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
int rid = context.getResources().getIdentifier("ncsu.vi.treefinder:raw/treeitems", null, null);
//Log.d(LOGTAG, Integer.toString(rid));
InputStream stream = context.getResources().openRawResource(rid);
xpp.setInput(stream, null);
int eventType = xpp.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG){
handleStartTag(xpp.getName());
}else if (eventType == XmlPullParser.END_TAG){
currentTag = null;
}else if(eventType == XmlPullParser.TEXT){
handleText(xpp.getText());
}
eventType = xpp.next();
}
}
catch(NotFoundException e){
Log.d(LOGTAG, e.getMessage());
}
catch(XmlPullParserException e){
Log.d(LOGTAG, e.getMessage());
}
catch(IOException e){
Log.d(LOGTAG, e.getMessage());
}
return treeItems;
}
private void handleText(String text){
String xmlText = text;
if(currentTreeItem!= null && currentTag!= null){
if(currentTag.equals(TREEITEM_ID)){
Integer id = Integer.parseInt(xmlText);
currentTreeItem.setId(id);
}
else if (currentTag.equals(TREEITEM_IMAGEURL)){
currentTreeItem.setImageUrl(xmlText);
}
else if(currentTag.equals(TREEITEM_ITEMTYPE)) {
currentTreeItem.setItemType(xmlText);
}
else if(currentTag.equals(TREEITEM_DESCRIPTION)) {
currentTreeItem.setDescription(xmlText);
}
else if(currentTag.equals(TREEITEM_QUESTION)) {
currentTreeItem.setQuestion(xmlText);
}
}
}
private void handleStartTag(String name){
if(name.equals("treeItem")){
currentTreeItem = new TreeItem();
treeItems.add(currentTreeItem);
}
else{
currentTag = name;
}
}
}
|
UTF-8
|
Java
| 2,894 |
java
|
TreeItemPullParser.java
|
Java
|
[] | null |
[] |
package ncsu.vi.treefinder.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
//import android.R;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.util.Log;
import ncsu.vi.treefinder.model.TreeItem;
public class TreeItemPullParser {
private static final String LOGTAG = "TREEFINDER";
private static final String TREEITEM_ID= "treeItemId";
private static final String TREEITEM_IMAGEURL= "imageUrl" ;
private static final String TREEITEM_ITEMTYPE= "itemType";
private static final String TREEITEM_DESCRIPTION= "treeDesc";
private static final String TREEITEM_QUESTION= "treeQues";
private TreeItem currentTreeItem = null ;
private String currentTag = null ;
List<TreeItem> treeItems = new ArrayList<TreeItem>();
public List<TreeItem> parseXML(Context context){
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
int rid = context.getResources().getIdentifier("ncsu.vi.treefinder:raw/treeitems", null, null);
//Log.d(LOGTAG, Integer.toString(rid));
InputStream stream = context.getResources().openRawResource(rid);
xpp.setInput(stream, null);
int eventType = xpp.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG){
handleStartTag(xpp.getName());
}else if (eventType == XmlPullParser.END_TAG){
currentTag = null;
}else if(eventType == XmlPullParser.TEXT){
handleText(xpp.getText());
}
eventType = xpp.next();
}
}
catch(NotFoundException e){
Log.d(LOGTAG, e.getMessage());
}
catch(XmlPullParserException e){
Log.d(LOGTAG, e.getMessage());
}
catch(IOException e){
Log.d(LOGTAG, e.getMessage());
}
return treeItems;
}
private void handleText(String text){
String xmlText = text;
if(currentTreeItem!= null && currentTag!= null){
if(currentTag.equals(TREEITEM_ID)){
Integer id = Integer.parseInt(xmlText);
currentTreeItem.setId(id);
}
else if (currentTag.equals(TREEITEM_IMAGEURL)){
currentTreeItem.setImageUrl(xmlText);
}
else if(currentTag.equals(TREEITEM_ITEMTYPE)) {
currentTreeItem.setItemType(xmlText);
}
else if(currentTag.equals(TREEITEM_DESCRIPTION)) {
currentTreeItem.setDescription(xmlText);
}
else if(currentTag.equals(TREEITEM_QUESTION)) {
currentTreeItem.setQuestion(xmlText);
}
}
}
private void handleStartTag(String name){
if(name.equals("treeItem")){
currentTreeItem = new TreeItem();
treeItems.add(currentTreeItem);
}
else{
currentTag = name;
}
}
}
| 2,894 | 0.719419 | 0.718383 | 106 | 26.301888 | 21.537668 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.59434 | false | false |
15
|
9f27bef55bff351e2851bc1e355a576b05c5e2a1
| 3,375,844,340,375 |
90aeae24f5d84e69138d5e800b3163b4b9b34724
|
/Main20171009002.java
|
49b06a7bde2a59ad8d8093072838771f9f417eca
|
[] |
no_license
|
hhfei/Algorithm
|
https://github.com/hhfei/Algorithm
|
d9346fe203bd50edeb640ec0b399d6223e090e88
|
1e1716ecf626a9fb7974ec9960af8697637429f4
|
refs/heads/master
| 2021-07-23T18:24:44.736000 | 2017-11-03T03:49:48 | 2017-11-03T03:49:48 | 109,145,701 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ZHIHU;
import ZHIHU.Main20170930_001.Node;
public class Main20171009002 {
/**
* 单链表的逆置
*/
private static class Node{
int value;
Node next;
}
private static Node reverse(Node head){
if(head == null){
return null;
}
Node pre = null;
Node cur = head;
Node next = cur.next;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//打印一个单链表
private static void printList(Node head) {
Node p = head;
while (p != null) {
System.out.print(p.value + " ");
p = p.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head1 = new Node();
head1.value = 1;
head1.next = new Node();
head1.next.value = 2;
head1.next.next = new Node();
head1.next.next.value = 3;
head1.next.next.next = new Node();
head1.next.next.next.value = 4;
head1.next.next.next.next = new Node();
head1.next.next.next.next.value = 5;
Node h = reverse(head1);
printList(h);
}
}
|
GB18030
|
Java
| 1,038 |
java
|
Main20171009002.java
|
Java
|
[] | null |
[] |
package ZHIHU;
import ZHIHU.Main20170930_001.Node;
public class Main20171009002 {
/**
* 单链表的逆置
*/
private static class Node{
int value;
Node next;
}
private static Node reverse(Node head){
if(head == null){
return null;
}
Node pre = null;
Node cur = head;
Node next = cur.next;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
//打印一个单链表
private static void printList(Node head) {
Node p = head;
while (p != null) {
System.out.print(p.value + " ");
p = p.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head1 = new Node();
head1.value = 1;
head1.next = new Node();
head1.next.value = 2;
head1.next.next = new Node();
head1.next.next.value = 3;
head1.next.next.next = new Node();
head1.next.next.next.value = 4;
head1.next.next.next.next = new Node();
head1.next.next.next.next.value = 5;
Node h = reverse(head1);
printList(h);
}
}
| 1,038 | 0.606719 | 0.56917 | 61 | 15.590164 | 13.035107 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.032787 | false | false |
15
|
52e13e4e0e6b782f1ccc7d016ffdcc1bb610ded1
| 34,600,256,547,047 |
f7ef52d760ec6cd18370dd71b1ba6e6870bd19ec
|
/integration-tests/src/test/java/integration/tests/gal/MVBaseTestScenario.java
|
08dc628d42f7dbd6cb2997ff017877e8797ffe77
|
[] |
no_license
|
cmoney/Troia-Server
|
https://github.com/cmoney/Troia-Server
|
c1ff6e7c614964565871c6cf65a47b9b313c4b29
|
b6ae640b85246a04a113c7c50fd789f503590864
|
refs/heads/master
| 2021-01-15T17:28:18.746000 | 2013-05-07T09:37:56 | 2013-05-07T09:37:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package test.java.integration.tests.gal;
import com.datascience.core.base.LObject;
import com.datascience.core.nominal.decision.ILabelProbabilityDistributionCostCalculator;
import com.datascience.core.nominal.decision.LabelProbabilityDistributionCostCalculators;
import com.datascience.mv.BatchMV;
import com.datascience.mv.IncrementalMV;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class MVBaseTestScenario extends BaseTestScenario {
public static class Setup {
public String algorithm;
public String testName;
public boolean loadEvaluationLabels;
public Setup(String alg, String tName, boolean lEvaluationLabels) {
algorithm = alg;
testName = tName;
loadEvaluationLabels = lEvaluationLabels;
}
}
public static void initSetup(Setup testSetup) {
if (testSetup.algorithm.equals("BMV")) {
setUp(new BatchMV(), testSetup.testName, testSetup.loadEvaluationLabels);
} else {
setUp(new IncrementalMV(), testSetup.testName, testSetup.loadEvaluationLabels);
}
}
@Test
public void test_ProbabilityDistributions_MV() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
Collection<LObject<String>> objects = data.getObjects();
//init the categoryProbabilities hashmap
HashMap<String, Double> categoryProbabilities = new HashMap<String, Double>();
for (String categoryName : data.getCategories()) {
categoryProbabilities.put(categoryName, 0.0);
}
//iterate through the datum objects and calculate the sum of the probabilities associated to each category
int noObjects = objects.size();
for (LObject<String> object : objects) {
Map<String, Double> objectProbabilities = project.getObjectResults(object).getCategoryProbabilites();
for (Map.Entry<String,Double> e : objectProbabilities.entrySet()) {
categoryProbabilities.put(e.getKey(), categoryProbabilities.get(e.getKey()) + e.getValue());
}
}
//calculate the average probability value for each category
for (String categoryName : data.getCategories()) {
categoryProbabilities.put(categoryName, categoryProbabilities.get(categoryName) / noObjects);
}
for (String categoryName : data.getCategories()) {
String metricName = "[MV_Pr[" + categoryName + "]] Majority Vote estimate for prior probability of category " + categoryName;
String expectedCategoryProbability = dataQuality.get(metricName);
String actualCategoryProbability = testHelper.format(categoryProbabilities.get(categoryName));
fileWriter.write("[MV_Pr[" + categoryName + "]]," + expectedCategoryProbability + "," + actualCategoryProbability);
assertEquals(expectedCategoryProbability, actualCategoryProbability);
}
}
@Test
public void test_DataCost_Estm_MV_Exp() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("EXPECTEDCOST");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_Exp] Estimated classification cost (MV_Exp metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_Exp," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Estm_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MAXLIKELIHOOD");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_ML] Estimated classification cost (MV_ML metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Estm_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MINCOST");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_Min] Estimated classification cost (MV_Min metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("MAXLIKELIHOOD");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_ML] Actual classification cost for majority vote classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("MINCOST");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_Min] Actual classification cost for naive min-cost classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_Soft() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("SOFT");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_Soft] Actual classification cost for naive soft-label classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_Soft," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MAXLIKELIHOOD");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_ML] Estimated data quality, naive majority label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_Exp() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("EXPECTEDCOST");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_Exp] Estimated data quality, naive soft label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_Exp," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MINCOST");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_Min] Estimated data quality, naive mincost label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("MAXLIKELIHOOD");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_ML] Actual data quality, naive majority label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("MINCOST");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_Min] Actual data quality, naive mincost label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_Soft() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("SOFT");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_Soft] Actual data quality, naive soft label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_Soft," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
}
|
UTF-8
|
Java
| 11,875 |
java
|
MVBaseTestScenario.java
|
Java
|
[] | null |
[] |
package test.java.integration.tests.gal;
import com.datascience.core.base.LObject;
import com.datascience.core.nominal.decision.ILabelProbabilityDistributionCostCalculator;
import com.datascience.core.nominal.decision.LabelProbabilityDistributionCostCalculators;
import com.datascience.mv.BatchMV;
import com.datascience.mv.IncrementalMV;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
public class MVBaseTestScenario extends BaseTestScenario {
public static class Setup {
public String algorithm;
public String testName;
public boolean loadEvaluationLabels;
public Setup(String alg, String tName, boolean lEvaluationLabels) {
algorithm = alg;
testName = tName;
loadEvaluationLabels = lEvaluationLabels;
}
}
public static void initSetup(Setup testSetup) {
if (testSetup.algorithm.equals("BMV")) {
setUp(new BatchMV(), testSetup.testName, testSetup.loadEvaluationLabels);
} else {
setUp(new IncrementalMV(), testSetup.testName, testSetup.loadEvaluationLabels);
}
}
@Test
public void test_ProbabilityDistributions_MV() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
Collection<LObject<String>> objects = data.getObjects();
//init the categoryProbabilities hashmap
HashMap<String, Double> categoryProbabilities = new HashMap<String, Double>();
for (String categoryName : data.getCategories()) {
categoryProbabilities.put(categoryName, 0.0);
}
//iterate through the datum objects and calculate the sum of the probabilities associated to each category
int noObjects = objects.size();
for (LObject<String> object : objects) {
Map<String, Double> objectProbabilities = project.getObjectResults(object).getCategoryProbabilites();
for (Map.Entry<String,Double> e : objectProbabilities.entrySet()) {
categoryProbabilities.put(e.getKey(), categoryProbabilities.get(e.getKey()) + e.getValue());
}
}
//calculate the average probability value for each category
for (String categoryName : data.getCategories()) {
categoryProbabilities.put(categoryName, categoryProbabilities.get(categoryName) / noObjects);
}
for (String categoryName : data.getCategories()) {
String metricName = "[MV_Pr[" + categoryName + "]] Majority Vote estimate for prior probability of category " + categoryName;
String expectedCategoryProbability = dataQuality.get(metricName);
String actualCategoryProbability = testHelper.format(categoryProbabilities.get(categoryName));
fileWriter.write("[MV_Pr[" + categoryName + "]]," + expectedCategoryProbability + "," + actualCategoryProbability);
assertEquals(expectedCategoryProbability, actualCategoryProbability);
}
}
@Test
public void test_DataCost_Estm_MV_Exp() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("EXPECTEDCOST");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_Exp] Estimated classification cost (MV_Exp metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_Exp," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Estm_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MAXLIKELIHOOD");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_ML] Estimated classification cost (MV_ML metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Estm_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MINCOST");
double avgClassificationCost = estimateMissclassificationCost(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataCost_Estm_MV_Min] Estimated classification cost (MV_Min metric)");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Estm_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("MAXLIKELIHOOD");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_ML] Actual classification cost for majority vote classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("MINCOST");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_Min] Actual classification cost for naive min-cost classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataCost_Eval_MV_Soft() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgClassificationCost = evaluateMissclassificationCost("SOFT");
String expectedClassificationCost = dataQuality.get("[DataCost_Eval_MV_Soft] Actual classification cost for naive soft-label classification");
String actualClassificationCost = testHelper.format(avgClassificationCost);
fileWriter.write("DataCost_Eval_MV_Soft," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MAXLIKELIHOOD");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_ML] Estimated data quality, naive majority label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_Exp() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("EXPECTEDCOST");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_Exp] Estimated data quality, naive soft label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_Exp," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Estm_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
ILabelProbabilityDistributionCostCalculator labelProbabilityDistributionCostCalculator = LabelProbabilityDistributionCostCalculators.get("MINCOST");
double avgQuality = estimateCostToQuality(labelProbabilityDistributionCostCalculator, null);
String expectedClassificationCost = dataQuality.get("[DataQuality_Estm_MV_Min] Estimated data quality, naive mincost label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Estm_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_ML() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("MAXLIKELIHOOD");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_ML] Actual data quality, naive majority label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_ML," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_Min() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("MINCOST");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_Min] Actual data quality, naive mincost label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_Min," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
@Test
public void test_DataQuality_Eval_MV_Soft() {
HashMap<String, String> dataQuality = summaryResultsParser.getDataQuality();
double avgQuality = evaluateCostToQuality("SOFT");
String expectedClassificationCost = dataQuality.get("[DataQuality_Eval_MV_Soft] Actual data quality, naive soft label");
String actualClassificationCost = testHelper.formatPercent(avgQuality);
fileWriter.write("DataQuality_Eval_MV_Soft," + expectedClassificationCost + "," + actualClassificationCost);
assertEquals(expectedClassificationCost, actualClassificationCost);
}
}
| 11,875 | 0.747705 | 0.747537 | 222 | 52.49099 | 47.564156 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.855856 | false | false |
15
|
fcb4e2bed41055888ac8adb7380f02dfb980a6e6
| 30,794,915,537,921 |
276e5cc7e225271cc3b4bde6b873a32375928588
|
/src/jedis/test/ZipListTest.java
|
0e71335eba7318a7adfe006c7cdc9eb584d7787c
|
[] |
no_license
|
qingzhengzhuma/jedis
|
https://github.com/qingzhengzhuma/jedis
|
199d4fc3306b5b089a1f776655e52fb3de3aa665
|
e152e2215301dace5cbf9ac85faf09c0d7de8038
|
refs/heads/master
| 2020-05-30T08:38:56.115000 | 2016-10-07T12:51:59 | 2016-10-07T12:51:59 | 69,105,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package jedis.test;
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Test;
import jedis.util.ZipList;
public class ZipListTest {
@Test
public void testGetEntrySize() {
ZipList zipList = new ZipList();
assertEquals(0, zipList.getEntrySize());
char[] entry = null;
zipList.push(entry);
assertEquals(0, zipList.getEntrySize());
entry = new char[0];
assertEquals(0, zipList.getEntrySize());
entry = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello".toCharArray();
zipList.push(entry);
assertEquals(1, zipList.getEntrySize());
}
@Test
public void testGetBlobSize() {
ZipList zipList = new ZipList();
assertEquals(0, zipList.getBlobSize());
char[] entry = null;
zipList.push(entry);
assertEquals(0, zipList.getBlobSize());
entry = new char[0];
assertEquals(0, zipList.getBlobSize());
entry = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello".toCharArray();
zipList.push(entry);
assertEquals(66, zipList.getBlobSize());
}
@Test
public void testPush(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.push(entry);
String s2 = (char)(entry.length) + string2;
assertEquals(s1+s2,zipList.toString());
}
@Test
public void testInsertAfter(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, true);
String s2 = (char)(entry.length) + string2;
assertEquals(s1 + s2,zipList.toString());
}
@Test
public void testInsertBefore(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, false);
String s2 = (char)(entry.length) + string2;
assertEquals(s2 + s1,zipList.toString());
}
@Test
public void testRemove() {
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
assertEquals(string2, new String(zipList.get(1)));
zipList.remove(1);
assertEquals(string3, new String(zipList.get(1)));
}
@Test
public void testRemoveRange(){
ZipList list1 = new ZipList(),list3 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
int i = 0;
for(;i < 3;++i){
list1.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
for(;i < 5; ++i){
list3.push(strings[i].toCharArray());
}
assertNotEquals(list3, list1);
list3.removeRange(3,2);
assertEquals(list3, list1);
}
@Test
public void testGet(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, true);
assertEquals(string, new String(zipList.get(0)));
assertEquals(string2, new String(zipList.get(1)));
}
@Test
public void testIterator(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
Iterator<char[]> iterator = zipList.iterator();
int i = 0;
while(iterator.hasNext()){
assertEquals(strings[i++], new String(iterator.next()));
}
}
@Test
public void testReverseIterator(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
String[] strings2 = {string3,string2,string};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
Iterator<char[]> iterator = zipList.reverseIterator();
int i = 0;
while(iterator.hasNext()){
assertEquals(strings2[i++], new String(iterator.next()));
}
}
@Test
public void testMerge(){
ZipList list1 = new ZipList(), list2 = new ZipList(),list3 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
int i = 0;
for(;i < 3;++i){
list1.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
for(;i < 5; ++i){
list2.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
ZipList list = list1.merge(list2);
assertEquals(list3, list);
}
@Test
public void testEquals(){
ZipList list1 = new ZipList(), list2 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
assertEquals(list1, list2);
for(String string : strings){
list1.push(string.toCharArray());
list2.push(string.toCharArray());
}
assertEquals(list1, list2);
list1.remove(0);
assertNotEquals(list1, list2);
}
@Test
public void testFind(){
ZipList list1 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
for(String string : strings){
list1.push(string.toCharArray());
}
assertEquals(list1.find("def".toCharArray()), 1);
assertEquals(list1.find("zzzz".toCharArray()), -1);
}
}
|
UTF-8
|
Java
| 6,057 |
java
|
ZipListTest.java
|
Java
|
[] | null |
[] |
package jedis.test;
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Test;
import jedis.util.ZipList;
public class ZipListTest {
@Test
public void testGetEntrySize() {
ZipList zipList = new ZipList();
assertEquals(0, zipList.getEntrySize());
char[] entry = null;
zipList.push(entry);
assertEquals(0, zipList.getEntrySize());
entry = new char[0];
assertEquals(0, zipList.getEntrySize());
entry = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello".toCharArray();
zipList.push(entry);
assertEquals(1, zipList.getEntrySize());
}
@Test
public void testGetBlobSize() {
ZipList zipList = new ZipList();
assertEquals(0, zipList.getBlobSize());
char[] entry = null;
zipList.push(entry);
assertEquals(0, zipList.getBlobSize());
entry = new char[0];
assertEquals(0, zipList.getBlobSize());
entry = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello".toCharArray();
zipList.push(entry);
assertEquals(66, zipList.getBlobSize());
}
@Test
public void testPush(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.push(entry);
String s2 = (char)(entry.length) + string2;
assertEquals(s1+s2,zipList.toString());
}
@Test
public void testInsertAfter(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, true);
String s2 = (char)(entry.length) + string2;
assertEquals(s1 + s2,zipList.toString());
}
@Test
public void testInsertBefore(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String s1 = (char)(entry.length) + string;
assertEquals(s1, zipList.toString());
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, false);
String s2 = (char)(entry.length) + string2;
assertEquals(s2 + s1,zipList.toString());
}
@Test
public void testRemove() {
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
assertEquals(string2, new String(zipList.get(1)));
zipList.remove(1);
assertEquals(string3, new String(zipList.get(1)));
}
@Test
public void testRemoveRange(){
ZipList list1 = new ZipList(),list3 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
int i = 0;
for(;i < 3;++i){
list1.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
for(;i < 5; ++i){
list3.push(strings[i].toCharArray());
}
assertNotEquals(list3, list1);
list3.removeRange(3,2);
assertEquals(list3, list1);
}
@Test
public void testGet(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
char[] entry = string.toCharArray();
zipList.push(entry);
String string2 = "women";
entry = string2.toCharArray();
zipList.insert(entry, 0, true);
assertEquals(string, new String(zipList.get(0)));
assertEquals(string2, new String(zipList.get(1)));
}
@Test
public void testIterator(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
Iterator<char[]> iterator = zipList.iterator();
int i = 0;
while(iterator.hasNext()){
assertEquals(strings[i++], new String(iterator.next()));
}
}
@Test
public void testReverseIterator(){
ZipList zipList = new ZipList();
String string = "sgedhtgrherjrtyjtyukerthwerutykyujtgehrwujuytrjtyjherethrhrehello";
String string2 = "women";
String string3 = "hello word";
String[] strings = {string,string2,string3};
String[] strings2 = {string3,string2,string};
for(String string4 : strings){
zipList.push(string4.toCharArray());
}
Iterator<char[]> iterator = zipList.reverseIterator();
int i = 0;
while(iterator.hasNext()){
assertEquals(strings2[i++], new String(iterator.next()));
}
}
@Test
public void testMerge(){
ZipList list1 = new ZipList(), list2 = new ZipList(),list3 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
int i = 0;
for(;i < 3;++i){
list1.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
for(;i < 5; ++i){
list2.push(strings[i].toCharArray());
list3.push(strings[i].toCharArray());
}
ZipList list = list1.merge(list2);
assertEquals(list3, list);
}
@Test
public void testEquals(){
ZipList list1 = new ZipList(), list2 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
assertEquals(list1, list2);
for(String string : strings){
list1.push(string.toCharArray());
list2.push(string.toCharArray());
}
assertEquals(list1, list2);
list1.remove(0);
assertNotEquals(list1, list2);
}
@Test
public void testFind(){
ZipList list1 = new ZipList();
String[] strings = {"abc","def","higklmn","weth","wo"};
for(String string : strings){
list1.push(string.toCharArray());
}
assertEquals(list1.find("def".toCharArray()), 1);
assertEquals(list1.find("zzzz".toCharArray()), -1);
}
}
| 6,057 | 0.695229 | 0.675747 | 209 | 27.980862 | 21.163742 | 92 | false | false | 0 | 0 | 0 | 0 | 65 | 0.096582 | 2.636364 | false | false |
15
|
fcf2b72889afd41e87b42371cc58a7f5c5f04ff4
| 35,716,948,049,025 |
8904f46f739f3c562e924e3862661ec9ea00eb8c
|
/Cwiczenie1/WstawPozFaktury.java
|
d24742e8c5befada9f06bc40165e2155057b8572
|
[] |
no_license
|
MarekOleksik/ZDA
|
https://github.com/MarekOleksik/ZDA
|
d291d8d46e95694aa9a3e8982b2632a68824118b
|
472c42bde6ef3ecf5a21cf8bd22bc792306fee9b
|
refs/heads/master
| 2022-02-06T02:24:19.307000 | 2019-01-23T19:32:59 | 2019-01-23T19:32:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class WstawPozFaktury extends JFrame {
public static void main(String[] args) {
new WstawPozFaktury();
}
private static final int
WINDOW_LOCATION_X = 250,
WINDOW_LOCATION_Y = 50,
WINDOW_WIDTH = 550,
WINDOW_HEIGHT = 100,
WINDOW_GRID_ROWS = 3,
WINDOW_GRID_COLS = 5;
private static final JLabel
kodProduktu = new JLabel("Kod produktu", JLabel.LEFT),
nazwaProduktu = new JLabel("Nazwa produktu", JLabel.LEFT),
ilosc = new JLabel("Ilość", JLabel.LEFT),
cenaNetto = new JLabel("Cena netto", JLabel.LEFT),
vat = new JLabel("Vat", JLabel.LEFT);
private static final JLabel[]
label_array = { kodProduktu, nazwaProduktu, ilosc, cenaNetto, vat };
public static final JTextField
txt_kodProduktu = new JTextField(""),
txt_nazwaProduktu = new JTextField(""),
txt_ilosc = new JTextField(""),
txt_cenaNetto = new JTextField(""),
txt_vat = new JTextField("");
// kontener do jtextfield
public static JTextField[] jtxt_array = { txt_kodProduktu, txt_nazwaProduktu, txt_ilosc, txt_cenaNetto, txt_vat };
// kontener do arraya z jtxtfield
static HashMap contener_prodoktow = new HashMap();
public static JButton
zamknij = new JButton("zamknij"),
wyczysc = new JButton("wyczyść"),
zapisz = new JButton("zapisz"),
wstaw = new JButton("wstaw"),
usun = new JButton("usuń");
public static JComboBox cbox = new JComboBox();
public WstawPozFaktury() {
JFrame frame = new JFrame("Wstaw pozycję do faktury");
//frame.setSize(300, 300);
//frame.setLocation(500, 300);
frame.setDefaultLookAndFeelDecorated(true);
//JPanel panel = new JPanel();
Container panel = frame.getContentPane();
for(int i=0;i < label_array.length; i++) {
panel.add(label_array[i]);
jtxt_array[i].setColumns(4);
panel.add(jtxt_array[i]);
}
frame.setLayout(new GridLayout(WINDOW_GRID_ROWS,WINDOW_GRID_COLS));
frame.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
frame.setLocation(WINDOW_LOCATION_X,WINDOW_LOCATION_Y);
panel.add(cbox);
panel.add(wyczysc);
panel.add(usun);
panel.add(zapisz);
panel.add(wstaw);
//panel.add(zamknij);
wyczysc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// petla zaczyna sie od jeden bo pierwszy jtxtfield nadaje nazwe
// calej tablicy i musi byc zachowana
for(int i=0;i<Okno.jtxt_array.length;i++) {
jtxt_array[i].setText("");
}
}
});
zapisz.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String nazwa_nabywcy = JOptionPane.showInputDialog(null,"Wpisz nazwę produktu","Zapisywanie danych", JOptionPane.PLAIN_MESSAGE);
zapiszDane(nazwa_nabywcy);
}
});
zamknij.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
cbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox t = (JComboBox)e.getSource();
if(t.getSelectedItem()!="wybierz odbiorce")
wczytajDane((String)t.getSelectedItem());
}
});
usun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
usunDane((String)cbox.getSelectedItem());
}
});
wstaw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Produkty prod = new Produkty(txt_kodProduktu.getText(),
txt_nazwaProduktu.getText(),
Integer.parseInt(txt_ilosc.getText()),
Double.parseDouble(txt_cenaNetto.getText()),
Integer.parseInt(txt_vat.getText())
);
DefaultTableModel model = (DefaultTableModel) (FormularzFaktury.tablePozFakt).getModel();
Object [] rzad = new Object[6];
rzad[0] = prod.getKodProduktu();
rzad[1] = prod.getNazwaProduktu();
rzad[2] = prod.getIlosc();
rzad[3] = prod.getCenaNetto();
rzad[4] = prod.getVat();
rzad[5] = String.valueOf(prod.getCenaNetto()*prod.getVat()+prod.getCenaNetto());
model.addRow(rzad);
for (Object i:rzad)
System.out.println(i);
}
});
frame.setVisible(true);
}
private void zapiszDane(String nazwa) {
try {
// wczytuje obiekt z pliku ktory jezeli nie istnieje to jest tworzony podczas startu programu
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
in.close();
// dodaje nowe pola i zapisuje spowrotem
if(contener_prodoktow.containsKey(nazwa))
throw new MyException();
cbox.addItem(nazwa);
contener_prodoktow.put(nazwa, jtxt_array);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
}
catch(MyException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: podana nazwa już istnieje","Podaj inną nazwę",JOptionPane.WARNING_MESSAGE);
}
catch(ClassCastException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
catch(Exception ioE) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: podczas odczytu/zapisu pliku: "+ioE,"Błąd", JOptionPane.ERROR_MESSAGE);
}
}
private void usunDane(String klucz){
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
in.close();
contener_prodoktow.remove(klucz);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
cbox.removeItem(klucz);
}
catch(ClassCastException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioE) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd podczas odczytu/zapisu pliku: "+ioE,"Błąd", JOptionPane.ERROR_MESSAGE);
}
catch(ClassNotFoundException E) {
JOptionPane.showMessageDialog(null,"Błąd w strukturze pliku tablica_nabywcow.txt usuń ten plik i uruchom ponownie program UWAGA utracisz dane odbiorców."+E,"Błąd", JOptionPane.ERROR_MESSAGE);
}
}
private void wczytajDane(String klucz) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
String[] t = (String[])contener_prodoktow.keySet().toArray(new String[contener_prodoktow.size()]);
JTextField[] tmp_array = (JTextField[])contener_prodoktow.get(klucz);
for(int i=0;i<tmp_array.length;i++) {
jtxt_array[i].setText(tmp_array[i].getText());
}
}
catch(Exception E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
}
private void zapisz() {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
}
catch(Exception E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
}
class MyException extends Exception {
//static final long serialVersionUID = 15l;
}
}
|
UTF-8
|
Java
| 7,725 |
java
|
WstawPozFaktury.java
|
Java
|
[] | null |
[] |
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class WstawPozFaktury extends JFrame {
public static void main(String[] args) {
new WstawPozFaktury();
}
private static final int
WINDOW_LOCATION_X = 250,
WINDOW_LOCATION_Y = 50,
WINDOW_WIDTH = 550,
WINDOW_HEIGHT = 100,
WINDOW_GRID_ROWS = 3,
WINDOW_GRID_COLS = 5;
private static final JLabel
kodProduktu = new JLabel("Kod produktu", JLabel.LEFT),
nazwaProduktu = new JLabel("Nazwa produktu", JLabel.LEFT),
ilosc = new JLabel("Ilość", JLabel.LEFT),
cenaNetto = new JLabel("Cena netto", JLabel.LEFT),
vat = new JLabel("Vat", JLabel.LEFT);
private static final JLabel[]
label_array = { kodProduktu, nazwaProduktu, ilosc, cenaNetto, vat };
public static final JTextField
txt_kodProduktu = new JTextField(""),
txt_nazwaProduktu = new JTextField(""),
txt_ilosc = new JTextField(""),
txt_cenaNetto = new JTextField(""),
txt_vat = new JTextField("");
// kontener do jtextfield
public static JTextField[] jtxt_array = { txt_kodProduktu, txt_nazwaProduktu, txt_ilosc, txt_cenaNetto, txt_vat };
// kontener do arraya z jtxtfield
static HashMap contener_prodoktow = new HashMap();
public static JButton
zamknij = new JButton("zamknij"),
wyczysc = new JButton("wyczyść"),
zapisz = new JButton("zapisz"),
wstaw = new JButton("wstaw"),
usun = new JButton("usuń");
public static JComboBox cbox = new JComboBox();
public WstawPozFaktury() {
JFrame frame = new JFrame("Wstaw pozycję do faktury");
//frame.setSize(300, 300);
//frame.setLocation(500, 300);
frame.setDefaultLookAndFeelDecorated(true);
//JPanel panel = new JPanel();
Container panel = frame.getContentPane();
for(int i=0;i < label_array.length; i++) {
panel.add(label_array[i]);
jtxt_array[i].setColumns(4);
panel.add(jtxt_array[i]);
}
frame.setLayout(new GridLayout(WINDOW_GRID_ROWS,WINDOW_GRID_COLS));
frame.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
frame.setLocation(WINDOW_LOCATION_X,WINDOW_LOCATION_Y);
panel.add(cbox);
panel.add(wyczysc);
panel.add(usun);
panel.add(zapisz);
panel.add(wstaw);
//panel.add(zamknij);
wyczysc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// petla zaczyna sie od jeden bo pierwszy jtxtfield nadaje nazwe
// calej tablicy i musi byc zachowana
for(int i=0;i<Okno.jtxt_array.length;i++) {
jtxt_array[i].setText("");
}
}
});
zapisz.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String nazwa_nabywcy = JOptionPane.showInputDialog(null,"Wpisz nazwę produktu","Zapisywanie danych", JOptionPane.PLAIN_MESSAGE);
zapiszDane(nazwa_nabywcy);
}
});
zamknij.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
cbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox t = (JComboBox)e.getSource();
if(t.getSelectedItem()!="wybierz odbiorce")
wczytajDane((String)t.getSelectedItem());
}
});
usun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
usunDane((String)cbox.getSelectedItem());
}
});
wstaw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Produkty prod = new Produkty(txt_kodProduktu.getText(),
txt_nazwaProduktu.getText(),
Integer.parseInt(txt_ilosc.getText()),
Double.parseDouble(txt_cenaNetto.getText()),
Integer.parseInt(txt_vat.getText())
);
DefaultTableModel model = (DefaultTableModel) (FormularzFaktury.tablePozFakt).getModel();
Object [] rzad = new Object[6];
rzad[0] = prod.getKodProduktu();
rzad[1] = prod.getNazwaProduktu();
rzad[2] = prod.getIlosc();
rzad[3] = prod.getCenaNetto();
rzad[4] = prod.getVat();
rzad[5] = String.valueOf(prod.getCenaNetto()*prod.getVat()+prod.getCenaNetto());
model.addRow(rzad);
for (Object i:rzad)
System.out.println(i);
}
});
frame.setVisible(true);
}
private void zapiszDane(String nazwa) {
try {
// wczytuje obiekt z pliku ktory jezeli nie istnieje to jest tworzony podczas startu programu
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
in.close();
// dodaje nowe pola i zapisuje spowrotem
if(contener_prodoktow.containsKey(nazwa))
throw new MyException();
cbox.addItem(nazwa);
contener_prodoktow.put(nazwa, jtxt_array);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
}
catch(MyException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: podana nazwa już istnieje","Podaj inną nazwę",JOptionPane.WARNING_MESSAGE);
}
catch(ClassCastException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
catch(Exception ioE) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: podczas odczytu/zapisu pliku: "+ioE,"Błąd", JOptionPane.ERROR_MESSAGE);
}
}
private void usunDane(String klucz){
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
in.close();
contener_prodoktow.remove(klucz);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
cbox.removeItem(klucz);
}
catch(ClassCastException E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
catch(IOException ioE) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd podczas odczytu/zapisu pliku: "+ioE,"Błąd", JOptionPane.ERROR_MESSAGE);
}
catch(ClassNotFoundException E) {
JOptionPane.showMessageDialog(null,"Błąd w strukturze pliku tablica_nabywcow.txt usuń ten plik i uruchom ponownie program UWAGA utracisz dane odbiorców."+E,"Błąd", JOptionPane.ERROR_MESSAGE);
}
}
private void wczytajDane(String klucz) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablica_nabywcow.txt"));
contener_prodoktow = (HashMap)in.readObject();
String[] t = (String[])contener_prodoktow.keySet().toArray(new String[contener_prodoktow.size()]);
JTextField[] tmp_array = (JTextField[])contener_prodoktow.get(klucz);
for(int i=0;i<tmp_array.length;i++) {
jtxt_array[i].setText(tmp_array[i].getText());
}
}
catch(Exception E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
}
private void zapisz() {
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablica_nabywcow.txt"));
out.writeObject(contener_prodoktow);
out.close();
}
catch(Exception E) {
JOptionPane.showMessageDialog(null,"Wystąpił błąd: "+E,"Błąd",JOptionPane.ERROR_MESSAGE);
}
}
class MyException extends Exception {
//static final long serialVersionUID = 15l;
}
}
| 7,725 | 0.717695 | 0.712609 | 239 | 31.087866 | 29.731655 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.707113 | false | false |
15
|
4495931c6d36ee48b21b1e22c47776abdff9403d
| 21,431,886,841,454 |
19b463e046a46db4131ca866537a131ac6acb150
|
/qpalx-elearning-service/src/main/java/com/quaza/solutions/qpalx/elearning/service/qpalxuser/IQPalXUserSubscriptionService.java
|
67ef6067d6198d6ba8e4927565e5ccaae9af9d4f
|
[] |
no_license
|
Quaza-Solutions/quaza-solutions-elearning-qpalx
|
https://github.com/Quaza-Solutions/quaza-solutions-elearning-qpalx
|
49f913b4eea3d02f7097cdb40e972ae027bad17e
|
421501cda3cb1aa59f11e4d9a330f4b3bf6c2236
|
refs/heads/master
| 2020-04-04T07:30:09.545000 | 2016-12-11T04:55:29 | 2016-12-11T04:55:29 | 50,192,947 | 0 | 0 | null | false | 2016-12-11T04:55:29 | 2016-01-22T16:26:47 | 2016-09-29T02:45:35 | 2016-12-11T04:55:29 | 35,206 | 0 | 0 | 0 |
Java
| null | null |
package com.quaza.solutions.qpalx.elearning.service.qpalxuser;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.IQPalXUserVO;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.QPalXUser;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.profile.StudentSubscriptionProfile;
import com.quaza.solutions.qpalx.elearning.domain.subscription.QPalXSubscription;
import java.util.Optional;
/**
*
* @author manyce400
*/
public interface IQPalXUserSubscriptionService {
public void updateQPalXUserInfo(QPalXUser qPalXUser, IQPalXUserVO iqPalXUserVO);
/**
* Create a brand new QPalXUser without a Tutorial Subscription. This is generally used to create all non Student users.
*
* @param iqPalXUserVO
* @return Optional object, empty if implementation is unable to create QPalXUser with registration
*/
public Optional<QPalXUser> createNewQPalXUser(IQPalXUserVO iqPalXUserVO);
/**
* Create a brand new QPalXUser with a valid active Subscription from today given QPalXUser Value Object.
*
* This represents setting up a brand new user for the first time in the system.
*
* @param iqPalXUserVO
* @return Optional object, empty if implementation is unable to create QPalXUser with registration
*/
public Optional<QPalXUser> createNewQPalXUserWithTutorialSubscription(IQPalXUserVO iqPalXUserVO);
/**
* Renew QPalX Student user's subscription with the Subscription passed in as argument.
*
* @param qPalXUser
* @param subscription
*/
public boolean renewQPalXUserSubscription(QPalXUser qPalXUser, QPalXSubscription subscription);
/**
* Creates a brand new StudentSubscriptionProfile given a subscriptionID for a QPalXUser.
*
* @param subscriptionID
* @param qPalXUser
* @return
*/
public Optional<StudentSubscriptionProfile> addQPalXUserTutorialSubscriptionProfile(Long subscriptionID, QPalXUser qPalXUser);
}
|
UTF-8
|
Java
| 1,993 |
java
|
IQPalXUserSubscriptionService.java
|
Java
|
[
{
"context": "on;\n\nimport java.util.Optional;\n\n/**\n *\n * @author manyce400\n */\npublic interface IQPalXUserSubscriptionServic",
"end": 443,
"score": 0.9995085000991821,
"start": 434,
"tag": "USERNAME",
"value": "manyce400"
}
] | null |
[] |
package com.quaza.solutions.qpalx.elearning.service.qpalxuser;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.IQPalXUserVO;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.QPalXUser;
import com.quaza.solutions.qpalx.elearning.domain.qpalxuser.profile.StudentSubscriptionProfile;
import com.quaza.solutions.qpalx.elearning.domain.subscription.QPalXSubscription;
import java.util.Optional;
/**
*
* @author manyce400
*/
public interface IQPalXUserSubscriptionService {
public void updateQPalXUserInfo(QPalXUser qPalXUser, IQPalXUserVO iqPalXUserVO);
/**
* Create a brand new QPalXUser without a Tutorial Subscription. This is generally used to create all non Student users.
*
* @param iqPalXUserVO
* @return Optional object, empty if implementation is unable to create QPalXUser with registration
*/
public Optional<QPalXUser> createNewQPalXUser(IQPalXUserVO iqPalXUserVO);
/**
* Create a brand new QPalXUser with a valid active Subscription from today given QPalXUser Value Object.
*
* This represents setting up a brand new user for the first time in the system.
*
* @param iqPalXUserVO
* @return Optional object, empty if implementation is unable to create QPalXUser with registration
*/
public Optional<QPalXUser> createNewQPalXUserWithTutorialSubscription(IQPalXUserVO iqPalXUserVO);
/**
* Renew QPalX Student user's subscription with the Subscription passed in as argument.
*
* @param qPalXUser
* @param subscription
*/
public boolean renewQPalXUserSubscription(QPalXUser qPalXUser, QPalXSubscription subscription);
/**
* Creates a brand new StudentSubscriptionProfile given a subscriptionID for a QPalXUser.
*
* @param subscriptionID
* @param qPalXUser
* @return
*/
public Optional<StudentSubscriptionProfile> addQPalXUserTutorialSubscriptionProfile(Long subscriptionID, QPalXUser qPalXUser);
}
| 1,993 | 0.753638 | 0.752132 | 57 | 33.947369 | 40.740696 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.280702 | false | false |
15
|
44031f7b953ed40488d66e6815b0e7eeebb899b6
| 34,033,320,866,711 |
eb187b7eaa1109fc97d917259e98bf36e82d40f1
|
/src/main/java/com/github/foxty/topaz/common/TopazUtil.java
|
0c310e9c98ef8905513d07d399e0df4c088a20a1
|
[] |
no_license
|
foxty/topaz
|
https://github.com/foxty/topaz
|
2f733a461d66920bdcdc6ccc0d0900bdf2a2a3e9
|
159b2ae910e6477602a7b6da9061ad980fcdd4a0
|
refs/heads/master
| 2020-06-02T05:18:56.188000 | 2018-04-13T01:59:10 | 2018-04-13T01:59:10 | 32,129,549 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.github.foxty.topaz.common;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
public class TopazUtil {
private static Log log = LogFactory.getLog(TopazUtil.class);
/**
* Convert input str to underscore split
*
* e.g. AbcDefDAo to abc_def
*
* @param input input string
* @return converted string
*/
public static String camel2flat(String input) {
StringBuffer result = new StringBuffer();
result.append(Character.toLowerCase(input.charAt(0)));
char[] chars = input.substring(1).toCharArray();
for (char c : chars) {
if (c >= 'A' && c <= 'Z') {
result.append("_").append(Character.toLowerCase(c));
} else {
result.append(c);
}
}
return result.toString().toLowerCase();
}
/**
* e.g. set_something to setSomething
*
* @param input input string
* @return converted string
*/
public static String flat2camel(String input) {
StringBuffer result = new StringBuffer();
String[] arr = input.toLowerCase().split("_");
result.append(arr[0]);
for (int i = 1; i < arr.length; i++) {
String ele = arr[i];
if (StringUtils.isNotBlank(ele)) {
result.append(StringUtils.capitalize(ele));
}
}
return result.toString();
}
@Deprecated
public static String MD5(String str) {
return digest("MD5", str);
}
public static String SHA1(String str) {
return digest("SHA-1", str);
}
public static String SHA256(String str) {
return digest("SHA-256", str);
}
public static String SHA512(String str) {
return digest("SHA-512", str);
}
public static String digest(String algo, String origStr) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(algo);
} catch (NoSuchAlgorithmException e) {
throw new TopazException(e);
}
digest.update(origStr.getBytes(Charset.forName("ASCII")));
byte[] bytes = digest.digest();
StringBuffer sb = new StringBuffer();
for (byte b : bytes) {
String s = Integer.toHexString(Math.abs(b));
sb.append(s.length() == 1 ? "0" + s : s);
}
return sb.toString();
}
public static long checksumCRC32(InputStream ins) throws IOException {
CRC32 crc = new CRC32();
InputStream in = null;
try {
in = new CheckedInputStream(ins, crc);
IOUtils.copy(in, new NullOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
return crc.getValue();
}
public static float parseFloat(String v, float def) {
float re = def;
try {
re = Float.parseFloat(v);
} catch (NumberFormatException e) {
log.error(e.getMessage(), e);
}
return re;
}
public static boolean isFloatEqual(float f1, float f2, float precision) {
return Math.abs(f1 - f2) <= precision;
}
public static boolean isDoubleEqual(double f1, double f2, double precision) {
return Math.abs(f1 - f2) <= precision;
}
public static String formatDate(Date d, String fmt) {
String re = d.toString();
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
re = sdf.format(d);
return re;
}
public static LocalDate parseDate(String dateString, String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
LocalDate ld = null;
try {
ld = LocalDate.parse(dateString, dtf);
} catch (DateTimeParseException e) {
log.error(e.getMessage(), e);
}
return ld;
}
public static LocalDateTime parseDateTime(String dateString, String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
LocalDateTime ldt = null;
try {
ldt = LocalDateTime.parse(dateString, dtf);
} catch (DateTimeParseException e) {
log.error(e.getMessage(), e);
}
return ldt;
}
/**
* Truncate hh:mm:ss.si part with 0, leave year/month/day not touched.
*
* @param d input date
* @return Date without hours, minutes and seconds
*/
public static Date truncTime(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date endOfMonth(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 0);
Date endOfMonth = cal.getTime();
return endOfMonth;
}
/**
* Get milliseconds diff between two times, use d1.getTime()- d2.getTime(), use 0
* if date is null.
*
* @param d1 first input datetime
* @param d2 second input datetime
* @return long milliseconds
*/
public static long timeDiffInMilli(Date d1, Date d2) {
long t1 = d1 == null ? 0 : d1.getTime();
long t2 = d2 == null ? 0 : d2.getTime();
return t1 - t2;
}
public static long timeDiffInSec(Date d1, Date d2) {
long milliDiff = timeDiffInMilli(d1, d2);
return milliDiff / 1000;
}
public static long timeDiffInHour(Date d1, Date d2) {
long milliDiff = timeDiffInMilli(d1, d2);
return milliDiff / 1000 / 3600;
}
public static String genUUID() {
return UUID.randomUUID().toString();
}
/**
* Remove duplicate / in the uri, remove trailing /
* e.g.
* //a/b/predicate/ to /a/b/predicate
* a/b/predicate to /a/b/predicate
* a//b//predicate to a/b/predicate
*
* @param uri input uri string
* @return String uri after clean
*/
public static String cleanUri(String uri) {
Objects.requireNonNull(uri);
uri = uri.replaceAll("/{2,}", "/");
if (uri.endsWith("/")) {
uri = uri.substring(0, uri.length() - 1);
}
if (!uri.startsWith("/")) {
uri = "/" + uri;
}
return uri;
}
}
|
UTF-8
|
Java
| 7,134 |
java
|
TopazUtil.java
|
Java
|
[
{
"context": "package com.github.foxty.topaz.common;\n\nimport org.apache.commons.io.IOUti",
"end": 24,
"score": 0.9779478907585144,
"start": 19,
"tag": "USERNAME",
"value": "foxty"
}
] | null |
[] |
package com.github.foxty.topaz.common;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
public class TopazUtil {
private static Log log = LogFactory.getLog(TopazUtil.class);
/**
* Convert input str to underscore split
*
* e.g. AbcDefDAo to abc_def
*
* @param input input string
* @return converted string
*/
public static String camel2flat(String input) {
StringBuffer result = new StringBuffer();
result.append(Character.toLowerCase(input.charAt(0)));
char[] chars = input.substring(1).toCharArray();
for (char c : chars) {
if (c >= 'A' && c <= 'Z') {
result.append("_").append(Character.toLowerCase(c));
} else {
result.append(c);
}
}
return result.toString().toLowerCase();
}
/**
* e.g. set_something to setSomething
*
* @param input input string
* @return converted string
*/
public static String flat2camel(String input) {
StringBuffer result = new StringBuffer();
String[] arr = input.toLowerCase().split("_");
result.append(arr[0]);
for (int i = 1; i < arr.length; i++) {
String ele = arr[i];
if (StringUtils.isNotBlank(ele)) {
result.append(StringUtils.capitalize(ele));
}
}
return result.toString();
}
@Deprecated
public static String MD5(String str) {
return digest("MD5", str);
}
public static String SHA1(String str) {
return digest("SHA-1", str);
}
public static String SHA256(String str) {
return digest("SHA-256", str);
}
public static String SHA512(String str) {
return digest("SHA-512", str);
}
public static String digest(String algo, String origStr) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(algo);
} catch (NoSuchAlgorithmException e) {
throw new TopazException(e);
}
digest.update(origStr.getBytes(Charset.forName("ASCII")));
byte[] bytes = digest.digest();
StringBuffer sb = new StringBuffer();
for (byte b : bytes) {
String s = Integer.toHexString(Math.abs(b));
sb.append(s.length() == 1 ? "0" + s : s);
}
return sb.toString();
}
public static long checksumCRC32(InputStream ins) throws IOException {
CRC32 crc = new CRC32();
InputStream in = null;
try {
in = new CheckedInputStream(ins, crc);
IOUtils.copy(in, new NullOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
return crc.getValue();
}
public static float parseFloat(String v, float def) {
float re = def;
try {
re = Float.parseFloat(v);
} catch (NumberFormatException e) {
log.error(e.getMessage(), e);
}
return re;
}
public static boolean isFloatEqual(float f1, float f2, float precision) {
return Math.abs(f1 - f2) <= precision;
}
public static boolean isDoubleEqual(double f1, double f2, double precision) {
return Math.abs(f1 - f2) <= precision;
}
public static String formatDate(Date d, String fmt) {
String re = d.toString();
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
re = sdf.format(d);
return re;
}
public static LocalDate parseDate(String dateString, String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
LocalDate ld = null;
try {
ld = LocalDate.parse(dateString, dtf);
} catch (DateTimeParseException e) {
log.error(e.getMessage(), e);
}
return ld;
}
public static LocalDateTime parseDateTime(String dateString, String format) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
LocalDateTime ldt = null;
try {
ldt = LocalDateTime.parse(dateString, dtf);
} catch (DateTimeParseException e) {
log.error(e.getMessage(), e);
}
return ldt;
}
/**
* Truncate hh:mm:ss.si part with 0, leave year/month/day not touched.
*
* @param d input date
* @return Date without hours, minutes and seconds
*/
public static Date truncTime(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
public static Date endOfMonth(Date d) {
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 0);
Date endOfMonth = cal.getTime();
return endOfMonth;
}
/**
* Get milliseconds diff between two times, use d1.getTime()- d2.getTime(), use 0
* if date is null.
*
* @param d1 first input datetime
* @param d2 second input datetime
* @return long milliseconds
*/
public static long timeDiffInMilli(Date d1, Date d2) {
long t1 = d1 == null ? 0 : d1.getTime();
long t2 = d2 == null ? 0 : d2.getTime();
return t1 - t2;
}
public static long timeDiffInSec(Date d1, Date d2) {
long milliDiff = timeDiffInMilli(d1, d2);
return milliDiff / 1000;
}
public static long timeDiffInHour(Date d1, Date d2) {
long milliDiff = timeDiffInMilli(d1, d2);
return milliDiff / 1000 / 3600;
}
public static String genUUID() {
return UUID.randomUUID().toString();
}
/**
* Remove duplicate / in the uri, remove trailing /
* e.g.
* //a/b/predicate/ to /a/b/predicate
* a/b/predicate to /a/b/predicate
* a//b//predicate to a/b/predicate
*
* @param uri input uri string
* @return String uri after clean
*/
public static String cleanUri(String uri) {
Objects.requireNonNull(uri);
uri = uri.replaceAll("/{2,}", "/");
if (uri.endsWith("/")) {
uri = uri.substring(0, uri.length() - 1);
}
if (!uri.startsWith("/")) {
uri = "/" + uri;
}
return uri;
}
}
| 7,134 | 0.592795 | 0.5806 | 246 | 28 | 21.029596 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573171 | false | false |
15
|
9832dccd6e47adc49e2c10f0ca15a36640a4b61d
| 24,627,342,478,074 |
f6bda11b226794e1875dd5ccf8117636cc6ffb34
|
/src/test/java/com/restapi/test/TC_002_POST_Request.java
|
e204a91dd112228b2019feb3f74855c6b67b24a8
|
[] |
no_license
|
vnarkar-prog/RestAssuredApiAutomation
|
https://github.com/vnarkar-prog/RestAssuredApiAutomation
|
6b8aef3a4480f93b34868b9dc0ab1105fa7404d2
|
6dfc970e35f65c21ee55c6b25f5a346c0760b9e7
|
refs/heads/master
| 2022-12-19T11:45:56.313000 | 2020-09-23T09:34:21 | 2020-09-23T09:34:21 | 297,920,503 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.restapi.test;
import org.json.simple.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class TC_002_POST_Request {
@Test
void createUser() {
// specify endpoint
RestAssured.baseURI = "https://reqres.in";
// Request object
RequestSpecification httpRequest = RestAssured.given();
//payload
JSONObject requestParams = new JSONObject();
requestParams.put("name", "morpheus");
requestParams.put("job", "leader");
//adding header
httpRequest.header("application/form-data", ContentType.TEXT);
httpRequest.body(requestParams.toJSONString()); //attach data to request
Response response = httpRequest.request(Method.POST, "/api/users");
String responseBody = response.getBody().asString();
// Step 4: Validate & Print response
System.out.println("Response is :" + responseBody);
int statusCode = response.getStatusCode();
System.out.println("Status Code is :" + statusCode);
Assert.assertEquals(statusCode, 201);
String id = response.jsonPath().get("id");
System.out.println("User has been created with id:" +id);
}
}
|
UTF-8
|
Java
| 1,320 |
java
|
TC_002_POST_Request.java
|
Java
|
[
{
"context": " = new JSONObject();\n\t\trequestParams.put(\"name\", \"morpheus\");\n\t\trequestParams.put(\"job\", \"leader\");\n\n\t\t//add",
"end": 643,
"score": 0.9975060820579529,
"start": 635,
"tag": "NAME",
"value": "morpheus"
}
] | null |
[] |
package com.restapi.test;
import org.json.simple.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class TC_002_POST_Request {
@Test
void createUser() {
// specify endpoint
RestAssured.baseURI = "https://reqres.in";
// Request object
RequestSpecification httpRequest = RestAssured.given();
//payload
JSONObject requestParams = new JSONObject();
requestParams.put("name", "morpheus");
requestParams.put("job", "leader");
//adding header
httpRequest.header("application/form-data", ContentType.TEXT);
httpRequest.body(requestParams.toJSONString()); //attach data to request
Response response = httpRequest.request(Method.POST, "/api/users");
String responseBody = response.getBody().asString();
// Step 4: Validate & Print response
System.out.println("Response is :" + responseBody);
int statusCode = response.getStatusCode();
System.out.println("Status Code is :" + statusCode);
Assert.assertEquals(statusCode, 201);
String id = response.jsonPath().get("id");
System.out.println("User has been created with id:" +id);
}
}
| 1,320 | 0.743182 | 0.737879 | 50 | 25.4 | 22.989563 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.44 | false | false |
15
|
6f5c34ccc4aec17355be2e72096a8d71521362b4
| 6,760,278,554,445 |
1f9baaa9d5ae5d31a68f8958421192b287338439
|
/app/src/main/java/ci/ws/Models/entities/CICheckVersionAndAnnouncementResp.java
|
f4e378dc6fcbb728454a80c86b4086a952e325fe
|
[] |
no_license
|
TkWu/CAL_live_code-1
|
https://github.com/TkWu/CAL_live_code-1
|
538dde0ce66825026ef01d3fadfcbf4d6e4b1dd0
|
ba30ccfd8056b9cc3045b8e06e8dc60b654c1e55
|
refs/heads/master
| 2020-08-29T09:16:35.600000 | 2019-10-23T06:46:53 | 2019-10-23T06:46:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package ci.ws.Models.entities;
import java.util.ArrayList;
/**
* Created by KevinCheng on 17/8/29.
* Doc. : CI_APP_API_CheckVersion.docx
* 功能說明:版本更新通知與重要公告。
*/
public class CICheckVersionAndAnnouncementResp extends ArrayList<CICheckVersionAndAnnouncementEntity> {
}
|
UTF-8
|
Java
| 307 |
java
|
CICheckVersionAndAnnouncementResp.java
|
Java
|
[
{
"context": "s;\n\nimport java.util.ArrayList;\n\n/**\n * Created by KevinCheng on 17/8/29.\n * Doc. : CI_APP_API_CheckVersion.doc",
"end": 89,
"score": 0.7977442741394043,
"start": 79,
"tag": "NAME",
"value": "KevinCheng"
}
] | null |
[] |
package ci.ws.Models.entities;
import java.util.ArrayList;
/**
* Created by KevinCheng on 17/8/29.
* Doc. : CI_APP_API_CheckVersion.docx
* 功能說明:版本更新通知與重要公告。
*/
public class CICheckVersionAndAnnouncementResp extends ArrayList<CICheckVersionAndAnnouncementEntity> {
}
| 307 | 0.772894 | 0.754579 | 12 | 21.75 | 28.460865 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false |
15
|
3aceff59a7c39cfe5fa49bc24b564fa699323384
| 17,600,776,009,453 |
b314011195d3888afe0f86caac0b6f3b4e7770fd
|
/src/test/java/com/mma/web/tests/MercariWebTests.java
|
6f046bfedf0447df945374592250a2bc70529df7
|
[] |
no_license
|
IshanShah1989/MercariAutomationFramework
|
https://github.com/IshanShah1989/MercariAutomationFramework
|
d942bea5996fb0c0924f6298b09e7c49f776c7ba
|
5404d999081670174ae1b66c18d3322a2c2ed9a0
|
refs/heads/main
| 2023-04-14T02:14:54.585000 | 2021-04-19T13:52:55 | 2021-04-19T13:52:55 | 359,445,537 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.mma.web.tests;
import java.lang.reflect.Method;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.mma.web.pages.HomePage;
import com.mma.web.pages.LoginPage;
import com.mma.web.pages.ProfilePage;
import com.mma.web.pages.SearchResultsPage;
import com.mma.web.util.BasicWebPage;
public class MercariWebTests {
WebDriver wd;
BasicWebPage bwp = new BasicWebPage();
LoginPage lp;
HomePage hp = new HomePage();
SearchResultsPage sp = new SearchResultsPage();
ProfilePage pr;
@BeforeMethod
public void beforeClass(Method method)
{
wd = bwp.getDriver();
lp = new LoginPage();
bwp.navigateUrl();
}
@Test
public void testScenario1()
{
pr = hp.clickProfile();
pr.clickMenuLink("My address");
pr.addAddressDetails("Arania", "Jain", "124 Vijay Nagar", "61259", "Illinois", "Illinois");
}
@Test
public void testScenario2()
{
String searchText = "MacBook";
String title;
hp.search(searchText);
title = sp.clickSearchedElement("3");
System.out.println("Title is " + title);
Assert.assertTrue(title.contains(searchText),"Either Text doesnot Match or Text is not present in the title");
}
@AfterMethod
public void afterMethod()
{
wd.close();
}
}
|
UTF-8
|
Java
| 1,411 |
java
|
MercariWebTests.java
|
Java
|
[] | null |
[] |
package com.mma.web.tests;
import java.lang.reflect.Method;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.mma.web.pages.HomePage;
import com.mma.web.pages.LoginPage;
import com.mma.web.pages.ProfilePage;
import com.mma.web.pages.SearchResultsPage;
import com.mma.web.util.BasicWebPage;
public class MercariWebTests {
WebDriver wd;
BasicWebPage bwp = new BasicWebPage();
LoginPage lp;
HomePage hp = new HomePage();
SearchResultsPage sp = new SearchResultsPage();
ProfilePage pr;
@BeforeMethod
public void beforeClass(Method method)
{
wd = bwp.getDriver();
lp = new LoginPage();
bwp.navigateUrl();
}
@Test
public void testScenario1()
{
pr = hp.clickProfile();
pr.clickMenuLink("My address");
pr.addAddressDetails("Arania", "Jain", "124 Vijay Nagar", "61259", "Illinois", "Illinois");
}
@Test
public void testScenario2()
{
String searchText = "MacBook";
String title;
hp.search(searchText);
title = sp.clickSearchedElement("3");
System.out.println("Title is " + title);
Assert.assertTrue(title.contains(searchText),"Either Text doesnot Match or Text is not present in the title");
}
@AfterMethod
public void afterMethod()
{
wd.close();
}
}
| 1,411 | 0.703756 | 0.69596 | 59 | 21.915255 | 21.518843 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.525424 | false | false |
15
|
abdcb007eb9faa966abe79d71af0981efad54fb5
| 31,516,470,081,408 |
441c13f0e40cfc939b67fb133b50841b22e63584
|
/UsersList/src/main/java/br/com/eiti/dao/UserDao.java
|
12cce6f0bf059c6add6469ee4b446079b41134aa
|
[] |
no_license
|
danillocesar/eitisolucoes
|
https://github.com/danillocesar/eitisolucoes
|
6720621285d2acd0230ba0668b256a390afba539
|
f68682714177a280acdcd5ab19229b3999b8974a
|
refs/heads/master
| 2021-04-12T04:33:28.643000 | 2018-03-19T16:19:16 | 2018-03-19T16:19:16 | 125,885,176 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package br.com.eiti.dao;
import java.util.List;
import br.com.eiti.entity.User;
public interface UserDao {
List<User> findAllBy(String username, String name, String email);
}
|
UTF-8
|
Java
| 179 |
java
|
UserDao.java
|
Java
|
[] | null |
[] |
package br.com.eiti.dao;
import java.util.List;
import br.com.eiti.entity.User;
public interface UserDao {
List<User> findAllBy(String username, String name, String email);
}
| 179 | 0.759777 | 0.759777 | 9 | 18.888889 | 20.663679 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false |
0
|
bb730e2fb352858a5b53e1dd1775c93a9cf8d7af
| 1,494,648,627,018 |
a0688fa7f917c60cb053ec9b27964a8ef49f74e6
|
/app/src/main/java/com/example/ahsanburney/recycler/StockContract.java
|
0eadd0b5744dbb9fa088c8cefe120a114ec071ec
|
[] |
no_license
|
rsaju8/StockWatch
|
https://github.com/rsaju8/StockWatch
|
c7476f42b6e10f7d99b9206b092cd9c829bdb680
|
e205382da31618d3b33599d260e790e5ec450854
|
refs/heads/master
| 2020-05-07T11:29:28.722000 | 2017-03-12T20:57:46 | 2017-03-12T20:57:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.ahsanburney.recycler;
/**
* @author Ahsan Burney
* @version 1.0
*/
public class StockContract {
public StockContract(){}
public static class stockEntry {
// DB Table Name
public static final String TABLE_NAME = "StockWatchTable";
public static final String company_name = "company_name";
public static final String company_symbol = "company_symbol";
public static final String l = "price";
public static final String c = "price_change";
public static final String cp = "percentage";
}
}
|
UTF-8
|
Java
| 588 |
java
|
StockContract.java
|
Java
|
[
{
"context": " com.example.ahsanburney.recycler;\n\n/**\n * @author Ahsan Burney\n * @version 1.0\n */\n\npublic class StockContract {",
"end": 70,
"score": 0.9998742341995239,
"start": 58,
"tag": "NAME",
"value": "Ahsan Burney"
}
] | null |
[] |
package com.example.ahsanburney.recycler;
/**
* @author <NAME>
* @version 1.0
*/
public class StockContract {
public StockContract(){}
public static class stockEntry {
// DB Table Name
public static final String TABLE_NAME = "StockWatchTable";
public static final String company_name = "company_name";
public static final String company_symbol = "company_symbol";
public static final String l = "price";
public static final String c = "price_change";
public static final String cp = "percentage";
}
}
| 582 | 0.651361 | 0.647959 | 27 | 20.777779 | 23.98971 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.259259 | false | false |
0
|
27786e94c001767a2d218fc6252325b9b322fd5d
| 584,115,577,447 |
f88f10c72a3f8fa572d58e4743ff8f175fdb65a4
|
/app/src/main/java/com/pvk/krishna/albumapp/utils/AlbumLoaderOptions.java
|
7b17e126572b210952605efc4c8d5c9383c3c2c4
|
[] |
no_license
|
VPVKrishna/AlbumApp
|
https://github.com/VPVKrishna/AlbumApp
|
7d678ce4cfb3822ee096c452c8b51c9ff7dde019
|
3dbeff0037ceb6a843de3d4c5bb713c58872112b
|
refs/heads/master
| 2021-01-10T15:21:45.814000 | 2019-10-29T19:27:11 | 2019-10-29T19:27:11 | 36,947,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.pvk.krishna.albumapp.utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.pvk.krishna.albumapp.R;
/**
* Created by Krishna on 31/05/2015.
*/
public interface AlbumLoaderOptions {
DisplayImageOptions OPTIONS = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.iv_default_image)
.showImageForEmptyUri(0).cacheInMemory(true)
.cacheOnDisk(true).delayBeforeLoading(100).build();
DisplayImageOptions OPTIONS_EMPTY = new DisplayImageOptions.Builder()
.showImageOnLoading(0)
.showImageForEmptyUri(0).cacheInMemory(true)
.cacheOnDisk(true).delayBeforeLoading(100).build();
int[] imageFrames = {R.drawable.frame_h_one, R.drawable.frame_h_two, R.drawable.frame_seven,
R.drawable.frame_two, R.drawable.aframe_one, R.drawable.aframe_two, R.drawable.aframe_three, R.drawable.aframe_four,
R.drawable.aframe_five, R.drawable.aframe_six};
String[] imageFrameNames = {"frame_h_one", "frame_h_two", "frame_seven", "frame_two", "aframe_one", "aframe_two",
"aframe_three", "aframe_four", "aframe_five", "aframe_six"};
}
|
UTF-8
|
Java
| 1,189 |
java
|
AlbumLoaderOptions.java
|
Java
|
[
{
"context": "ort com.pvk.krishna.albumapp.R;\n\n/**\n * Created by Krishna on 31/05/2015.\n */\npublic interface AlbumLoaderOp",
"end": 169,
"score": 0.9992241263389587,
"start": 162,
"tag": "NAME",
"value": "Krishna"
}
] | null |
[] |
package com.pvk.krishna.albumapp.utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.pvk.krishna.albumapp.R;
/**
* Created by Krishna on 31/05/2015.
*/
public interface AlbumLoaderOptions {
DisplayImageOptions OPTIONS = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.iv_default_image)
.showImageForEmptyUri(0).cacheInMemory(true)
.cacheOnDisk(true).delayBeforeLoading(100).build();
DisplayImageOptions OPTIONS_EMPTY = new DisplayImageOptions.Builder()
.showImageOnLoading(0)
.showImageForEmptyUri(0).cacheInMemory(true)
.cacheOnDisk(true).delayBeforeLoading(100).build();
int[] imageFrames = {R.drawable.frame_h_one, R.drawable.frame_h_two, R.drawable.frame_seven,
R.drawable.frame_two, R.drawable.aframe_one, R.drawable.aframe_two, R.drawable.aframe_three, R.drawable.aframe_four,
R.drawable.aframe_five, R.drawable.aframe_six};
String[] imageFrameNames = {"frame_h_one", "frame_h_two", "frame_seven", "frame_two", "aframe_one", "aframe_two",
"aframe_three", "aframe_four", "aframe_five", "aframe_six"};
}
| 1,189 | 0.694701 | 0.678722 | 26 | 44.73077 | 36.391628 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961538 | false | false |
0
|
7c820173d02c9628b3e9e1b9a6a2d34d369a01bc
| 4,380,866,648,437 |
bbf2523f02bd5935018e4e8878ca563dcf6936a5
|
/src/main/java/com/hit/carField/ModelField.java
|
6db6d5b88ac5d95a20decd96ae16e3b65b96d404
|
[] |
no_license
|
orIsc/CarRentalProject
|
https://github.com/orIsc/CarRentalProject
|
1d1f329406d28712044cf7037b9dbf35ba0206e4
|
68a9138b5384cbf9043c1abbae311f801b387916
|
refs/heads/master
| 2022-11-28T19:26:35.625000 | 2020-08-12T21:57:45 | 2020-08-12T21:57:45 | 287,122,699 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.hit.carField;
import com.hit.dm.Car;
public class ModelField implements CarField {
@Override
public String getField(Car car) {
return car.getModel();
}
}
|
UTF-8
|
Java
| 183 |
java
|
ModelField.java
|
Java
|
[] | null |
[] |
package com.hit.carField;
import com.hit.dm.Car;
public class ModelField implements CarField {
@Override
public String getField(Car car) {
return car.getModel();
}
}
| 183 | 0.699454 | 0.699454 | 12 | 14.25 | 15.248633 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false |
0
|
f390b23a64b0ec848ccff54fc20d025c9708f901
| 9,663,676,420,416 |
be432f777f0e39da063406f62ffe3c3844f0a433
|
/projects/TransportationAdmin/src/com/freshdirect/transadmin/web/editor/TrnFacilityPropertyEditor.java
|
311d1651661728ebdb14361246a5af97c9121d0d
|
[] |
no_license
|
AnthonyCC/sf-temp-ui
|
https://github.com/AnthonyCC/sf-temp-ui
|
29428ae4df2985582d96fd55a55c7e936ba4b0e4
|
0c95b810bc44bd2bd46d0c7e968e9cf4e17a943a
|
refs/heads/master
| 2021-10-19T09:51:17.279000 | 2019-02-15T23:00:09 | 2019-02-15T23:00:09 | 171,323,740 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.freshdirect.transadmin.web.editor;
import java.beans.PropertyEditorSupport;
import com.freshdirect.transadmin.model.TrnFacility;
import com.freshdirect.transadmin.model.TrnFacilityType;
public class TrnFacilityPropertyEditor extends PropertyEditorSupport {
public String getAsText() {
if (getValue() == null) {
return "";
}
TrnFacility p = (TrnFacility) getValue();
return "" + p.getFacilityId();
}
public void setAsText(String text) throws IllegalArgumentException {
if ("".equals(text)) {
setValue(null);
} else {
try {
TrnFacility view = new TrnFacility();
view.setFacilityId(text);
setValue(view);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
"Invalid id for TrnFacility: " + text);
}
}
}
}
|
UTF-8
|
Java
| 829 |
java
|
TrnFacilityPropertyEditor.java
|
Java
|
[] | null |
[] |
package com.freshdirect.transadmin.web.editor;
import java.beans.PropertyEditorSupport;
import com.freshdirect.transadmin.model.TrnFacility;
import com.freshdirect.transadmin.model.TrnFacilityType;
public class TrnFacilityPropertyEditor extends PropertyEditorSupport {
public String getAsText() {
if (getValue() == null) {
return "";
}
TrnFacility p = (TrnFacility) getValue();
return "" + p.getFacilityId();
}
public void setAsText(String text) throws IllegalArgumentException {
if ("".equals(text)) {
setValue(null);
} else {
try {
TrnFacility view = new TrnFacility();
view.setFacilityId(text);
setValue(view);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
"Invalid id for TrnFacility: " + text);
}
}
}
}
| 829 | 0.683957 | 0.683957 | 32 | 23.90625 | 21.318066 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.15625 | false | false |
0
|
e2b38499e2357df9ebfcae29386794212669b532
| 1,821,066,193,834 |
2b4ccb12b01b934519f7063964cf9da3d3cd2e1f
|
/sqlitewrapper/src/sqlitewrapper/CodeHandler.java
|
96badab1f495b37e2b646054b8f07945a4a6c4c0
|
[] |
no_license
|
xibyte/egis
|
https://github.com/xibyte/egis
|
c0123de83fa1ebcdc0e6bd115a5cb831ef1cafc2
|
debc6baa24ecf9d9e7baed140280e201b3016c9f
|
refs/heads/master
| 2016-09-05T14:51:45.045000 | 2012-01-20T18:33:51 | 2012-01-20T18:33:51 | 3,057,127 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package sqlitewrapper;
public class CodeHandler {
public static int checkForError(int code) throws DatabaseException {
if (code != Code.SQLITE_OK.code &&
code != Code.SQLITE_ROW.code &&
code != Code.SQLITE_DONE.code) {
throw new DatabaseException(code);
}
return code;
}
}
|
UTF-8
|
Java
| 296 |
java
|
CodeHandler.java
|
Java
|
[] | null |
[] |
package sqlitewrapper;
public class CodeHandler {
public static int checkForError(int code) throws DatabaseException {
if (code != Code.SQLITE_OK.code &&
code != Code.SQLITE_ROW.code &&
code != Code.SQLITE_DONE.code) {
throw new DatabaseException(code);
}
return code;
}
}
| 296 | 0.689189 | 0.689189 | 15 | 18.733334 | 19.861073 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.466667 | false | false |
0
|
a8f857109dab53f0e8f70ec4301ed62ef087179c
| 6,760,278,545,909 |
87ab720bf3a02d40afdec4d44e7b10a08f9f7c39
|
/app/src/main/java/io/github/billynyh/videofacetrack/ui/FaceDraweeView.java
|
e85ec2e09e1429fa00620fa8b5ef1e2fa9c18147
|
[] |
no_license
|
billynyh/android-vision-playground
|
https://github.com/billynyh/android-vision-playground
|
8e107c838c52cafd51d1c5b7d41223952cf3bbb3
|
f3f5bef380e37278eda5cb08c83bdf259229c50e
|
refs/heads/master
| 2021-01-01T04:45:41.547000 | 2016-05-15T23:33:41 | 2016-05-15T23:33:41 | 58,890,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package io.github.billynyh.videofacetrack.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
import io.github.billynyh.videofacetrack.vision.ScaledFaceData;
/**
* Created by billy on 15/05/16.
*/
public class FaceDraweeView extends SimpleDraweeView {
private List<ScaledFaceData> mList;
private Paint mFacePaint;
public FaceDraweeView(Context context) {
super(context);
init();
}
public FaceDraweeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FaceDraweeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mFacePaint = new Paint();
mFacePaint.setAntiAlias(true);
mFacePaint.setStyle(Paint.Style.STROKE);
mFacePaint.setColor(0xffffff66);
}
public void setFaces(List<ScaledFaceData> list) {
mList = list;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mList != null) {
int w = getWidth();
int h = getHeight();
for (ScaledFaceData face : mList) {
canvas.drawCircle(face.x * w, face.y * h, face.r * w, mFacePaint);
}
}
}
}
|
UTF-8
|
Java
| 1,366 |
java
|
FaceDraweeView.java
|
Java
|
[
{
"context": "package io.github.billynyh.videofacetrack.ui;\n\nimport android.content.Contex",
"end": 26,
"score": 0.9990010261535645,
"start": 18,
"tag": "USERNAME",
"value": "billynyh"
},
{
"context": "eeView;\n\nimport java.util.List;\n\nimport io.github.billynyh.videofacetrack.vision.ScaledFaceData;\n\n/**\n * Cre",
"end": 277,
"score": 0.9987283945083618,
"start": 269,
"tag": "USERNAME",
"value": "billynyh"
},
{
"context": "acetrack.vision.ScaledFaceData;\n\n/**\n * Created by billy on 15/05/16.\n */\npublic class FaceDraweeView exte",
"end": 340,
"score": 0.999602198600769,
"start": 335,
"tag": "USERNAME",
"value": "billy"
}
] | null |
[] |
package io.github.billynyh.videofacetrack.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
import io.github.billynyh.videofacetrack.vision.ScaledFaceData;
/**
* Created by billy on 15/05/16.
*/
public class FaceDraweeView extends SimpleDraweeView {
private List<ScaledFaceData> mList;
private Paint mFacePaint;
public FaceDraweeView(Context context) {
super(context);
init();
}
public FaceDraweeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FaceDraweeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mFacePaint = new Paint();
mFacePaint.setAntiAlias(true);
mFacePaint.setStyle(Paint.Style.STROKE);
mFacePaint.setColor(0xffffff66);
}
public void setFaces(List<ScaledFaceData> list) {
mList = list;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mList != null) {
int w = getWidth();
int h = getHeight();
for (ScaledFaceData face : mList) {
canvas.drawCircle(face.x * w, face.y * h, face.r * w, mFacePaint);
}
}
}
}
| 1,366 | 0.692533 | 0.685944 | 60 | 21.766666 | 20.451868 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false |
0
|
092e860a3eb0716a2fa5f564f46c66a98876818b
| 4,870,492,955,941 |
bda61ef1790fe73ebcb393f24a023a309159c37a
|
/src/main/java/com/fancyliu/learningspringboot/dao/UserRepository.java
|
e54924c5068e3b960a714b0d5e01c2b205bab23f
|
[] |
no_license
|
flanliulf/learningspringboot-web-jwt
|
https://github.com/flanliulf/learningspringboot-web-jwt
|
877af1cdb42d3870bc25d35513e44c0f895f1fe9
|
e31dad0151de69c179fe6d63d9eb6d27c31daac4
|
refs/heads/master
| 2022-06-29T06:59:40.996000 | 2019-11-22T08:14:38 | 2019-11-22T08:14:38 | 223,355,263 | 0 | 0 | null | false | 2022-06-21T02:17:34 | 2019-11-22T08:13:18 | 2019-11-22T08:15:10 | 2022-06-21T02:17:31 | 18 | 0 | 0 | 2 |
Java
| false | false |
package com.fancyliu.learningspringboot.dao;
import com.fancyliu.learningspringboot.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 类描述:
* 用户 Repository 接口
*
* @author : Liu Fan
* @date : 2019/11/22 14:23
*/
public interface UserRepository extends JpaRepository<User, Long> {
}
|
UTF-8
|
Java
| 332 |
java
|
UserRepository.java
|
Java
|
[
{
"context": ";\n\n/**\n * 类描述:\n * 用户 Repository 接口\n *\n * @author : Liu Fan\n * @date : 2019/11/22 14:23\n */\npublic interface ",
"end": 215,
"score": 0.9997989535331726,
"start": 208,
"tag": "NAME",
"value": "Liu Fan"
}
] | null |
[] |
package com.fancyliu.learningspringboot.dao;
import com.fancyliu.learningspringboot.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 类描述:
* 用户 Repository 接口
*
* @author : <NAME>
* @date : 2019/11/22 14:23
*/
public interface UserRepository extends JpaRepository<User, Long> {
}
| 331 | 0.751572 | 0.713836 | 14 | 21.714285 | 23.309803 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
0
|
bd6b9fe03faeda4c26d3fa8d1b1fc33a156a050f
| 28,535,762,747,660 |
8a133a33bb33e757352f625821f766a46e26172d
|
/opap/src/main/java/com/anakiou/opap/model/kino/KinoDraws.java
|
1e724f0da4ecf445a11670ada03da29e1868e46e
|
[] |
no_license
|
anakiou/opap
|
https://github.com/anakiou/opap
|
d845aab8061b1cfc7047c4975dc15ba2dae1485b
|
50b899360a398b912662ec1bbfe5cb2888f3388a
|
refs/heads/master
| 2021-01-10T14:30:58.860000 | 2015-09-24T21:11:23 | 2015-09-24T21:11:23 | 43,068,222 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.anakiou.opap.model.kino;
import com.anakiou.opap.model.AbstractGameDraws;
public final class KinoDraws extends AbstractGameDraws<KinoDraws> {
}
|
UTF-8
|
Java
| 166 |
java
|
KinoDraws.java
|
Java
|
[] | null |
[] |
package com.anakiou.opap.model.kino;
import com.anakiou.opap.model.AbstractGameDraws;
public final class KinoDraws extends AbstractGameDraws<KinoDraws> {
}
| 166 | 0.783133 | 0.783133 | 7 | 21.714285 | 26.157295 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false |
0
|
e4e2d9fa88c67b0a10fe16c5955cf7d2799b0a47
| 16,801,912,089,958 |
5417ea09478690a4945c7d98971beab7fbc865c9
|
/CMSContainer_Modules/community/src/java/com/finalist/cmsc/services/community/CommunityServiceImpl.java
|
681e16a4f1d432ab878b554cfe77341f29014d2b
|
[] |
no_license
|
mmbase/CMSContainer
|
https://github.com/mmbase/CMSContainer
|
b20f3ef7b1f86cc4c2907c58d166f59237513b35
|
e63817408e060d4cff1a99cdeff23a8f953f8892
|
refs/heads/master
| 2023-03-11T07:18:24.184000 | 2022-07-08T21:46:25 | 2022-07-08T21:46:25 | 201,436,616 | 1 | 0 | null | false | 2023-02-22T08:03:48 | 2019-08-09T09:29:32 | 2022-07-08T09:19:58 | 2023-02-22T08:03:47 | 17,204 | 0 | 0 | 7 |
Java
| false | false |
/*
*
* This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source
* Initiative.
*
* The license (Mozilla version 1.0) can be read at the MMBase site. See http://www.MMBase.org/license
*
*/
package com.finalist.cmsc.services.community;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.User;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.finalist.cmsc.mmbase.EmailUtil;
import com.finalist.cmsc.services.Properties;
import com.finalist.cmsc.services.community.person.Person;
import com.finalist.cmsc.services.community.person.PersonService;
import com.finalist.cmsc.services.community.preferences.PreferenceService;
import com.finalist.cmsc.services.community.security.Authentication;
import com.finalist.cmsc.services.community.security.AuthenticationService;
import com.finalist.cmsc.util.NameUtil;
/**
* CommunityServiceImpl, a CMSc service class.
*
* @author Remco Bos
*/
public class CommunityServiceImpl extends CommunityService {
private static Log log = LogFactory.getLog(CommunityServiceImpl.class);
private AuthenticationManager authenticationManager;
private PreferenceService preferenceService;
private PersonService personService;
private AuthenticationService authenticationService;
@Override
protected void init(ServletConfig config, Properties properties) throws Exception {
/* Some Spring magic. Sets the AuthenticationManager and PreferenceService */
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
ac.getAutowireCapableBeanFactory().autowireBeanProperties(this, Autowire.BY_NAME.value(), false);
}
@Override
public void login(String userName, String password) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
try {
org.acegisecurity.Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (AuthenticationException ae) {
SecurityContextHolder.clearContext();
log.debug(String.format("Authentication attempt failed for user %s", userName), ae);
}
}
@Override
public void logout() {
SecurityContextHolder.clearContext();
}
@Override
public boolean isAuthenticated() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return (authentication != null) && authentication.isAuthenticated();
}
@Override
public String getAuthenticatedUser() {
User principal = getPrincipal();
return principal != null ? principal.getUsername() : null;
}
@Override
public List < String > getAuthorities() {
List < String > authorities = new ArrayList < String >();
User principal = getPrincipal();
if (principal != null) {
GrantedAuthority[] grantedAuthorities = principal.getAuthorities();
for (GrantedAuthority grantedAuthoritie : grantedAuthorities) {
authorities.add(grantedAuthoritie.getAuthority());
}
}
return authorities;
}
@Override
public boolean hasAuthority(String authority) {
User principal = getPrincipal();
if (principal != null) {
GrantedAuthority[] grantedAuthorities = principal.getAuthorities();
for (GrantedAuthority grantedAuthoritie : grantedAuthorities) {
if (grantedAuthoritie.getAuthority().equals(authority)) {
return true;
}
}
}
return false;
}
private User getPrincipal() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return authentication != null ? (User) authentication.getPrincipal() : null;
}
public Map < Long , Map < String , String > > getPreferencesByModule(String module) {
return preferenceService.getPreferencesByModule(module);
}
public Map < String , Map < String , String > > getPreferencesByUserId(String userId) {
return preferenceService.getPreferencesByUserId(userId);
}
@Override
public List < String > getPreferenceValues(String module, String userId, String key) {
return preferenceService.getPreferenceValues(module, userId, key);
}
public void createPreference(String module, String userId, String key, String value) {
preferenceService.createPreference(module, userId, key, value);
}
public void deletePreference(String module, String userId, String key, String value) {
preferenceService.deletePreference(module, userId, key, value);
}
// TODO: replace the previous methods by methods who accept the following
// properties!
/**
* @deprecated please try to use another service
*/
@Override
public void createPreference(String module, String userId, String key, List < String > values) {
for (String value : values) {
preferenceService.createPreference(module, userId, key, value);
}
}
/**
* @deprecated please try to use another service
*/
@Override
public Map < String , Map < String , List < String > > > getPreferences(String module, String userId, String key,
String value) {
return null;
}
/**
* @deprecated please try to use another service
*/
@Override
public Map < String , Map < String , String > > getUserProperty(String userId) {
// return preferenceService.getPreferencesByUserId(userId);
return null;
}
/** {@inheritDoc} */
@Override
boolean sendPassword(String email, String senderName, String senderEmail, String emailSubject, String emailBody) {
boolean authenticationFound = false;
if (StringUtils.isEmpty(email)) {
throw new IllegalArgumentException("Username not found.");
}
if (StringUtils.isEmpty(emailSubject)) {
emailSubject = "<email subject is missing>";
}
if (StringUtils.isEmpty(emailBody)) {
emailBody = "<email body is missing>";
}
String name = "";
StringBuilder body = new StringBuilder(emailBody);
Person example = new Person();
example.setEmail(email);
// Retrieve a list of persons that match this example
List < Person > persons = personService.getPersons(example);
for (Person person : persons) {
Authentication authentication = authenticationService.getAuthenticationById(person.getAuthenticationId());
if (authentication != null) {
if ("".equals(name)) {
name = NameUtil.getFullName(person.getFirstName(), person.getInfix(), person.getLastName());
}
body.append("\n---\n");
body.append("Gebruikersnaam: ").append(authentication.getUserId());
body.append("\n");
body.append("Wachtwoord : ").append(authentication.getPassword());
authenticationFound = true;
}
}
if (authenticationFound) {
EmailUtil.send(null, name, email, senderName, senderEmail, emailSubject, body.toString());
}
return authenticationFound;
}
/**
* @deprecated please try to use another service
*/
@Override
public void removePreferences(String module, String userId, String key) {
List < String > valueList = preferenceService.getPreferenceValues(module, userId, key);
for (String value : valueList) {
preferenceService.deletePreference(module, userId, key, value);
}
}
@Required
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Required
public void setPreferenceService(PreferenceService preferenceService) {
this.preferenceService = preferenceService;
}
@Required
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@Required
public void setAuthenticationService(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public Principal getUserPrincipal() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return authentication;
}
}
|
UTF-8
|
Java
| 9,357 |
java
|
CommunityServiceImpl.java
|
Java
|
[
{
"context": "yServiceImpl, a CMSc service class.\n * \n * @author Remco Bos\n */\npublic class CommunityServiceImpl extends Com",
"end": 1736,
"score": 0.9998658299446106,
"start": 1727,
"tag": "NAME",
"value": "Remco Bos"
}
] | null |
[] |
/*
*
* This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source
* Initiative.
*
* The license (Mozilla version 1.0) can be read at the MMBase site. See http://www.MMBase.org/license
*
*/
package com.finalist.cmsc.services.community;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.User;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.finalist.cmsc.mmbase.EmailUtil;
import com.finalist.cmsc.services.Properties;
import com.finalist.cmsc.services.community.person.Person;
import com.finalist.cmsc.services.community.person.PersonService;
import com.finalist.cmsc.services.community.preferences.PreferenceService;
import com.finalist.cmsc.services.community.security.Authentication;
import com.finalist.cmsc.services.community.security.AuthenticationService;
import com.finalist.cmsc.util.NameUtil;
/**
* CommunityServiceImpl, a CMSc service class.
*
* @author <NAME>
*/
public class CommunityServiceImpl extends CommunityService {
private static Log log = LogFactory.getLog(CommunityServiceImpl.class);
private AuthenticationManager authenticationManager;
private PreferenceService preferenceService;
private PersonService personService;
private AuthenticationService authenticationService;
@Override
protected void init(ServletConfig config, Properties properties) throws Exception {
/* Some Spring magic. Sets the AuthenticationManager and PreferenceService */
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
ac.getAutowireCapableBeanFactory().autowireBeanProperties(this, Autowire.BY_NAME.value(), false);
}
@Override
public void login(String userName, String password) {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
try {
org.acegisecurity.Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (AuthenticationException ae) {
SecurityContextHolder.clearContext();
log.debug(String.format("Authentication attempt failed for user %s", userName), ae);
}
}
@Override
public void logout() {
SecurityContextHolder.clearContext();
}
@Override
public boolean isAuthenticated() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return (authentication != null) && authentication.isAuthenticated();
}
@Override
public String getAuthenticatedUser() {
User principal = getPrincipal();
return principal != null ? principal.getUsername() : null;
}
@Override
public List < String > getAuthorities() {
List < String > authorities = new ArrayList < String >();
User principal = getPrincipal();
if (principal != null) {
GrantedAuthority[] grantedAuthorities = principal.getAuthorities();
for (GrantedAuthority grantedAuthoritie : grantedAuthorities) {
authorities.add(grantedAuthoritie.getAuthority());
}
}
return authorities;
}
@Override
public boolean hasAuthority(String authority) {
User principal = getPrincipal();
if (principal != null) {
GrantedAuthority[] grantedAuthorities = principal.getAuthorities();
for (GrantedAuthority grantedAuthoritie : grantedAuthorities) {
if (grantedAuthoritie.getAuthority().equals(authority)) {
return true;
}
}
}
return false;
}
private User getPrincipal() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return authentication != null ? (User) authentication.getPrincipal() : null;
}
public Map < Long , Map < String , String > > getPreferencesByModule(String module) {
return preferenceService.getPreferencesByModule(module);
}
public Map < String , Map < String , String > > getPreferencesByUserId(String userId) {
return preferenceService.getPreferencesByUserId(userId);
}
@Override
public List < String > getPreferenceValues(String module, String userId, String key) {
return preferenceService.getPreferenceValues(module, userId, key);
}
public void createPreference(String module, String userId, String key, String value) {
preferenceService.createPreference(module, userId, key, value);
}
public void deletePreference(String module, String userId, String key, String value) {
preferenceService.deletePreference(module, userId, key, value);
}
// TODO: replace the previous methods by methods who accept the following
// properties!
/**
* @deprecated please try to use another service
*/
@Override
public void createPreference(String module, String userId, String key, List < String > values) {
for (String value : values) {
preferenceService.createPreference(module, userId, key, value);
}
}
/**
* @deprecated please try to use another service
*/
@Override
public Map < String , Map < String , List < String > > > getPreferences(String module, String userId, String key,
String value) {
return null;
}
/**
* @deprecated please try to use another service
*/
@Override
public Map < String , Map < String , String > > getUserProperty(String userId) {
// return preferenceService.getPreferencesByUserId(userId);
return null;
}
/** {@inheritDoc} */
@Override
boolean sendPassword(String email, String senderName, String senderEmail, String emailSubject, String emailBody) {
boolean authenticationFound = false;
if (StringUtils.isEmpty(email)) {
throw new IllegalArgumentException("Username not found.");
}
if (StringUtils.isEmpty(emailSubject)) {
emailSubject = "<email subject is missing>";
}
if (StringUtils.isEmpty(emailBody)) {
emailBody = "<email body is missing>";
}
String name = "";
StringBuilder body = new StringBuilder(emailBody);
Person example = new Person();
example.setEmail(email);
// Retrieve a list of persons that match this example
List < Person > persons = personService.getPersons(example);
for (Person person : persons) {
Authentication authentication = authenticationService.getAuthenticationById(person.getAuthenticationId());
if (authentication != null) {
if ("".equals(name)) {
name = NameUtil.getFullName(person.getFirstName(), person.getInfix(), person.getLastName());
}
body.append("\n---\n");
body.append("Gebruikersnaam: ").append(authentication.getUserId());
body.append("\n");
body.append("Wachtwoord : ").append(authentication.getPassword());
authenticationFound = true;
}
}
if (authenticationFound) {
EmailUtil.send(null, name, email, senderName, senderEmail, emailSubject, body.toString());
}
return authenticationFound;
}
/**
* @deprecated please try to use another service
*/
@Override
public void removePreferences(String module, String userId, String key) {
List < String > valueList = preferenceService.getPreferenceValues(module, userId, key);
for (String value : valueList) {
preferenceService.deletePreference(module, userId, key, value);
}
}
@Required
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Required
public void setPreferenceService(PreferenceService preferenceService) {
this.preferenceService = preferenceService;
}
@Required
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@Required
public void setAuthenticationService(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public Principal getUserPrincipal() {
SecurityContext context = SecurityContextHolder.getContext();
org.acegisecurity.Authentication authentication = context.getAuthentication();
return authentication;
}
}
| 9,354 | 0.715507 | 0.715293 | 262 | 34.713741 | 32.45499 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.587786 | false | false |
0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.