blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ba6e65ba523f92807fca36d428f6129a5b99d7bc | 27,865,747,842,797 | 450a568d71d029731011a5e9735164651bc4e213 | /src/main/java/biz/models/Promo.java | bdd52cae60a097ec152a320060763098f6848558 | [] | no_license | Bizon4ik/pitstop | https://github.com/Bizon4ik/pitstop | f2cf9b44328a0f70daab9bb3c737519f810bc138 | dcba4fe48952084a261a3bf998f485132949f8b6 | refs/heads/master | 2018-12-31T23:35:07.072000 | 2018-12-27T23:19:59 | 2018-12-27T23:19:59 | 63,637,472 | 4 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package biz.models;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Set;
@Entity
@Table(name = "promo")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Promo extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="name", nullable = false, length = 100)
private String name;
@Column(name = "start_date", nullable = false)
private LocalDateTime startDate;
@Column(name = "end_date")
private LocalDateTime endDate;
@Column(name = "max_exp_days_for_orders")
private Integer maxExpirationDaysForOrders;
@Column(name = "max_apply")
private Integer maxApply;
@Column(name = "total_discount")
private Integer totalDiscount;
@Column(name = "is_allow_for_legal")
private Boolean isAvailableForLegal;
@Column(name = "min_order_cost")
private Integer minOrderCost;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "promo_carwash",
joinColumns = @JoinColumn(name = "promo_id"),
inverseJoinColumns = @JoinColumn(name = "carwash_id"))
private Set<CarWash> carWashes;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "promo_rule_relation",
joinColumns = @JoinColumn(name = "promo_id"),
inverseJoinColumns = @JoinColumn(name = "rule_id"))
private Set<PromoRule> promoRules;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id", nullable = false)
private Owner owner;
@Override
public String toString() {
return "Promo{" +
"id=" + id +
", name='" + name + '\'' +
", startDate=" + startDate +
", endDate=" + endDate +
", maxExpirationDaysForOrders=" + maxExpirationDaysForOrders +
", maxApply=" + maxApply +
", totalDiscount=" + totalDiscount +
", carWashes=" + carWashes +
", promoRules=" + promoRules +
", owner=" + owner +
'}';
}
}
| UTF-8 | Java | 2,198 | java | Promo.java | Java | [] | null | [] | package biz.models;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Set;
@Entity
@Table(name = "promo")
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Promo extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="name", nullable = false, length = 100)
private String name;
@Column(name = "start_date", nullable = false)
private LocalDateTime startDate;
@Column(name = "end_date")
private LocalDateTime endDate;
@Column(name = "max_exp_days_for_orders")
private Integer maxExpirationDaysForOrders;
@Column(name = "max_apply")
private Integer maxApply;
@Column(name = "total_discount")
private Integer totalDiscount;
@Column(name = "is_allow_for_legal")
private Boolean isAvailableForLegal;
@Column(name = "min_order_cost")
private Integer minOrderCost;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "promo_carwash",
joinColumns = @JoinColumn(name = "promo_id"),
inverseJoinColumns = @JoinColumn(name = "carwash_id"))
private Set<CarWash> carWashes;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "promo_rule_relation",
joinColumns = @JoinColumn(name = "promo_id"),
inverseJoinColumns = @JoinColumn(name = "rule_id"))
private Set<PromoRule> promoRules;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id", nullable = false)
private Owner owner;
@Override
public String toString() {
return "Promo{" +
"id=" + id +
", name='" + name + '\'' +
", startDate=" + startDate +
", endDate=" + endDate +
", maxExpirationDaysForOrders=" + maxExpirationDaysForOrders +
", maxApply=" + maxApply +
", totalDiscount=" + totalDiscount +
", carWashes=" + carWashes +
", promoRules=" + promoRules +
", owner=" + owner +
'}';
}
}
| 2,198 | 0.611465 | 0.6101 | 77 | 27.545454 | 20.833006 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480519 | false | false | 4 |
2888fbdd427cc67ee333ecf1004562a231658b10 | 27,754,078,686,171 | 995c1686f1c2dabd4d4b8deac2a66ad97849ed4a | /src/main/java/com/huivip/service/impl/ClassBZManagerImpl.java | fcdcbb5a8e5b3de55bc238ac2f74904cc6c52fe9 | [] | no_license | laihui0207/jwsystem | https://github.com/laihui0207/jwsystem | 17477a16bae002bb829ae8300d015e03a8329993 | e4e118718fd90106a97e8be9d5dea7c15da58b6a | refs/heads/master | 2019-01-01T09:28:12.147000 | 2017-04-01T02:15:03 | 2017-04-01T02:15:03 | 8,537,377 | 0 | 0 | null | false | 2017-04-01T02:11:56 | 2013-03-03T14:34:32 | 2014-09-04T17:11:54 | 2017-04-01T02:11:10 | 83,616 | 0 | 0 | 1 | JavaScript | null | null | package com.huivip.service.impl;
import com.huivip.dao.ClassBZDao;
import com.huivip.model.ClassBZ;
import com.huivip.service.ClassBZManager;
import com.huivip.util.cache.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.jws.WebService;
import java.util.List;
@Service("classBZManager")
@WebService(serviceName = "ClassBZService", endpointInterface = "com.huivip.service.ClassBZManager")
public class ClassBZManagerImpl extends GenericManagerImpl<ClassBZ, Long> implements ClassBZManager {
ClassBZDao classBZDao;
@Autowired
public ClassBZManagerImpl(ClassBZDao classBZDao) {
super(classBZDao);
this.classBZDao = classBZDao;
}
@Override
public ClassBZ getClassBZByName(String name) {
ClassBZ classBZ= (ClassBZ) CacheUtil.get(ClassBZ.CACHEKEY_PREFIX + name);
if(classBZ==null){
classBZ=classBZDao.getClassBZByName(name);
CacheUtil.put(ClassBZ.CACHEKEY_PREFIX + name,classBZ);
}
return classBZ; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ClassBZ get(Long id) {
ClassBZ classBZ= (ClassBZ) CacheUtil.get(ClassBZ.CACHEKEY_PREFIX + id);
if(classBZ==null){
classBZ=super.get(id);
if(classBZ !=null)
CacheUtil.put(ClassBZ.CACHEKEY_PREFIX + id, classBZ);
}
return classBZ;
}
@Override
public ClassBZ save(ClassBZ object) {
ClassBZ classBZ=super.save(object);
return classBZ; //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public List<ClassBZ> getAll() {
List<ClassBZ> list= (List<ClassBZ>) CacheUtil.get(ClassBZ.CACHEKEYS_PREFIX + "All");
if(list==null){
list=super.getAll();
CacheUtil.put(ClassBZ.CACHEKEYS_PREFIX + "All", list);
}
return list;
}
@Override
public void remove(Long id) {
super.remove(id); //To change body of overridden methods use File | Settings | File Templates.
}
} | UTF-8 | Java | 2,175 | java | ClassBZManagerImpl.java | Java | [] | null | [] | package com.huivip.service.impl;
import com.huivip.dao.ClassBZDao;
import com.huivip.model.ClassBZ;
import com.huivip.service.ClassBZManager;
import com.huivip.util.cache.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.jws.WebService;
import java.util.List;
@Service("classBZManager")
@WebService(serviceName = "ClassBZService", endpointInterface = "com.huivip.service.ClassBZManager")
public class ClassBZManagerImpl extends GenericManagerImpl<ClassBZ, Long> implements ClassBZManager {
ClassBZDao classBZDao;
@Autowired
public ClassBZManagerImpl(ClassBZDao classBZDao) {
super(classBZDao);
this.classBZDao = classBZDao;
}
@Override
public ClassBZ getClassBZByName(String name) {
ClassBZ classBZ= (ClassBZ) CacheUtil.get(ClassBZ.CACHEKEY_PREFIX + name);
if(classBZ==null){
classBZ=classBZDao.getClassBZByName(name);
CacheUtil.put(ClassBZ.CACHEKEY_PREFIX + name,classBZ);
}
return classBZ; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ClassBZ get(Long id) {
ClassBZ classBZ= (ClassBZ) CacheUtil.get(ClassBZ.CACHEKEY_PREFIX + id);
if(classBZ==null){
classBZ=super.get(id);
if(classBZ !=null)
CacheUtil.put(ClassBZ.CACHEKEY_PREFIX + id, classBZ);
}
return classBZ;
}
@Override
public ClassBZ save(ClassBZ object) {
ClassBZ classBZ=super.save(object);
return classBZ; //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public List<ClassBZ> getAll() {
List<ClassBZ> list= (List<ClassBZ>) CacheUtil.get(ClassBZ.CACHEKEYS_PREFIX + "All");
if(list==null){
list=super.getAll();
CacheUtil.put(ClassBZ.CACHEKEYS_PREFIX + "All", list);
}
return list;
}
@Override
public void remove(Long id) {
super.remove(id); //To change body of overridden methods use File | Settings | File Templates.
}
} | 2,175 | 0.671264 | 0.671264 | 65 | 32.476925 | 29.968758 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584615 | false | false | 4 |
d9e2ba0c11c8df9a98095fe97afadba80101b91f | 19,885,698,635,466 | 5d5cbda99b9456f9f93995c7d8263b75dca8bac9 | /app/src/main/java/de/vanappsteer/windowalarmconfig/presenter/DeviceConfigPresenter.java | 35fb8c9e8143e19264add7a608a76bdd0835ec8a | [] | no_license | HendrikVE/WindowAlarmConfigApp | https://github.com/HendrikVE/WindowAlarmConfigApp | 66a3b314380cbc73a8c18a5bfc549071ff41adc6 | 70d73c7790ea80e5d8782fbfaa8285734ec940ec | refs/heads/master | 2020-04-28T04:53:44.971000 | 2020-02-22T12:56:46 | 2020-02-22T12:56:46 | 174,998,683 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.vanappsteer.windowalarmconfig.presenter;
import de.vanappsteer.windowalarmconfig.interfaces.ConfigController;
import de.vanappsteer.windowalarmconfig.interfaces.DeviceConfigView;
import de.vanappsteer.windowalarmconfig.models.DeviceConfigModel;
public class DeviceConfigPresenter extends ConfigController<DeviceConfigModel> {
private DeviceConfigModel mModel;
private DeviceConfigView mView;
public DeviceConfigPresenter(DeviceConfigModel model, DeviceConfigView view) {
mModel = model;
mView = view;
}
@Override
public void updateView() {
mView.updateDeviceRoom(mModel.getDeviceRoom());
mView.updateDeviceId(mModel.getDeviceId());
}
@Override
public DeviceConfigModel getModel() {
return mModel;
}
/* BEGIN GETTER */
public String getDeviceRoom() {
return mModel.getDeviceRoom();
}
public String getDeviceId() {
return mModel.getDeviceId();
}
/* END GETTER */
/* BEGIN SETTER */
public void setDeviceRoom(String room) {
mModel.setDeviceRoom(room);
}
public void setDeviceId(String id) {
mModel.setDeviceId(id);
}
/* END SETTER */
}
| UTF-8 | Java | 1,216 | java | DeviceConfigPresenter.java | Java | [] | null | [] | package de.vanappsteer.windowalarmconfig.presenter;
import de.vanappsteer.windowalarmconfig.interfaces.ConfigController;
import de.vanappsteer.windowalarmconfig.interfaces.DeviceConfigView;
import de.vanappsteer.windowalarmconfig.models.DeviceConfigModel;
public class DeviceConfigPresenter extends ConfigController<DeviceConfigModel> {
private DeviceConfigModel mModel;
private DeviceConfigView mView;
public DeviceConfigPresenter(DeviceConfigModel model, DeviceConfigView view) {
mModel = model;
mView = view;
}
@Override
public void updateView() {
mView.updateDeviceRoom(mModel.getDeviceRoom());
mView.updateDeviceId(mModel.getDeviceId());
}
@Override
public DeviceConfigModel getModel() {
return mModel;
}
/* BEGIN GETTER */
public String getDeviceRoom() {
return mModel.getDeviceRoom();
}
public String getDeviceId() {
return mModel.getDeviceId();
}
/* END GETTER */
/* BEGIN SETTER */
public void setDeviceRoom(String room) {
mModel.setDeviceRoom(room);
}
public void setDeviceId(String id) {
mModel.setDeviceId(id);
}
/* END SETTER */
}
| 1,216 | 0.693257 | 0.693257 | 49 | 23.816326 | 23.350632 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.326531 | false | false | 4 |
16b0cf372fbc03b8a9b198413b844376c5ed8a88 | 4,501,125,763,601 | 2a668eee3ce414a0ee299bd6d3bbd9236e6baf7d | /src/chapter_two/linked_lists/LinkedListRemoveDupsBookSolution.java | 90d74ca8e9d559256d4f8f839585482eb1c37200 | [] | no_license | simonaOancea/cracking-the-interview-code-solutions | https://github.com/simonaOancea/cracking-the-interview-code-solutions | ddf24472161516b136b163703521bdcd69ac1135 | d4c6ee6f2054b4d5b85d581e0fe70091922ec5ba | refs/heads/master | 2023-02-13T00:43:12.196000 | 2021-01-11T12:07:03 | 2021-01-11T12:07:03 | 268,231,735 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package chapter_two.linked_lists;
import java.util.Hashtable;
/**
* Date 27/05/20.
* @Author Cracking the interview code
*
* 2.1 Write code to remove duplicates from an unsorted linked list.
* FOLLOW UP
* How would you solve this problem if a temporary buffer was not allowed?
*
* Solution: we iterate through the linked list, adding each element to a hash table.
* When we discover a duplicate element, we remove the element and continue iterating.
* We can do this all in one pass since we are using a linked list.
*/
public class LinkedListRemoveDupsBookSolution {
public static void main(String[] args) {
LinkedListRemoveDupsBookSolution list = new LinkedListRemoveDupsBookSolution();
list.head = new Node(10);
list.head.next = new Node(12);
list.head.next.next = new Node(11);
list.head.next.next.next = new Node(11);
list.head.next.next.next.next = new Node(12);
list.head.next.next.next.next.next = new Node(11);
list.head.next.next.next.next.next.next = new Node(10);
System.out.println("Linked list before removing duplicates : \n");
list.printList(head);
list.deleteDups(list.head);
System.out.println("");
System.out.println("Linked list after removing duplicates : \n");
list.printList(head);
}
static Node head;
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public static void deleteDups(Node n) {
Hashtable table = new Hashtable();
Node previous = null;
while (n != null) {
if(table.containsKey(n.data)) {
previous.next = n.next;
} else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
public void printList(Node node) {
while (node != null) {
System.out.println(node.data + " ");
node = node.next;
}
}
}
| UTF-8 | Java | 2,056 | java | LinkedListRemoveDupsBookSolution.java | Java | [] | null | [] | package chapter_two.linked_lists;
import java.util.Hashtable;
/**
* Date 27/05/20.
* @Author Cracking the interview code
*
* 2.1 Write code to remove duplicates from an unsorted linked list.
* FOLLOW UP
* How would you solve this problem if a temporary buffer was not allowed?
*
* Solution: we iterate through the linked list, adding each element to a hash table.
* When we discover a duplicate element, we remove the element and continue iterating.
* We can do this all in one pass since we are using a linked list.
*/
public class LinkedListRemoveDupsBookSolution {
public static void main(String[] args) {
LinkedListRemoveDupsBookSolution list = new LinkedListRemoveDupsBookSolution();
list.head = new Node(10);
list.head.next = new Node(12);
list.head.next.next = new Node(11);
list.head.next.next.next = new Node(11);
list.head.next.next.next.next = new Node(12);
list.head.next.next.next.next.next = new Node(11);
list.head.next.next.next.next.next.next = new Node(10);
System.out.println("Linked list before removing duplicates : \n");
list.printList(head);
list.deleteDups(list.head);
System.out.println("");
System.out.println("Linked list after removing duplicates : \n");
list.printList(head);
}
static Node head;
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public static void deleteDups(Node n) {
Hashtable table = new Hashtable();
Node previous = null;
while (n != null) {
if(table.containsKey(n.data)) {
previous.next = n.next;
} else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
public void printList(Node node) {
while (node != null) {
System.out.println(node.data + " ");
node = node.next;
}
}
}
| 2,056 | 0.594358 | 0.583658 | 74 | 26.783783 | 24.486771 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418919 | false | false | 4 |
50bf75a20ef7b419ff523ab9d74efa6f7793f173 | 12,962,211,325,955 | af48992d10e4839e6b9b4a52dabee952fe7f89af | /src/sistemaacademico/ValidaCpf.java | 414f9cc99f59cd1a7236e656783d0c98eaa98c5a | [] | no_license | rafaeldziderio/Sistema-Academico | https://github.com/rafaeldziderio/Sistema-Academico | 1932f3f1d053cf1a0c4af8d25df3526d638db577 | 2c6af3438bb27213129b0db3fe74eb5307070b63 | refs/heads/master | 2020-04-09T09:18:15.023000 | 2018-12-18T15:32:45 | 2018-12-18T15:32:45 | 160,228,418 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sistemaacademico;
import java.util.InputMismatchException;
public class ValidaCpf {
public static boolean isCPF(String CPF) {
//Considera-se erro CPF's formados por uma sequência de números iguais
if(CPF.equals("00000000000") || CPF.equals("11111111111") || CPF.equals("22222222222") ||
CPF.equals("33333333333") ||CPF.equals("44444444444") ||CPF.equals("55555555555") ||
CPF.equals("66666666666") ||CPF.equals("77777777777") ||CPF.equals("88888888888") ||
CPF.equals("99999999999") || (CPF.length() != 11))
return (false);
char dig10, dig11;
int sm, i , r, num ,peso;
try {
//Calculo do 1º dígito verificador
sm = 0;
peso = 10;
for(i=0;i<9;i++) {
num = (int)(CPF.charAt(i)-48);
sm = sm+ (num*peso);
peso = peso -1;
}
//
r = 11 -(sm%11);
if((r == 10)|| (r==11))
dig10 = '0';
else dig10 = (char)(r+48);
sm = 0;
peso = 11;
for(i = 0 ; i<10; i++) {
num =(int)(CPF.charAt(i)-48);
sm = sm + (num*peso);
peso = peso -1;
}
r=11 - (sm%11);
if((r == 10)|| (r==11))
dig11 = '0';
else dig11 = (char)(r+48);
if((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
return (true);
else return(false);
}catch(InputMismatchException erro) {
return false;
}
}
}
| ISO-8859-1 | Java | 1,360 | java | ValidaCpf.java | Java | [] | null | [] | package sistemaacademico;
import java.util.InputMismatchException;
public class ValidaCpf {
public static boolean isCPF(String CPF) {
//Considera-se erro CPF's formados por uma sequência de números iguais
if(CPF.equals("00000000000") || CPF.equals("11111111111") || CPF.equals("22222222222") ||
CPF.equals("33333333333") ||CPF.equals("44444444444") ||CPF.equals("55555555555") ||
CPF.equals("66666666666") ||CPF.equals("77777777777") ||CPF.equals("88888888888") ||
CPF.equals("99999999999") || (CPF.length() != 11))
return (false);
char dig10, dig11;
int sm, i , r, num ,peso;
try {
//Calculo do 1º dígito verificador
sm = 0;
peso = 10;
for(i=0;i<9;i++) {
num = (int)(CPF.charAt(i)-48);
sm = sm+ (num*peso);
peso = peso -1;
}
//
r = 11 -(sm%11);
if((r == 10)|| (r==11))
dig10 = '0';
else dig10 = (char)(r+48);
sm = 0;
peso = 11;
for(i = 0 ; i<10; i++) {
num =(int)(CPF.charAt(i)-48);
sm = sm + (num*peso);
peso = peso -1;
}
r=11 - (sm%11);
if((r == 10)|| (r==11))
dig11 = '0';
else dig11 = (char)(r+48);
if((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
return (true);
else return(false);
}catch(InputMismatchException erro) {
return false;
}
}
}
| 1,360 | 0.54351 | 0.417404 | 55 | 22.654545 | 22.490578 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.472727 | false | false | 4 |
ce38b76809f817013ace358bcf7c80a1406ad8dd | 28,750,511,113,265 | a3ff99e3000b6e4faaf1a18b7ea20e892b81c458 | /app/src/main/java/moderbord/huntforcoffee/GameFunctions/Inventory.java | 57a9c3ba909047afbf20ebceef1d537d0a3c548b | [] | no_license | Moderbord/HuntForCoffee | https://github.com/Moderbord/HuntForCoffee | ebb28b99782f27ec5cab7f05feb9b8edafbc9e41 | 4b291a95d3e91f843661bbc720e02f159d02d6b3 | refs/heads/master | 2016-08-12T16:43:59.449000 | 2015-12-16T19:55:30 | 2015-12-16T19:55:30 | 48,132,144 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package moderbord.huntforcoffee.GameFunctions;
import moderbord.huntforcoffee.Entity;
/**
* Created by Moderbord on 2015-12-14.
*/
public class Inventory{
private Item inventory[] = new Item[5];
public String printInventory(Entity entity){
this.inventory = entity.getInventory().inventory;
String string = "";
for(int i = 0; i < inventory.length; i++){
if (inventory[i] != null) {
string = string + "\n"+ (i+1) + ": " +inventory[i].getiName() + ", qty " + inventory[i].getAmount();
}
}
String inv = "Your inventory:\n" + string;
return inv;
}
public String addItemToInv(Entity entity, Item item, int amount){
this.inventory = entity.getInventory().inventory;
String string = "\n\nYou have no room for " + item.getiName() + " in your inventory";
for(int i = 0; i < inventory.length; i++){
if(inventory[i] != null && inventory[i].getiName().equals(item.getiName()) && !item.getType().equals("weapon")){
inventory[i].setAmount(inventory[i].getAmount() + amount);
if(amount > 1){
string = "\n\n" + entity.geteName() + " have received " + amount + " additional " + item.getiName() + "s";
} else {
string = "\n\n" + entity.geteName() + " have received one additional " + item.getiName();
}
entity.setInventory(this);
return string;
} else if(inventory[i] == null){
inventory[i] = item;
inventory[i].setAmount(amount);
string = "\n\n" + entity.geteName() + " has received " + item.getiName();
entity.setInventory(this);
return string;
}
}
return string;
}
public Item getInvItem(Entity entity, int x){
this.inventory = entity.getInventory().inventory;
if(inventory[x] != null){
return inventory[x];
} else {
return null;
}
}
public void sortInventory(){
for(int i = 0; i < 4; i++){
int z = i + 1;
if(inventory[i] == null && inventory[z] != null){
inventory[i] = inventory[z];
inventory[z] = null;
}
}
}
public void setInvItem(Entity entity, int x, Item item) {
this.inventory = entity.getInventory().inventory;
inventory[x] = item;
}
public void removeItem(Entity entity, int x) {
this.inventory = entity.getInventory().inventory;
inventory[x] = null;
sortInventory();
}
public void consumeItem(Entity entity, int x){
this.inventory = entity.getInventory().inventory;
if(inventory[x].getType().equals("consumable")){
}
}
}
| UTF-8 | Java | 2,897 | java | Inventory.java | Java | [
{
"context": "moderbord.huntforcoffee.Entity;\n\n/**\n * Created by Moderbord on 2015-12-14.\n */\n\npublic class Inventory{",
"end": 110,
"score": 0.6499549150466919,
"start": 107,
"tag": "USERNAME",
"value": "Mod"
},
{
"context": "rbord.huntforcoffee.Entity;\n\n/**\n * Created by Moderbord on 2015-12-14.\n */\n\npublic class Inventory{\n\n ",
"end": 116,
"score": 0.9675288796424866,
"start": 110,
"tag": "NAME",
"value": "erbord"
}
] | null | [] | package moderbord.huntforcoffee.GameFunctions;
import moderbord.huntforcoffee.Entity;
/**
* Created by Moderbord on 2015-12-14.
*/
public class Inventory{
private Item inventory[] = new Item[5];
public String printInventory(Entity entity){
this.inventory = entity.getInventory().inventory;
String string = "";
for(int i = 0; i < inventory.length; i++){
if (inventory[i] != null) {
string = string + "\n"+ (i+1) + ": " +inventory[i].getiName() + ", qty " + inventory[i].getAmount();
}
}
String inv = "Your inventory:\n" + string;
return inv;
}
public String addItemToInv(Entity entity, Item item, int amount){
this.inventory = entity.getInventory().inventory;
String string = "\n\nYou have no room for " + item.getiName() + " in your inventory";
for(int i = 0; i < inventory.length; i++){
if(inventory[i] != null && inventory[i].getiName().equals(item.getiName()) && !item.getType().equals("weapon")){
inventory[i].setAmount(inventory[i].getAmount() + amount);
if(amount > 1){
string = "\n\n" + entity.geteName() + " have received " + amount + " additional " + item.getiName() + "s";
} else {
string = "\n\n" + entity.geteName() + " have received one additional " + item.getiName();
}
entity.setInventory(this);
return string;
} else if(inventory[i] == null){
inventory[i] = item;
inventory[i].setAmount(amount);
string = "\n\n" + entity.geteName() + " has received " + item.getiName();
entity.setInventory(this);
return string;
}
}
return string;
}
public Item getInvItem(Entity entity, int x){
this.inventory = entity.getInventory().inventory;
if(inventory[x] != null){
return inventory[x];
} else {
return null;
}
}
public void sortInventory(){
for(int i = 0; i < 4; i++){
int z = i + 1;
if(inventory[i] == null && inventory[z] != null){
inventory[i] = inventory[z];
inventory[z] = null;
}
}
}
public void setInvItem(Entity entity, int x, Item item) {
this.inventory = entity.getInventory().inventory;
inventory[x] = item;
}
public void removeItem(Entity entity, int x) {
this.inventory = entity.getInventory().inventory;
inventory[x] = null;
sortInventory();
}
public void consumeItem(Entity entity, int x){
this.inventory = entity.getInventory().inventory;
if(inventory[x].getType().equals("consumable")){
}
}
}
| 2,897 | 0.527442 | 0.521919 | 88 | 31.920454 | 29.834476 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.534091 | false | false | 4 |
63ac23c2955f82cbabedd9df20137730f38a89b7 | 5,884,105,219,503 | ba8a9424c3fe44231dff3f937992cb0c5c04fb46 | /LMSJ/src/main/java/in/vagabond/lms/model/financial/plaid/PlaidLocation.java | aace16525b816f7416d7c81573bea79ea6908a6f | [] | no_license | asaxena76/todo.txt-cli | https://github.com/asaxena76/todo.txt-cli | aa47d0297a971aee0b067a003e940a4ad91b0d79 | 79004e02b55dfd893b262a9018e727871537c695 | refs/heads/master | 2021-01-23T18:07:56.920000 | 2017-08-28T23:37:04 | 2017-08-28T23:37:05 | 82,992,085 | 0 | 0 | null | true | 2017-02-24T02:21:04 | 2017-02-24T02:21:04 | 2017-02-23T07:31:56 | 2017-01-03T00:13:33 | 5,467 | 0 | 0 | 0 | null | null | null | package in.vagabond.lms.model.financial.plaid;
import com.plaid.client.response.TransactionsGetResponse;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Created by asaxena on 8/2/17.
*/
@Entity
@Data
@NoArgsConstructor
public class PlaidLocation {
@TableGenerator(name = "gen_plaid_location_id", table = "sequence_generator", pkColumnName = "sequence_name",
valueColumnName = "sequence_value", pkColumnValue = "plaid_location_id", allocationSize = 1)
@Id
@GeneratedValue(
strategy = GenerationType.TABLE, generator = "gen_plaid_location_id")
private Long id;
private String address;
private String city;
private String lat;
private String lon;
private String state;
private String store_number;
private String zip;
public PlaidLocation(TransactionsGetResponse.Transaction.Location location) {
this.address = location.getAddress();
this.city = location.getCity();
this.lat= (location.getLat() == null) ? null : location.getLat().toString();
this.lon = (location.getLon() == null) ? null : location.getLon().toString();
this.state = location.getState();
this.store_number=location.getStoreNumber();
this.zip= location.getZip();
}
}
| UTF-8 | Java | 1,321 | java | PlaidLocation.java | Java | [
{
"context": "r;\n\nimport javax.persistence.*;\n\n/**\n * Created by asaxena on 8/2/17.\n */\n\n@Entity\n@Data\n@NoArgsConstructor\n",
"end": 214,
"score": 0.9981756806373596,
"start": 207,
"tag": "USERNAME",
"value": "asaxena"
}
] | null | [] | package in.vagabond.lms.model.financial.plaid;
import com.plaid.client.response.TransactionsGetResponse;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* Created by asaxena on 8/2/17.
*/
@Entity
@Data
@NoArgsConstructor
public class PlaidLocation {
@TableGenerator(name = "gen_plaid_location_id", table = "sequence_generator", pkColumnName = "sequence_name",
valueColumnName = "sequence_value", pkColumnValue = "plaid_location_id", allocationSize = 1)
@Id
@GeneratedValue(
strategy = GenerationType.TABLE, generator = "gen_plaid_location_id")
private Long id;
private String address;
private String city;
private String lat;
private String lon;
private String state;
private String store_number;
private String zip;
public PlaidLocation(TransactionsGetResponse.Transaction.Location location) {
this.address = location.getAddress();
this.city = location.getCity();
this.lat= (location.getLat() == null) ? null : location.getLat().toString();
this.lon = (location.getLon() == null) ? null : location.getLon().toString();
this.state = location.getState();
this.store_number=location.getStoreNumber();
this.zip= location.getZip();
}
}
| 1,321 | 0.680545 | 0.67676 | 53 | 23.924528 | 29.137831 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false | 4 |
cf1fe44e4b951c1f8ff93b479139dbe02589afe2 | 2,388,001,857,710 | 216e8651afc2f9393a374df55d1b0613f3f16d3f | /src/main/java/org/usfirst/frc/falcons6443/robot/subsystems/DriveTrainSystem.java | 8ab8fc80224a35beb894e18fbbde03045664fa59 | [] | no_license | AEMBOT/FRC_2019 | https://github.com/AEMBOT/FRC_2019 | f3b818be59d4f373d3623b463ad01b9e45ad1810 | a1451eafd560e0638c5aa9b66b39513ff15d9658 | refs/heads/master | 2022-05-01T21:21:36.118000 | 2019-10-29T01:27:07 | 2019-10-29T01:27:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.usfirst.frc.falcons6443.robot.subsystems;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.VictorSP;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.falcons6443.robot.RobotMap;
import org.usfirst.frc.falcons6443.robot.hardware.*;
import java.util.ArrayList;
import java.util.List;
import com.revrobotics.*;
import org.usfirst.frc.falcons6443.robot.hardware.joysticks.Xbox;
import org.usfirst.frc.falcons6443.robot.utilities.enums.DriveStyles;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMax.IdleMode;
import com.revrobotics.CANSparkMax.InputMode;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
//import org.usfirst.frc.falcons6443.robot.utilities.Logger;
/**
* Subsystem for the robot's drive train.
* <p>
* Contains 2 SpeedControllerGroups which are controlled by an instance of RobotDrive.
* This class is meant to fix some of the shortcomings of the original DriveTrainSystem
* class as well as make it more simple and readable.
*
* @author Christopher Medlin, Ivan Kenevich, Shivashriganesh Mahato
*/
public class DriveTrainSystem{
SpeedControllerGroup leftMotors;
SpeedControllerGroup rightMotors;
private Encoders leftEncoder; // Encoders clicks per rotation = 49
//private Encoders rightEncoder;
private List<List<Integer>> encoderList = new ArrayList<List<Integer>>();
public Timer encoderCheck;
private boolean usingLeftEncoder = true; //keep true. Left is our default encoder, right is our backup encoder
private double minEncoderMovement = 5; //ticks //change value
private static final double WheelDiameter = 6;
//Controls robot movement speed
private double[] speedLevels = {4, 2, 1.3333 , 1};
private int speedIndex = 3;
private double currentLevel = speedLevels[speedIndex];
private double moveSpeed;
// A [nice] class in the wpilib that provides numerous driving capabilities.
// Use it whenever you want your robot to move.
private DifferentialDrive drive;
/**
* Constructor for DriveTrainSystem.
*/
public DriveTrainSystem() {
//2019 Seasson Comp Bot motors
leftMotors = new SpeedControllerGroup(new CANSparkMax(RobotMap.FrontLeftMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.BackLeftMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.LeftCenterMotor,MotorType.kBrushless));
rightMotors = new SpeedControllerGroup(new CANSparkMax(RobotMap.FrontRightMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.BackRightMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.RightCenterMotor, MotorType.kBrushless));
//Creates a new differential drive using the previously defined motors
drive = new DifferentialDrive(leftMotors, rightMotors);
//Flips motor direction to run the left in the correct direction
leftMotors.setInverted(true);
// the driver station will complain for some reason if this isn't setSpeed so it's pretty necessary.
// [FOR SCIENCE!]
drive.setSafetyEnabled(false);
drive.setMaxOutput(1);
for(int i = 0; i <= 1; i++) encoderList.add(i, new ArrayList<>());
encoderCheck = new Timer();
}
/**
* Used to get a reference to the left side of the drive train from other classes
* @return 'leftMotors' SpeedControllerGroup
*/
public SpeedControllerGroup getLeftMotors(){
return leftMotors;
}
/**
* Used to get a reference to the right side of the motors
* @return 'rightMotors' SpeedControllerGroup
*/
public SpeedControllerGroup getRightMotors(){
return rightMotors;
}
/**
* Singular callable method to quickly change drive styles.
*
* @param controller controller reference used for power/rotation values
* @param style DriveStyles enum, used to easily switch style
* @param speedMultiplier will adjust the drive speed depending on weather or not demo mode is on
*/
public void generalDrive(Xbox controller, DriveStyles style, double speedMultiplier){
switch(style){
//General tank drive, 2 Joysticks one for each side
case Tank:
tankDrive(controller.leftStickY() * speedMultiplier,controller.rightStickY() * speedMultiplier);
break;
//Arcade drive, 2 Joysticks, one for forward and reverse another for turning
case Arcade:
arcadeDrive(-controller.rightStickX() * speedMultiplier, controller.leftStickY() * speedMultiplier);
break;
case Curve:
curvatureDrive(controller.leftStickY() / currentLevel,controller.rightStickX() / currentLevel, false);
break;
//RC 'Style' controls, 1 Joystick followed by the left trigger and right trigger.
//Joystick turns and the triggers move forward and back
case RC:
rcDrive(controller.leftTrigger(), controller.rightTrigger(), controller.rightStickX());
break;
//The drive style selection default, is currently defautlting to arcade
default:
arcadeDrive(-controller.rightStickX() / currentLevel, controller.leftStickY() / currentLevel);
}
}
/**
* Allows for custom setting of motor power level.
*
* @param left the power for the left motors.
* @param right the power for the right motors.
*
* Implements the differentialDrive tankDrive into a local method
*/
public void tankDrive(double left, double right) {
drive.tankDrive(left, right);
}
/**
* Allows separate control of forward movement and heading
*
* @param speed the robots speed: forward is positive
* @param rotation the rate of rotation: clockwise is positive
*
* Implements the differentialDrive arcadeDrive into a local method
*/
public void arcadeDrive(double speed, double rotation){
drive.arcadeDrive(speed,-rotation);
}
/**
* Allows for RC car style drive
*
* @param leftTrig Left trigger goes forward
* @param rightTrig Right trigger goes backward
* @param rotation Right stick X-axis
*
* Implements arcadeDrive using RC controls
*/
private void rcDrive(double leftTrig, double rightTrig, double rotation){
//Makes sure some values are being sent over the 'leftTrig' variable
if(leftTrig > 0){
//Asssign the trigger value to the new value of the 'moveSpeed' variable
moveSpeed = leftTrig;
}
//Repeats the same process used for the left trigger
else if(rightTrig > 0){
moveSpeed = -rightTrig;
}
//If neither the left or right trigger are pushed set move speed to 0
else{
moveSpeed = 0;
}
//Finally applies the values to the motors
drive.arcadeDrive(-rotation, moveSpeed);
}
/**
* Allows separate control of forward movement and change in path curvature
*
* @param speed the robots speed: forward is positive
* @param rotation the rate of rotation: clockwise is positive
*
* Implements the differentialDrive curvatureDrive into a local method
*/
private void curvatureDrive(double speed, double rotation, boolean isQuickTurn){
drive.curvatureDrive(speed,rotation,isQuickTurn);
}
public boolean first; //set true in AutoPaths.WaitDrive()
private int strikes; //how many times the encoder did not move enough in 1 second
//In progress. Needs to be tested
public double getDistanceSafe(){
if(first){
encoderCheck.reset();
encoderCheck.start(); //stopped in AutoPaths.WaitDrive()
}
first = false;
if(encoderCheck.get() > 1){ //if the function has been running for a second
double first = encoderList.get(0).get(0);
double last = encoderList.get(0).get(encoderList.size() - 1);
encoderCheck.reset();
for(int i = 0; i <= 1; i++) encoderList.get(i).clear();
if(last - first < minEncoderMovement){ //if the encoder has not moved enough in a second increase strikes
strikes++;
if(strikes >= 3) usingLeftEncoder = false; //if 3 strikes use right encoder (the backup encoder)
}
}
return getDistanceUnsafe();
}
/**
* Used to return a constant of the unsafe distance for the encoder
*/
public double getDistanceUnsafe(){
return 10;
}
/**
* The following method is used to act as a virtual speed shifter to shift between several different speed values
*/
public void changeSpeed (boolean upOrDown){
if(upOrDown && speedIndex < speedLevels.length){
speedIndex += 1;
currentLevel = speedLevels[speedIndex];
}
else if(!upOrDown && speedIndex > 0){
speedIndex -= 1;
currentLevel = speedLevels[speedIndex];
}
else {
//redundant but might as well
currentLevel = currentLevel;
}
}
}
| UTF-8 | Java | 9,377 | java | DriveTrainSystem.java | Java | [
{
"context": "as make it more simple and readable.\n *\n * @author Christopher Medlin, Ivan Kenevich, Shivashriganesh Mahato\n */\npublic",
"end": 1122,
"score": 0.9998784065246582,
"start": 1104,
"tag": "NAME",
"value": "Christopher Medlin"
},
{
"context": "le and readable.\n *\n * @author Christopher Medlin, Ivan Kenevich, Shivashriganesh Mahato\n */\npublic class DriveTra",
"end": 1137,
"score": 0.9998852610588074,
"start": 1124,
"tag": "NAME",
"value": "Ivan Kenevich"
},
{
"context": ".\n *\n * @author Christopher Medlin, Ivan Kenevich, Shivashriganesh Mahato\n */\npublic class DriveTrainSystem{\n\n SpeedCont",
"end": 1161,
"score": 0.9998835325241089,
"start": 1139,
"tag": "NAME",
"value": "Shivashriganesh Mahato"
}
] | null | [] | package org.usfirst.frc.falcons6443.robot.subsystems;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.VictorSP;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.falcons6443.robot.RobotMap;
import org.usfirst.frc.falcons6443.robot.hardware.*;
import java.util.ArrayList;
import java.util.List;
import com.revrobotics.*;
import org.usfirst.frc.falcons6443.robot.hardware.joysticks.Xbox;
import org.usfirst.frc.falcons6443.robot.utilities.enums.DriveStyles;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMax.IdleMode;
import com.revrobotics.CANSparkMax.InputMode;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
//import org.usfirst.frc.falcons6443.robot.utilities.Logger;
/**
* Subsystem for the robot's drive train.
* <p>
* Contains 2 SpeedControllerGroups which are controlled by an instance of RobotDrive.
* This class is meant to fix some of the shortcomings of the original DriveTrainSystem
* class as well as make it more simple and readable.
*
* @author <NAME>, <NAME>, <NAME>
*/
public class DriveTrainSystem{
SpeedControllerGroup leftMotors;
SpeedControllerGroup rightMotors;
private Encoders leftEncoder; // Encoders clicks per rotation = 49
//private Encoders rightEncoder;
private List<List<Integer>> encoderList = new ArrayList<List<Integer>>();
public Timer encoderCheck;
private boolean usingLeftEncoder = true; //keep true. Left is our default encoder, right is our backup encoder
private double minEncoderMovement = 5; //ticks //change value
private static final double WheelDiameter = 6;
//Controls robot movement speed
private double[] speedLevels = {4, 2, 1.3333 , 1};
private int speedIndex = 3;
private double currentLevel = speedLevels[speedIndex];
private double moveSpeed;
// A [nice] class in the wpilib that provides numerous driving capabilities.
// Use it whenever you want your robot to move.
private DifferentialDrive drive;
/**
* Constructor for DriveTrainSystem.
*/
public DriveTrainSystem() {
//2019 Seasson Comp Bot motors
leftMotors = new SpeedControllerGroup(new CANSparkMax(RobotMap.FrontLeftMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.BackLeftMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.LeftCenterMotor,MotorType.kBrushless));
rightMotors = new SpeedControllerGroup(new CANSparkMax(RobotMap.FrontRightMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.BackRightMotor, MotorType.kBrushless), new CANSparkMax(RobotMap.RightCenterMotor, MotorType.kBrushless));
//Creates a new differential drive using the previously defined motors
drive = new DifferentialDrive(leftMotors, rightMotors);
//Flips motor direction to run the left in the correct direction
leftMotors.setInverted(true);
// the driver station will complain for some reason if this isn't setSpeed so it's pretty necessary.
// [FOR SCIENCE!]
drive.setSafetyEnabled(false);
drive.setMaxOutput(1);
for(int i = 0; i <= 1; i++) encoderList.add(i, new ArrayList<>());
encoderCheck = new Timer();
}
/**
* Used to get a reference to the left side of the drive train from other classes
* @return 'leftMotors' SpeedControllerGroup
*/
public SpeedControllerGroup getLeftMotors(){
return leftMotors;
}
/**
* Used to get a reference to the right side of the motors
* @return 'rightMotors' SpeedControllerGroup
*/
public SpeedControllerGroup getRightMotors(){
return rightMotors;
}
/**
* Singular callable method to quickly change drive styles.
*
* @param controller controller reference used for power/rotation values
* @param style DriveStyles enum, used to easily switch style
* @param speedMultiplier will adjust the drive speed depending on weather or not demo mode is on
*/
public void generalDrive(Xbox controller, DriveStyles style, double speedMultiplier){
switch(style){
//General tank drive, 2 Joysticks one for each side
case Tank:
tankDrive(controller.leftStickY() * speedMultiplier,controller.rightStickY() * speedMultiplier);
break;
//Arcade drive, 2 Joysticks, one for forward and reverse another for turning
case Arcade:
arcadeDrive(-controller.rightStickX() * speedMultiplier, controller.leftStickY() * speedMultiplier);
break;
case Curve:
curvatureDrive(controller.leftStickY() / currentLevel,controller.rightStickX() / currentLevel, false);
break;
//RC 'Style' controls, 1 Joystick followed by the left trigger and right trigger.
//Joystick turns and the triggers move forward and back
case RC:
rcDrive(controller.leftTrigger(), controller.rightTrigger(), controller.rightStickX());
break;
//The drive style selection default, is currently defautlting to arcade
default:
arcadeDrive(-controller.rightStickX() / currentLevel, controller.leftStickY() / currentLevel);
}
}
/**
* Allows for custom setting of motor power level.
*
* @param left the power for the left motors.
* @param right the power for the right motors.
*
* Implements the differentialDrive tankDrive into a local method
*/
public void tankDrive(double left, double right) {
drive.tankDrive(left, right);
}
/**
* Allows separate control of forward movement and heading
*
* @param speed the robots speed: forward is positive
* @param rotation the rate of rotation: clockwise is positive
*
* Implements the differentialDrive arcadeDrive into a local method
*/
public void arcadeDrive(double speed, double rotation){
drive.arcadeDrive(speed,-rotation);
}
/**
* Allows for RC car style drive
*
* @param leftTrig Left trigger goes forward
* @param rightTrig Right trigger goes backward
* @param rotation Right stick X-axis
*
* Implements arcadeDrive using RC controls
*/
private void rcDrive(double leftTrig, double rightTrig, double rotation){
//Makes sure some values are being sent over the 'leftTrig' variable
if(leftTrig > 0){
//Asssign the trigger value to the new value of the 'moveSpeed' variable
moveSpeed = leftTrig;
}
//Repeats the same process used for the left trigger
else if(rightTrig > 0){
moveSpeed = -rightTrig;
}
//If neither the left or right trigger are pushed set move speed to 0
else{
moveSpeed = 0;
}
//Finally applies the values to the motors
drive.arcadeDrive(-rotation, moveSpeed);
}
/**
* Allows separate control of forward movement and change in path curvature
*
* @param speed the robots speed: forward is positive
* @param rotation the rate of rotation: clockwise is positive
*
* Implements the differentialDrive curvatureDrive into a local method
*/
private void curvatureDrive(double speed, double rotation, boolean isQuickTurn){
drive.curvatureDrive(speed,rotation,isQuickTurn);
}
public boolean first; //set true in AutoPaths.WaitDrive()
private int strikes; //how many times the encoder did not move enough in 1 second
//In progress. Needs to be tested
public double getDistanceSafe(){
if(first){
encoderCheck.reset();
encoderCheck.start(); //stopped in AutoPaths.WaitDrive()
}
first = false;
if(encoderCheck.get() > 1){ //if the function has been running for a second
double first = encoderList.get(0).get(0);
double last = encoderList.get(0).get(encoderList.size() - 1);
encoderCheck.reset();
for(int i = 0; i <= 1; i++) encoderList.get(i).clear();
if(last - first < minEncoderMovement){ //if the encoder has not moved enough in a second increase strikes
strikes++;
if(strikes >= 3) usingLeftEncoder = false; //if 3 strikes use right encoder (the backup encoder)
}
}
return getDistanceUnsafe();
}
/**
* Used to return a constant of the unsafe distance for the encoder
*/
public double getDistanceUnsafe(){
return 10;
}
/**
* The following method is used to act as a virtual speed shifter to shift between several different speed values
*/
public void changeSpeed (boolean upOrDown){
if(upOrDown && speedIndex < speedLevels.length){
speedIndex += 1;
currentLevel = speedLevels[speedIndex];
}
else if(!upOrDown && speedIndex > 0){
speedIndex -= 1;
currentLevel = speedLevels[speedIndex];
}
else {
//redundant but might as well
currentLevel = currentLevel;
}
}
}
| 9,342 | 0.664178 | 0.657033 | 254 | 35.917324 | 35.955204 | 242 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484252 | false | false | 4 |
1ce40eef165903e6a09868da3c673cb360757468 | 26,362,509,310,375 | 4de46b91f653f45bda1757cd9e1161ff3de8305c | /static_block.java | 42d3c6a4d65e97f2f2eacad978f5bb288fa2bf3b | [] | no_license | SuhasKamble/simple-java-programs | https://github.com/SuhasKamble/simple-java-programs | 6674da8e87df8d229665aee0b53db56225977dcf | 0bf8f1de714d3c3891a20f5ab754fba811dd1e93 | refs/heads/master | 2023-02-25T01:16:52.448000 | 2021-01-25T13:16:53 | 2021-01-25T13:16:53 | 332,752,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class static_block {
static int rnum;
static String name;
static {
rnum = 10;
name = "Suhas Kamble";
}
public static void main(String[] args) {
System.out.println("Roll number is " + rnum);
System.out.println("Name is " + name);
}
}
| UTF-8 | Java | 298 | java | static_block.java | Java | [
{
"context": "\n\n static {\n rnum = 10;\n name = \"Suhas Kamble\";\n }\n\n public static void main(String[] arg",
"end": 134,
"score": 0.9998843669891357,
"start": 122,
"tag": "NAME",
"value": "Suhas Kamble"
}
] | null | [] | public class static_block {
static int rnum;
static String name;
static {
rnum = 10;
name = "<NAME>";
}
public static void main(String[] args) {
System.out.println("Roll number is " + rnum);
System.out.println("Name is " + name);
}
}
| 292 | 0.557047 | 0.550336 | 14 | 20.285715 | 17.272722 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
170e9a3d32e6bfce915a2ddb5922dd36c0ef57d4 | 21,139,829,068,257 | cac5587d6fce718dff1fe9368dde9a8eb9815446 | /swift/web/src/main/java/edu/mayo/mprc/swift/report/ReportInfo.java | b432a3ca25aa5709eaec81121dc56684621e6897 | [
"Apache-2.0"
] | permissive | romanzenka/swift | https://github.com/romanzenka/swift | e999255872eea48bd6261a87185d2403b9ab27d8 | 82232750807696ba48fa84f0d5b43e558a3222a5 | refs/heads/master | 2022-02-08T13:26:43.840000 | 2016-02-17T20:49:04 | 2016-02-17T20:49:04 | 2,935,040 | 2 | 2 | Apache-2.0 | false | 2022-02-09T23:07:07 | 2011-12-07T19:29:21 | 2015-04-30T12:53:37 | 2022-02-09T23:07:06 | 20,141 | 2 | 2 | 14 | Java | false | false | package edu.mayo.mprc.swift.report;
/**
* Report information. A report is a Scaffold output file which can have Analysis attached to it.
*
* @author Roman Zenka
*/
public class ReportInfo implements Comparable<ReportInfo> {
private long reportId;
private String filePath;
private boolean hasAnalysis;
public ReportInfo(final long reportId, final String filePath, final boolean hasAnalysis) {
this.reportId = reportId;
this.filePath = filePath;
this.hasAnalysis = hasAnalysis;
}
public long getReportId() {
return reportId;
}
public String getFilePath() {
return filePath;
}
public boolean isHasAnalysis() {
return hasAnalysis;
}
@Override
public int compareTo(final ReportInfo reportInfo) {
return getFilePath().compareTo(reportInfo.getFilePath());
}
}
| UTF-8 | Java | 791 | java | ReportInfo.java | Java | [
{
"context": "ch can have Analysis attached to it.\n *\n * @author Roman Zenka\n */\npublic class ReportInfo implements Comparable",
"end": 164,
"score": 0.9993981122970581,
"start": 153,
"tag": "NAME",
"value": "Roman Zenka"
}
] | null | [] | package edu.mayo.mprc.swift.report;
/**
* Report information. A report is a Scaffold output file which can have Analysis attached to it.
*
* @author <NAME>
*/
public class ReportInfo implements Comparable<ReportInfo> {
private long reportId;
private String filePath;
private boolean hasAnalysis;
public ReportInfo(final long reportId, final String filePath, final boolean hasAnalysis) {
this.reportId = reportId;
this.filePath = filePath;
this.hasAnalysis = hasAnalysis;
}
public long getReportId() {
return reportId;
}
public String getFilePath() {
return filePath;
}
public boolean isHasAnalysis() {
return hasAnalysis;
}
@Override
public int compareTo(final ReportInfo reportInfo) {
return getFilePath().compareTo(reportInfo.getFilePath());
}
}
| 786 | 0.74842 | 0.74842 | 35 | 21.6 | 24.659046 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.171429 | false | false | 4 |
0da7326fc1aeb4206afa07cd7ac1ff25ca3821bf | 27,504,970,629,237 | 69e6412a77b695f61df9c15e0baf7c2c7f6cf3cd | /src/Main.java | b49de1c209f47395e3b0f3d0d26cb5cb0e176379 | [] | no_license | DCplayer/Gauss-Gauss-Jordan | https://github.com/DCplayer/Gauss-Gauss-Jordan | ded4b62f5572c5fabf5e056c915e074bf0b58b3b | a48a86cc5399646d1b95caa8095b149f695f4949 | refs/heads/master | 2021-01-20T22:55:13.873000 | 2017-08-30T07:01:15 | 2017-08-30T07:01:15 | 101,830,296 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.font.NumericShaper;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by Diego Castaneda on 21/08/2017.
*/
public class Main {
public static void main(String args[]){
ArrayList<ArrayList<Double>> matriz = new ArrayList<>();
ArrayList<Double> resultadosFilas = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Introduzca el numero de incognitas de su sistema: ");
int numeroDeFilas = scanner.nextInt();
for (int indexFila = 0; indexFila < numeroDeFilas; indexFila++){
ArrayList<Double> fila = new ArrayList<>();
for(int variable = 0; variable < numeroDeFilas; variable++){
System.out.println("Porfavor ingrese el coeficiente de la variable " + (variable + 1) + " de la fila "
+ (indexFila + 1));
double coeficiente = Double.parseDouble(scanner.next());
fila.add(coeficiente);
}
System.out.println("Ingrese el resutlado de esta fila: ");
double resultado = Double.parseDouble(scanner.next());
fila.add(resultado);
resultadosFilas.add(resultado);
matriz.add(fila);
}
Gauss gauss = new Gauss(matriz);
GaussJordan gaussJ = new GaussJordan(matriz);
gauss.calcularIncognitas();
gaussJ.calcularIncognitas();
ArrayList<Double> respuestasG = gauss.getIncognitas();
ArrayList<Double> respuestasGJ = gaussJ.getIncognitas();
System.out.println("Su respuesta con Eliminacion gaussiana es: ");
System.out.println(respuestasG);
System.out.println("Su respuesta con Gauss-Jordan es: ");
System.out.println(respuestasGJ);
}
}
| UTF-8 | Java | 1,802 | java | Main.java | Java | [
{
"context": "List;\nimport java.util.Scanner;\n\n/**\n * Created by Diego Castaneda on 21/08/2017.\n */\npublic class Main {\n\n publi",
"end": 124,
"score": 0.9998924136161804,
"start": 109,
"tag": "NAME",
"value": "Diego Castaneda"
}
] | null | [] | import java.awt.font.NumericShaper;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by <NAME> on 21/08/2017.
*/
public class Main {
public static void main(String args[]){
ArrayList<ArrayList<Double>> matriz = new ArrayList<>();
ArrayList<Double> resultadosFilas = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Introduzca el numero de incognitas de su sistema: ");
int numeroDeFilas = scanner.nextInt();
for (int indexFila = 0; indexFila < numeroDeFilas; indexFila++){
ArrayList<Double> fila = new ArrayList<>();
for(int variable = 0; variable < numeroDeFilas; variable++){
System.out.println("Porfavor ingrese el coeficiente de la variable " + (variable + 1) + " de la fila "
+ (indexFila + 1));
double coeficiente = Double.parseDouble(scanner.next());
fila.add(coeficiente);
}
System.out.println("Ingrese el resutlado de esta fila: ");
double resultado = Double.parseDouble(scanner.next());
fila.add(resultado);
resultadosFilas.add(resultado);
matriz.add(fila);
}
Gauss gauss = new Gauss(matriz);
GaussJordan gaussJ = new GaussJordan(matriz);
gauss.calcularIncognitas();
gaussJ.calcularIncognitas();
ArrayList<Double> respuestasG = gauss.getIncognitas();
ArrayList<Double> respuestasGJ = gaussJ.getIncognitas();
System.out.println("Su respuesta con Eliminacion gaussiana es: ");
System.out.println(respuestasG);
System.out.println("Su respuesta con Gauss-Jordan es: ");
System.out.println(respuestasGJ);
}
}
| 1,793 | 0.618202 | 0.611543 | 53 | 33 | 29.117847 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584906 | false | false | 4 |
aaff503ab978db5da1123e8eb10511974bad246b | 30,236,569,813,404 | 2a71c517b8cc70d1c40184bdb2488c7da2fc6cec | /PRISBusWeb/src/main/java/servlets/PretragaServlet.java | a4c6879a9576158345c08741cc6dfad8ef050205 | [] | no_license | nixos89/AS-BUS | https://github.com/nixos89/AS-BUS | 8030117b1fd06b4254616f646480d400c6149f70 | bf1f0f19f635eb79502b19ce93b22a73074ebf01 | refs/heads/TK-756 | 2023-02-05T19:00:33.018000 | 2023-01-24T14:57:19 | 2023-01-24T14:57:19 | 86,580,868 | 2 | 0 | null | false | 2023-01-24T14:57:20 | 2017-03-29T12:43:45 | 2022-02-02T18:30:01 | 2023-01-24T14:57:19 | 17,171 | 0 | 0 | 0 | Java | false | false | package servlets;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import managers.PolasciManager;
import model.Polazak;
/**
* Servlet implementation class PretragaServlet
*/
public class PretragaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public PretragaServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
request.getSession().getServletContext();
int idGrad = Integer.parseInt(request.getParameter("destinacija"));
String datumStr = request.getParameter("datumPolaska");
Date datumP = null;
String porukaPretraga = null;
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
datumP = sdf.parse(datumStr);
List<Polazak> polasci = new PolasciManager().vratiPolaskeZaDatumIDestinaciju(idGrad, datumP);
if(!polasci.isEmpty()){
porukaPretraga = "Nema polazaka za zadate parametre!";
request.setAttribute("porukaPretraga", porukaPretraga);
request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
}else{//NIJE prazan
request.setAttribute("polasci", polasci);
request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
}
}catch(DateTimeParseException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
// List<Polazak> polasci = new PolasciManager().vratiPolaskeZaDatumIDestinaciju(idGrad, datumP);
// if(polasci.isEmpty()){
// porukaPretraga = "Nema polazaka za zadate parametre!";
// request.setAttribute("porukaPretraga", porukaPretraga);
// request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
// }else{//NIJE prazan
// request.setAttribute("polasci", polasci);
// request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
// }
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| UTF-8 | Java | 2,446 | java | PretragaServlet.java | Java | [] | null | [] | package servlets;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import managers.PolasciManager;
import model.Polazak;
/**
* Servlet implementation class PretragaServlet
*/
public class PretragaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public PretragaServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
request.getSession().getServletContext();
int idGrad = Integer.parseInt(request.getParameter("destinacija"));
String datumStr = request.getParameter("datumPolaska");
Date datumP = null;
String porukaPretraga = null;
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
datumP = sdf.parse(datumStr);
List<Polazak> polasci = new PolasciManager().vratiPolaskeZaDatumIDestinaciju(idGrad, datumP);
if(!polasci.isEmpty()){
porukaPretraga = "Nema polazaka za zadate parametre!";
request.setAttribute("porukaPretraga", porukaPretraga);
request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
}else{//NIJE prazan
request.setAttribute("polasci", polasci);
request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
}
}catch(DateTimeParseException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
// List<Polazak> polasci = new PolasciManager().vratiPolaskeZaDatumIDestinaciju(idGrad, datumP);
// if(polasci.isEmpty()){
// porukaPretraga = "Nema polazaka za zadate parametre!";
// request.setAttribute("porukaPretraga", porukaPretraga);
// request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
// }else{//NIJE prazan
// request.setAttribute("polasci", polasci);
// request.getRequestDispatcher("Pretraga.jsp").forward(request, response);
// }
}catch(Exception e){
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 2,446 | 0.737122 | 0.736713 | 73 | 32.506851 | 29.004545 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.726027 | false | false | 4 |
fa21977ad9c7ad2686f107fa450af636f61726f9 | 20,976,620,315,253 | f5d52112e70431045817a94503546bb16a863372 | /src/main/java/verni/co/kr/message/MessageService.java | 49e868759b3c11af8d16277399c5f2f83e666f60 | [] | no_license | chlee2103/finalVerni | https://github.com/chlee2103/finalVerni | 8a44ff8fbcffa0fe0b35ad5cbe0407e4aad7fab1 | 412eb8b5d8f3e56775d05803d099ce27afe5b8f0 | refs/heads/master | 2023-08-12T02:44:22.685000 | 2021-10-15T14:30:08 | 2021-10-15T14:30:08 | 402,737,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package verni.co.kr.message;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageService {
@Autowired
MessageDao dao;
public boolean messageAdd(MessageDto ms) {
return dao.messageAdd(ms);
}
public List<MessageDto> getMessageList(MessageParam param){
return dao.getMessageList(param);
}
public int getMessageTotal(MessageParam param) {
return dao.getMessageTotal(param);
}
//상태 업데이트
public void statusUpdate(int ms_no) {
dao.statusUpdate(ms_no);
}
public int getOrderMaxNo() {
return dao.getOrderMaxNo();
}
public int getMsno(int od_no) {
return dao.getMsno(od_no);
}
public boolean msgUpdate(MessageDto ms) {
return dao.msgUpdate(ms);
}
}
| UTF-8 | Java | 809 | java | MessageService.java | Java | [] | null | [] | package verni.co.kr.message;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageService {
@Autowired
MessageDao dao;
public boolean messageAdd(MessageDto ms) {
return dao.messageAdd(ms);
}
public List<MessageDto> getMessageList(MessageParam param){
return dao.getMessageList(param);
}
public int getMessageTotal(MessageParam param) {
return dao.getMessageTotal(param);
}
//상태 업데이트
public void statusUpdate(int ms_no) {
dao.statusUpdate(ms_no);
}
public int getOrderMaxNo() {
return dao.getOrderMaxNo();
}
public int getMsno(int od_no) {
return dao.getMsno(od_no);
}
public boolean msgUpdate(MessageDto ms) {
return dao.msgUpdate(ms);
}
}
| 809 | 0.741531 | 0.741531 | 41 | 18.439024 | 18.455019 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.219512 | false | false | 4 |
7e178b26721c72ff43a6e910463788839a60cae7 | 23,570,780,561,049 | 90432268acdcad73d841a8ae4296389305afdcc8 | /前端/src/androidTest/java/com/example/danciji1_0/AddDCTest.java | 9a774cfbd6023b1189a6d543d3f23874c30ec32a | [] | no_license | HuY2x4/DanCiJiApp | https://github.com/HuY2x4/DanCiJiApp | b0c6db629d53c81922b6a49cf9c43d384c1d0cd3 | 6cf299859301e2173342f4ad578548ee25b3c473 | refs/heads/master | 2020-04-03T14:08:24.623000 | 2018-10-30T02:42:42 | 2018-10-30T02:42:42 | 155,312,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.danciji1_0;
import static org.junit.Assert.*;
/**
* Created by hyx on 2018/6/26.
*/
public class AddDCTest {
} | UTF-8 | Java | 135 | java | AddDCTest.java | Java | [
{
"context": "port static org.junit.Assert.*;\n\n/**\n * Created by hyx on 2018/6/26.\n */\npublic class AddDCTest {\n\n}",
"end": 89,
"score": 0.9994688034057617,
"start": 86,
"tag": "USERNAME",
"value": "hyx"
}
] | null | [] | package com.example.danciji1_0;
import static org.junit.Assert.*;
/**
* Created by hyx on 2018/6/26.
*/
public class AddDCTest {
} | 135 | 0.688889 | 0.622222 | 10 | 12.6 | 14.207041 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
3e8cba7ab0f80a9e7c2e1d54e3b03ca34ed361f5 | 1,614,907,759,083 | 56dfe8d46eeb4ece71b3cd5e1bc2774f8f371c5e | /app/src/main/java/edu/neu/khojak/LocationReminder/TODOList/TODOListPersonal.java | 4f5e0a6f4acda1ef9aae11b8137b481e35777dd3 | [] | no_license | pankaj-badgujar/khojak-location-reminder-app | https://github.com/pankaj-badgujar/khojak-location-reminder-app | dea38171c9619b0028d9ad29a87e5abad72d8a2b | a24bcbd4eda152f95950b9b82f0a20f7733da261 | refs/heads/master | 2022-12-21T09:09:40.004000 | 2020-04-19T02:46:16 | 2020-04-19T02:46:16 | 296,886,424 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.neu.khojak.LocationReminder.TODOList;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import java.util.function.Consumer;
import edu.neu.khojak.LocationReminder.Adapters.TODOAdapter;
import edu.neu.khojak.LocationReminder.POJO.PersonalReminder;
import edu.neu.khojak.R;
public class TODOListPersonal extends AppCompatActivity {
private static TODOAdapter adapter;
private ListView listView;
private final static int REQUEST_CODE_1 = 1;
private final Context context = this;
private AlertDialog inputDialog;
private EditText reminderTitle;
private Location location;
private final static String emptyText = "";
public static void addToList(List<PersonalReminder> data) {
adapter.addAll(data);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_personal);
//Consumer to call addToList Function for the data fetched.
Consumer<List<PersonalReminder>> function = TODOListPersonal::addToList;
(new FetchTask(this, function)).execute();
adapter = new TODOAdapter(this);
listView = findViewById(R.id.personal_todo_list);
listView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.new_todo);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// get activity_reminder_info.xml as prompt
LayoutInflater layoutInflater = LayoutInflater.from(context);
final View parentView = view;
final View promptView = layoutInflater.inflate(R.layout.activity_reminder_info, null);
reminderTitle = promptView.findViewById(R.id.urlName);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set activity_reminder_info.xml to be the layout file of the inputDialog builder
alertDialogBuilder.setView(promptView);
// setup a dialog window
alertDialogBuilder.setCancelable(true);
// create an alert dialog
inputDialog = alertDialogBuilder.create();
inputDialog.show();
}
});
}
public void clearText(View view) {
reminderTitle.setText(emptyText);
}
public void onSetLocationPressed(View view) {
// Toast.makeText(this, "starting map activity", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(this, LocationActivity.class), REQUEST_CODE_1);
}
public void exit(View view) {
inputDialog.dismiss();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_1:
if(data != null) {
this.location = data.getParcelableExtra("location");
Toast.makeText(this, location != null ? location.toString() : "",
Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
public void closeActivity(View view) {
inputDialog.dismiss();
}
public void createReminder(View view) {
String reminder = reminderTitle.getText().toString();
if (reminder.isEmpty()) {
reminderTitle.setError(getString(R.string.empty_field_error));
} else if (location == null) {
Toast.makeText(this, " Location cannot be empty.",
Toast.LENGTH_LONG).show();
} else {
PersonalReminder personalReminder = new PersonalReminder(reminder, location);
adapter.add(personalReminder);
(new InsertTask(this,personalReminder)).execute();
this.location = null;
inputDialog.dismiss();
}
}
}
| UTF-8 | Java | 4,534 | java | TODOListPersonal.java | Java | [] | null | [] | package edu.neu.khojak.LocationReminder.TODOList;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
import java.util.function.Consumer;
import edu.neu.khojak.LocationReminder.Adapters.TODOAdapter;
import edu.neu.khojak.LocationReminder.POJO.PersonalReminder;
import edu.neu.khojak.R;
public class TODOListPersonal extends AppCompatActivity {
private static TODOAdapter adapter;
private ListView listView;
private final static int REQUEST_CODE_1 = 1;
private final Context context = this;
private AlertDialog inputDialog;
private EditText reminderTitle;
private Location location;
private final static String emptyText = "";
public static void addToList(List<PersonalReminder> data) {
adapter.addAll(data);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_personal);
//Consumer to call addToList Function for the data fetched.
Consumer<List<PersonalReminder>> function = TODOListPersonal::addToList;
(new FetchTask(this, function)).execute();
adapter = new TODOAdapter(this);
listView = findViewById(R.id.personal_todo_list);
listView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.new_todo);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// get activity_reminder_info.xml as prompt
LayoutInflater layoutInflater = LayoutInflater.from(context);
final View parentView = view;
final View promptView = layoutInflater.inflate(R.layout.activity_reminder_info, null);
reminderTitle = promptView.findViewById(R.id.urlName);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set activity_reminder_info.xml to be the layout file of the inputDialog builder
alertDialogBuilder.setView(promptView);
// setup a dialog window
alertDialogBuilder.setCancelable(true);
// create an alert dialog
inputDialog = alertDialogBuilder.create();
inputDialog.show();
}
});
}
public void clearText(View view) {
reminderTitle.setText(emptyText);
}
public void onSetLocationPressed(View view) {
// Toast.makeText(this, "starting map activity", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(this, LocationActivity.class), REQUEST_CODE_1);
}
public void exit(View view) {
inputDialog.dismiss();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_1:
if(data != null) {
this.location = data.getParcelableExtra("location");
Toast.makeText(this, location != null ? location.toString() : "",
Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
public void closeActivity(View view) {
inputDialog.dismiss();
}
public void createReminder(View view) {
String reminder = reminderTitle.getText().toString();
if (reminder.isEmpty()) {
reminderTitle.setError(getString(R.string.empty_field_error));
} else if (location == null) {
Toast.makeText(this, " Location cannot be empty.",
Toast.LENGTH_LONG).show();
} else {
PersonalReminder personalReminder = new PersonalReminder(reminder, location);
adapter.add(personalReminder);
(new InsertTask(this,personalReminder)).execute();
this.location = null;
inputDialog.dismiss();
}
}
}
| 4,534 | 0.654168 | 0.653286 | 128 | 34.421875 | 26.678822 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 4 |
825341d47954a2ca9732ef66b2b06080396ba879 | 1,614,907,760,356 | c46c6d865836c912a7673161c9f3da2183a6b905 | /src/month_12/day14/Test54.java | 2d19e7cee5de2d6c9e1389ee72d9e81778abb269 | [] | no_license | ye-huanhuan/Leetcode | https://github.com/ye-huanhuan/Leetcode | 5afd215f033eb077338b38b8f2e52d230b0e7bca | 92a8277009161756b3dffdb2051c73f33466c669 | refs/heads/master | 2021-07-04T06:12:03.578000 | 2020-08-22T14:59:32 | 2020-08-22T14:59:32 | 156,846,356 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package month_12.day14;
public class Test54 {
}
/**
* 字符流中第一个不重复的字符
*/
class Solution06 {
//Insert one char from stringstream
private int[] tmp = new int[256];
int seq = 1;
public void Insert(char ch) {
if(tmp[ch] == 0) {
tmp[ch] = seq++;
} else {
tmp[ch] = -1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
int min = Integer.MAX_VALUE;
char ch = '#';
for(int i=0; i<tmp.length; i++) {
if(tmp[i] != -1 && tmp[i] != 0 && tmp[i] < min) {
min = tmp[i];
ch = (char)i;
}
}
return ch;
}
} | UTF-8 | Java | 745 | java | Test54.java | Java | [] | null | [] | package month_12.day14;
public class Test54 {
}
/**
* 字符流中第一个不重复的字符
*/
class Solution06 {
//Insert one char from stringstream
private int[] tmp = new int[256];
int seq = 1;
public void Insert(char ch) {
if(tmp[ch] == 0) {
tmp[ch] = seq++;
} else {
tmp[ch] = -1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
int min = Integer.MAX_VALUE;
char ch = '#';
for(int i=0; i<tmp.length; i++) {
if(tmp[i] != -1 && tmp[i] != 0 && tmp[i] < min) {
min = tmp[i];
ch = (char)i;
}
}
return ch;
}
} | 745 | 0.470097 | 0.446453 | 32 | 21.5 | 16.635805 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 4 |
396b7e596cb717fce6b72bba78b14c3eec58930d | 1,614,907,758,994 | b3a02d5f1f60cd584fbb6da1b823899607693f63 | /04_DB Frameworks_Hibernate+Spring Data/09_Spring Data Querying LAB/ShampooCompany/src/main/java/app/service/api/ShampoosService.java | e3fa198c97183bbe10d1fab67a35a11bc212fa70 | [
"MIT"
] | permissive | akkirilov/SoftUniProject | https://github.com/akkirilov/SoftUniProject | 20bf0543c9aaa0a33364daabfddd5f4c3e400ba2 | 709d2d1981c1bb6f1d652fe4101c1693f5afa376 | refs/heads/master | 2021-07-11T02:53:18.108000 | 2018-12-04T20:14:19 | 2018-12-04T20:14:19 | 79,428,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.service.api;
import app.model.BasicIngredient;
import app.model.ClassicLabel;
import app.model.ProductionBatch;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public interface ShampoosService<BasicShampoos, Long> extends ServiceInterface<BasicShampoos, Long> {
List<BasicShampoos> shampoosWithIngredient(String ingredientName);
void save(List<BasicShampoos> shampoosToSave);
List<BasicShampoos> findByBrand(String brandName);
List<BasicShampoos> findByBrandAndSize(String brandName, int size);
List<BasicShampoos> findBySizeAndLabel(int size, ClassicLabel label);
List<BasicShampoos> findByPriceGreaterThanOrderByBrandDesc(BigDecimal price);
List<BasicShampoos> findByPriceLowerThan(BigDecimal price);
List<BasicShampoos> findByLabelJPQL(ClassicLabel classicLabel);
List<BasicShampoos> findByIngredientInListJPQL(List<BasicIngredient> basicIngredients);
List<BasicShampoos> findByIngredientCountLowerThanNumberJPQL(Integer number);
List<BasicShampoos> findByBatchDateBeforeGivenDateJPQL(Date date);
List<BasicShampoos> findByIngredientsSumLowerThanGivenPriceJPQL(BigDecimal price);
List<BasicShampoos> findByBatchIdAndSubTitleDifferentThanGivenJPQL(ProductionBatch productionBatch,
String subTitle);
}
| UTF-8 | Java | 1,305 | java | ShampoosService.java | Java | [] | null | [] | package app.service.api;
import app.model.BasicIngredient;
import app.model.ClassicLabel;
import app.model.ProductionBatch;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public interface ShampoosService<BasicShampoos, Long> extends ServiceInterface<BasicShampoos, Long> {
List<BasicShampoos> shampoosWithIngredient(String ingredientName);
void save(List<BasicShampoos> shampoosToSave);
List<BasicShampoos> findByBrand(String brandName);
List<BasicShampoos> findByBrandAndSize(String brandName, int size);
List<BasicShampoos> findBySizeAndLabel(int size, ClassicLabel label);
List<BasicShampoos> findByPriceGreaterThanOrderByBrandDesc(BigDecimal price);
List<BasicShampoos> findByPriceLowerThan(BigDecimal price);
List<BasicShampoos> findByLabelJPQL(ClassicLabel classicLabel);
List<BasicShampoos> findByIngredientInListJPQL(List<BasicIngredient> basicIngredients);
List<BasicShampoos> findByIngredientCountLowerThanNumberJPQL(Integer number);
List<BasicShampoos> findByBatchDateBeforeGivenDateJPQL(Date date);
List<BasicShampoos> findByIngredientsSumLowerThanGivenPriceJPQL(BigDecimal price);
List<BasicShampoos> findByBatchIdAndSubTitleDifferentThanGivenJPQL(ProductionBatch productionBatch,
String subTitle);
}
| 1,305 | 0.823755 | 0.823755 | 57 | 21.877193 | 31.617268 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.719298 | false | false | 4 |
74401af11548085c06b1cb733d2a523bd9ab8ce8 | 26,826,365,757,741 | ea1ec6b517a6aa609daa9efcca170eed0fa8a6b3 | /src/exwrapper/ch/shaktipat/exwrapper/java/lang/ClassLoaderWrapper.java | f229b03c2de105adc7dc9ebbf73961fa3a7883e4 | [
"Apache-2.0"
] | permissive | liquid-mind/warp | https://github.com/liquid-mind/warp | c891a47016c60b6d512d009fd7ec94e7843074ce | 875a5624f71596b4f40b6133f890ac9626e21574 | refs/heads/master | 2021-06-25T10:12:52.371000 | 2016-10-31T13:35:03 | 2016-10-31T13:35:03 | 30,016,682 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ch.shaktipat.exwrapper.java.lang;
public class ClassLoaderWrapper
{
public static Class< ? > loadClass( ClassLoader loader, String name )
{
try
{
return loader.loadClass( name );
}
catch ( ClassNotFoundException e )
{
throw new ClassNotFoundExceptionWrapper( e );
}
}
}
| UTF-8 | Java | 300 | java | ClassLoaderWrapper.java | Java | [] | null | [] | package ch.shaktipat.exwrapper.java.lang;
public class ClassLoaderWrapper
{
public static Class< ? > loadClass( ClassLoader loader, String name )
{
try
{
return loader.loadClass( name );
}
catch ( ClassNotFoundException e )
{
throw new ClassNotFoundExceptionWrapper( e );
}
}
}
| 300 | 0.703333 | 0.703333 | 16 | 17.75 | 21.501453 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5625 | false | false | 4 |
11b6da0e4df070a581b7668e6edfd3aa18a3962a | 33,036,888,444,028 | 58e2faee7221a046d41a4faa4a407ea389dc032d | /src/main/java/server/service/ImgUploadService.java | 7eaf770d035bfb42b31b647f4f58ef06db8159d4 | [] | no_license | CuiShiHao-tech/txgs | https://github.com/CuiShiHao-tech/txgs | 9aa8af99d71df16695f95c57c9881b1ed69e8383 | 7b0f69eda0375dd8bf7f5a1ba2d4e472b0d95cd0 | refs/heads/master | 2022-12-10T18:19:24.154000 | 2020-09-07T02:21:18 | 2020-09-07T02:21:18 | 293,396,566 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server.service;
import server.db.primary.model.ImgUpload;
public interface ImgUploadService {
int updateByPrimaryKeySelective(ImgUpload record);
int insertSelective(ImgUpload record);
ImgUpload selectByPrimaryKey(Short id);
} | UTF-8 | Java | 249 | java | ImgUploadService.java | Java | [] | null | [] | package server.service;
import server.db.primary.model.ImgUpload;
public interface ImgUploadService {
int updateByPrimaryKeySelective(ImgUpload record);
int insertSelective(ImgUpload record);
ImgUpload selectByPrimaryKey(Short id);
} | 249 | 0.795181 | 0.795181 | 11 | 21.727272 | 20.828699 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 4 |
71bc6235a9ae7259357958ac04a2f0f8c35a4e37 | 26,422,638,844,428 | a41243908309fdba2594ca8e21bdc2e635c4fd39 | /Programming/Java/Class Projects/Java Introduction/MathTime2/DataSet.java | 4573410fbcc9e72defa590c3b5d47ec7ca0517d2 | [] | no_license | RazorThyOwn/Portfolio | https://github.com/RazorThyOwn/Portfolio | e55847fbf6d1f3964aa6da31aef2f1cb155324c1 | 3929eff0e60a00961d4c5eb066143f66a4ad7b9b | refs/heads/master | 2020-12-04T23:51:54.461000 | 2016-08-29T23:17:21 | 2016-08-29T23:17:21 | 66,887,010 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class DataSet
{
private int maxVal, minVal;
public DataSet()
{
maxVal = Integer.MIN_VALUE;
minVal = Integer.MAX_VALUE;
}
public void registerValue(int tmpVal)
{
//
minVal = Math.min(tmpVal, minVal);
maxVal = Math.max(tmpVal, maxVal);
}
public String toString()
{
return "Your max value is "+maxVal+" and your min value is "+minVal;
}
public int getRange()
{
return Math.abs(minVal)+Math.abs(maxVal);
}
} | UTF-8 | Java | 522 | java | DataSet.java | Java | [] | null | [] | public class DataSet
{
private int maxVal, minVal;
public DataSet()
{
maxVal = Integer.MIN_VALUE;
minVal = Integer.MAX_VALUE;
}
public void registerValue(int tmpVal)
{
//
minVal = Math.min(tmpVal, minVal);
maxVal = Math.max(tmpVal, maxVal);
}
public String toString()
{
return "Your max value is "+maxVal+" and your min value is "+minVal;
}
public int getRange()
{
return Math.abs(minVal)+Math.abs(maxVal);
}
} | 522 | 0.565134 | 0.565134 | 27 | 18.370371 | 19.432978 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false | 4 |
276eca52e94feadbcab2c83fc6a6d09f415f8a59 | 5,823,975,654,135 | 6400dad12891bbb8b4d351926a8cc6e2759af5db | /src/Simulation.java | 3c3eaa55974227bb8cf857da30d130c6ae411163 | [] | no_license | zoheiry/MMU | https://github.com/zoheiry/MMU | 0025e075aa3d2575f31f1aaac14f23e7df853191 | 4721a8dc55541868fa046e8bb2fc0350829dc180 | refs/heads/master | 2020-05-18T12:45:21.007000 | 2013-05-15T22:05:21 | 2013-05-15T22:05:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Simulation {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(split("10000000000100"));
}
public static ReferenceAndVirtualAddress split(String in) {
ReferenceAndVirtualAddress out = new ReferenceAndVirtualAddress();
out.reference = out.reference(in.substring(0,2));
out.virtual_address = in.substring(2, in.length());
return out;
}
public boolean conformation(String reference) {
}
}
class ReferenceAndVirtualAddress {
String reference;
String virtual_address;
public String toString() {
return reference + " | " + virtual_address;
}
public String reference(String reference) {
if (reference.equals("00"))
return "read";
if (reference.equals("01"))
return "execute";
return "write";
}
} | UTF-8 | Java | 906 | java | Simulation.java | Java | [] | null | [] | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Simulation {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(split("10000000000100"));
}
public static ReferenceAndVirtualAddress split(String in) {
ReferenceAndVirtualAddress out = new ReferenceAndVirtualAddress();
out.reference = out.reference(in.substring(0,2));
out.virtual_address = in.substring(2, in.length());
return out;
}
public boolean conformation(String reference) {
}
}
class ReferenceAndVirtualAddress {
String reference;
String virtual_address;
public String toString() {
return reference + " | " + virtual_address;
}
public String reference(String reference) {
if (reference.equals("00"))
return "read";
if (reference.equals("01"))
return "execute";
return "write";
}
} | 906 | 0.725166 | 0.701987 | 39 | 22.256411 | 21.675602 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 4 |
e83727d476e9aba4556d47ee9525788b1ec45e9c | 15,221,364,130,304 | 8157cc1fe105cb561c75ceb86eac6fc2e6e12a91 | /src/jconsole/Main.java | 0e06e0598730a89c5f73b1d2fe8c2c4610d2dc5a | [] | no_license | Adrian-Gonzalez-Madruga/JConsole | https://github.com/Adrian-Gonzalez-Madruga/JConsole | 40009e100bf97e3cf0afa1e6c364406554c1ec08 | d9bf94443eac7abc8971e16b2d970612b7a3b530 | refs/heads/master | 2020-08-04T10:08:43.571000 | 2019-10-01T13:23:14 | 2019-10-01T13:23:14 | 212,101,469 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jconsole;
import DLibX.DConsole;
import java.awt.Color;
public class Main {
public static void main(String[] args) {
int x = 0;
int y = 0;
int num = 7;
int[] xp = {0, 0, -num, num};
int[] yp = {-num, num, 0, 0};
Color[] c = {Color.GREEN, Color.RED, Color.BLUE, Color.YELLOW};
DConsole dc = new DConsole(800,800);
JConsole j = new JConsole(0);
while(true) {
dc.setPaint(new Color(0,0,0,10));
dc.fillRect(0,0,1000,1000);
dc.setPaint(Color.MAGENTA);
for(int q = 0; q < 4; q++) { // test button
if(j.isButtonPressed(q)) {
dc.setPaint(c[q]);
}
}
dc.fillEllipse(x, y, 35, 35);
x += (j.analogHorizontal(0) - 50) / 4; //test analog
y += (j.analogVertical(0) - 50) / 4;
for(int q = 0; q < 4; q++) { // test DPAD
if(j.isDpadPressed(q)) {
x += xp[q];
y += yp[q];
}
}
dc.redraw();
dc.pause(20);
}
}
}
| UTF-8 | Java | 1,347 | java | Main.java | Java | [] | null | [] | package jconsole;
import DLibX.DConsole;
import java.awt.Color;
public class Main {
public static void main(String[] args) {
int x = 0;
int y = 0;
int num = 7;
int[] xp = {0, 0, -num, num};
int[] yp = {-num, num, 0, 0};
Color[] c = {Color.GREEN, Color.RED, Color.BLUE, Color.YELLOW};
DConsole dc = new DConsole(800,800);
JConsole j = new JConsole(0);
while(true) {
dc.setPaint(new Color(0,0,0,10));
dc.fillRect(0,0,1000,1000);
dc.setPaint(Color.MAGENTA);
for(int q = 0; q < 4; q++) { // test button
if(j.isButtonPressed(q)) {
dc.setPaint(c[q]);
}
}
dc.fillEllipse(x, y, 35, 35);
x += (j.analogHorizontal(0) - 50) / 4; //test analog
y += (j.analogVertical(0) - 50) / 4;
for(int q = 0; q < 4; q++) { // test DPAD
if(j.isDpadPressed(q)) {
x += xp[q];
y += yp[q];
}
}
dc.redraw();
dc.pause(20);
}
}
}
| 1,347 | 0.363771 | 0.328879 | 52 | 23.865385 | 17.363787 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.865385 | false | false | 4 |
7878afec5863db64248c01d6f9c3b334201e14a6 | 33,646,773,830,367 | 84c4283e295db00e0d8ec906a6615804322d8693 | /java/hr-server/src/main/java/com/pdd/mapper/PositionMapper.java | f01c61f4864a733f899e17d9d4b56739ccfed844 | [] | no_license | xiaojiejie777/wow-hr | https://github.com/xiaojiejie777/wow-hr | d20633963570ff2121b84e2509a6ac6985f74587 | 0103bcbba32e2539927bd96f1598d3e0f2b884a9 | refs/heads/main | 2023-04-03T00:05:31.435000 | 2021-04-14T15:17:16 | 2021-04-14T15:17:16 | 357,904,031 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pdd.mapper;
import com.pdd.pojo.Position;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author pdd
* @since 2021-03-13
*/
public interface PositionMapper extends BaseMapper<Position> {
}
| UTF-8 | Java | 258 | java | PositionMapper.java | Java | [
{
"context": "r;\n\n/**\n * <p>\n * Mapper 接口\n * </p>\n *\n * @author pdd\n * @since 2021-03-13\n */\npublic interface Positio",
"end": 162,
"score": 0.999596357345581,
"start": 159,
"tag": "USERNAME",
"value": "pdd"
}
] | null | [] | package com.pdd.mapper;
import com.pdd.pojo.Position;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author pdd
* @since 2021-03-13
*/
public interface PositionMapper extends BaseMapper<Position> {
}
| 258 | 0.69685 | 0.665354 | 16 | 14.875 | 18.661039 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1875 | false | false | 4 |
80a5278f29bf3e25b835bbd52bfbafcfd02d41c9 | 4,337,917,013,647 | 69c18acfc7023f6145bd6d1f119f167d7c14be8d | /modules/iamrescue/src/iamrescue/communication/scenario/scenarios/IAMTeamCommunicationConfiguration.java | a91502f3829ef9f0bc56ee147ca9cb35a0ca27b8 | [] | no_license | xuzhikethinker/ISDM | https://github.com/xuzhikethinker/ISDM | a9bd67ed9241d9c6656d49f9ebfaf37779c8d507 | 303d545ed937af5a2df3f192f514558e5208d0fe | refs/heads/master | 2021-01-20T07:56:53.783000 | 2011-02-08T17:09:23 | 2011-02-08T17:09:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package iamrescue.communication.scenario.scenarios;
import iamrescue.communication.messages.MessageChannel;
import iamrescue.communication.messages.MessageChannelType;
import iamrescue.communication.scenario.ChannelDividerUtil;
import iamrescue.util.comparators.EntityIDComparator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Map.Entry;
import javolution.util.FastMap;
import javolution.util.FastSet;
import org.apache.log4j.Logger;
import rescuecore2.standard.entities.AmbulanceTeam;
import rescuecore2.standard.entities.FireBrigade;
import rescuecore2.standard.entities.FireStation;
import rescuecore2.standard.entities.PoliceForce;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;
public class IAMTeamCommunicationConfiguration {
public static final int RELATIVE_CENTRE_BANDIWDTH = 5;
private static Logger LOGGER = Logger
.getLogger(IAMTeamCommunicationConfiguration.class);
private List<MessageChannel> mainCommunicationChannels;
private List<MessageChannel> overflowChannels;
private Map<EntityID, MessageChannel> outputMainChannels;
private Map<EntityID, MessageChannel> outputOverflowChannels;
private Map<MessageChannel, List<EntityID>> channelSenders;
private Map<EntityID, List<MessageChannel>> subscribedChannels;
private Set<EntityID> centres;
private Set<EntityID> platoons;
private ConfigInfo configInfo;
private Set<EntityID> ignoredEntities = new FastSet<EntityID>();
private IAMTeamCommunicationConfiguration(ConfigInfo configInfo) {
this.configInfo = configInfo;
}
public void setIgnoredEntities(Collection<EntityID> ignored) {
ignoredEntities.clear();
ignoredEntities.addAll(ignored);
}
public Map<EntityID, MessageChannel> getOutputMainChannels() {
return outputMainChannels;
}
public Map<EntityID, MessageChannel> getOutputOverflowChannels() {
return outputOverflowChannels;
}
public Map<MessageChannel, List<EntityID>> getChannelSenders() {
return channelSenders;
}
public Map<EntityID, List<MessageChannel>> getSubscribedChannels() {
return subscribedChannels;
}
public Set<EntityID> getCentres() {
return centres;
}
public Set<EntityID> getPlatoons() {
return platoons;
}
public List<MessageChannel> getMainCommunicationChannels() {
return mainCommunicationChannels;
}
public List<MessageChannel> getOverflowChannels() {
return overflowChannels;
}
public static IAMTeamCommunicationConfiguration createTeam(
List<MessageChannel> mainChannels,
List<MessageChannel> overflowChannels,
List<MessageChannel> highPriorityTeamsToListen,
List<MessageChannel> lowPriorityTeamsToListen,
List<MessageChannel> veryLowPriorityTeamsToListen,
Collection<StandardEntity> entities, int maxPlatoonChannels,
int maxCentreChannels) {
ConfigInfo configInfo = new ConfigInfo(mainChannels, overflowChannels,
highPriorityTeamsToListen, lowPriorityTeamsToListen,
veryLowPriorityTeamsToListen, entities, maxPlatoonChannels,
maxCentreChannels);
IAMTeamCommunicationConfiguration config = new IAMTeamCommunicationConfiguration(
configInfo);
config.initialise();
return config;
}
public void reinitialise(Collection<EntityID> ignoredEntities) {
setIgnoredEntities(ignoredEntities);
initialise();
}
private void initialise() {
List<MessageChannel> mainChannels = configInfo.getMainChannels();
List<MessageChannel> overflowChannels = configInfo
.getOverflowChannels();
List<MessageChannel> highPriorityTeamsToListen = configInfo
.getHighPriorityTeamsToListen();
List<MessageChannel> lowPriorityTeamsToListen = configInfo
.getLowPriorityTeamsToListen();
List<MessageChannel> veryLowPriorityTeamsToListen = configInfo
.getVeryLowPriorityTeamsToListen();
int maxPlatoonChannels = configInfo.getMaxPlatoonChannels();
int maxCentreChannels = configInfo.getMaxCentreChannels();
Collection<StandardEntity> entities = new ArrayList<StandardEntity>();
for (StandardEntity se : configInfo.getEntities()) {
if (!ignoredEntities.contains(se.getID())) {
entities.add(se);
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Starting team configuration with main channels "
+ mainChannels + ", overflow channels: " + overflowChannels
+ ", high priority " + highPriorityTeamsToListen + ", low "
+ lowPriorityTeamsToListen + ", very low: "
+ veryLowPriorityTeamsToListen + ", max platoon: "
+ maxPlatoonChannels + ", maxCentre: " + maxCentreChannels
+ ", entities: " + entities);
}
this.mainCommunicationChannels = mainChannels;
this.centres = new FastSet<EntityID>();
this.subscribedChannels = new FastMap<EntityID, List<MessageChannel>>();
this.outputMainChannels = new FastMap<EntityID, MessageChannel>();
this.outputOverflowChannels = new FastMap<EntityID, MessageChannel>();
this.overflowChannels = overflowChannels;
List<StandardEntity> platoons = new ArrayList<StandardEntity>();
List<StandardEntity> centres = new ArrayList<StandardEntity>();
for (StandardEntity entity : entities) {
if (entity instanceof FireBrigade || entity instanceof PoliceForce
|| entity instanceof AmbulanceTeam) {
platoons.add(entity);
} else {
centres.add(entity);
}
}
Collections.sort(platoons, new EntityIDComparator());
Collections.sort(centres, new EntityIDComparator());
// How many normal platoon agents need to additionally listen to other
// teams.
int needToListen = 0;
int channelsEach = 1;
List<MessageChannel> channelsToListenTo = new ArrayList<MessageChannel>();
channelsToListenTo.addAll(highPriorityTeamsToListen);
channelsToListenTo.addAll(mainChannels);
channelsToListenTo.addAll(overflowChannels);
channelsToListenTo.addAll(lowPriorityTeamsToListen);
channelsToListenTo.addAll(veryLowPriorityTeamsToListen);
if (channelsToListenTo.size() > maxPlatoonChannels) {
// Only do centres if they are required.
if (centres.size() > 0) {
// There are centres
// First do high priority channels
int index = 0;
for (int i = 0; i < centres.size(); i++) {
List<MessageChannel> toSubscribe = new ArrayList<MessageChannel>();
while (toSubscribe.size() < maxCentreChannels
&& index < channelsToListenTo.size()) {
toSubscribe.add(channelsToListenTo.get(index++));
}
if (toSubscribe.size() > 0) {
if (toSubscribe.size() < maxCentreChannels) {
// Fill up with own channels if still space
Iterator<MessageChannel> iterator = mainChannels
.iterator();
while (iterator.hasNext()
&& toSubscribe.size() < maxCentreChannels) {
MessageChannel next = iterator.next();
if (!toSubscribe.contains(next)) {
toSubscribe.add(next);
}
}
}
EntityID id = centres.get(i).getID();
this.centres.add(id);
this.subscribedChannels.put(id, toSubscribe);
}
}
List<StandardEntity> newCentres = new ArrayList<StandardEntity>();
for (StandardEntity se : centres) {
if (this.centres.contains(se.getID())) {
newCentres.add(se);
}
}
/*for (StandardEntity se : centres) {
if (!newCentres.contains(se)) {
newCentres.add(se);
this.centres.add(se.getID());
this.subscribedChannels.put(se.getID(), mainChannels);
}
}*/
centres = newCentres;
int nextGoal = highPriorityTeamsToListen.size();
if (index < nextGoal) {
LOGGER.error("Could not get centres to listen "
+ "to all high priority channels.");
this.overflowChannels = new ArrayList<MessageChannel>();
} else {
nextGoal += mainChannels.size();
if (index < nextGoal) {
LOGGER.warn("Centre is not listening to all its own "
+ "team's channels. This can lead to "
+ "duplicate messages.");
this.overflowChannels = new ArrayList<MessageChannel>();
} else {
nextGoal += overflowChannels.size();
if (index < nextGoal) {
// Could not add all overflow channels
index -= (nextGoal - overflowChannels.size());
// index should now point to last overflow channel
// that
// was added
this.overflowChannels = new ArrayList<MessageChannel>();
for (int i = 0; i < index; i++) {
this.overflowChannels.add(overflowChannels
.get(i));
}
LOGGER.info("Added only " + index
+ " overflow channels.");
}
// No need to be more verbose now.
}
}
} else {
// No centres
// Assign several agents to just listen on the other channels
needToListen = highPriorityTeamsToListen.size();
channelsEach = 1;
if (needToListen > platoons.size()) {
// If too few agents, make one of them listen to all
channelsEach = needToListen;
needToListen = 1;
}
centres = new ArrayList<StandardEntity>();
// int counter = 0;
for (int i = 0; i < needToListen; i++) {
StandardEntity newCentre = platoons.remove(0);
centres.add(newCentre);
}
// No overflow channels in this case
overflowChannels = new ArrayList<MessageChannel>();
}
}
// Add any remaining centres to platoons
boolean added = false;
for (StandardEntity se : entities) {
if (!centres.contains(se)) {
if (!platoons.contains(se)) {
// Add to platoons
platoons.add(se);
added = true;
}
}
}
if (added) {
Collections.sort(platoons, new EntityIDComparator());
}
// Now work out assignments for main channel.
Map<MessageChannel, List<EntityID>> divideAgents = ChannelDividerUtil
.divideAgents(mainChannels, ChannelDividerUtil
.convertToIDs(platoons), ChannelDividerUtil
.convertToIDs(centres), RELATIVE_CENTRE_BANDIWDTH);
// Store this
for (Entry<MessageChannel, List<EntityID>> entry : divideAgents
.entrySet()) {
MessageChannel channel = entry.getKey();
List<EntityID> listeners = entry.getValue();
for (EntityID entityID : listeners) {
this.outputMainChannels.put(entityID, channel);
}
}
// Ensure centres are listening to their own allocated channels where
// possible
if (needToListen == 0) {
// Only do for real centres, otherwise next if statement takes care
// of this.
Map<EntityID, MessageChannel> needed = new FastMap<EntityID, MessageChannel>();
Map<EntityID, Set<MessageChannel>> surplus = new FastMap<EntityID, Set<MessageChannel>>();
for (EntityID centreID : this.centres) {
surplus.put(centreID, new FastSet<MessageChannel>());
MessageChannel messageChannel = this.outputMainChannels
.get(centreID);
needed.put(centreID, messageChannel);
Set<MessageChannel> mainCommsChannels = new FastSet<MessageChannel>();
mainCommsChannels.addAll(this.getMainCommunicationChannels());
boolean ok = false;
for (MessageChannel already : this.getSubscribedChannels().get(
centreID)) {
if (already.equals(messageChannel)) {
ok = true;
} else if (mainCommsChannels.contains(already)) {
surplus.get(centreID).add(already);
}
}
if (ok) {
needed.remove(centreID);
}
}
// Now swap
for (EntityID centreID : this.centres) {
MessageChannel neededChannel = needed.get(centreID);
if (neededChannel != null) {
for (EntityID otherCentreID : this.centres) {
Set<MessageChannel> otherSurplus = surplus
.get(otherCentreID);
MessageChannel toSwap = null;
if (otherSurplus.contains(neededChannel)) {
for (MessageChannel unneeded : surplus
.get(centreID)) {
if (!otherSurplus.contains(unneeded)
&& ((needed.get(otherCentreID) != null && needed
.get(otherCentreID).equals(
unneeded)) || !this
.getOutputMainChannels().get(
otherCentreID).equals(
unneeded))) {
toSwap = unneeded;
break;
}
}
if (toSwap != null) {
this.getSubscribedChannels().get(centreID).add(
neededChannel);
this.getSubscribedChannels().get(centreID)
.remove(toSwap);
this.getSubscribedChannels().get(otherCentreID)
.add(toSwap);
this.getSubscribedChannels().get(otherCentreID)
.remove(neededChannel);
needed.remove(centreID);
}
}
}
}
}
}
// Next, assign platoon centres (if any) to listen to other channels and
// their own
if (needToListen > 0) {
int counter = 0;
// Yes, there are platoon centres
for (int i = 0; i < centres.size(); i++) {
List<MessageChannel> listenTo = new ArrayList<MessageChannel>();
while (listenTo.size() < maxPlatoonChannels
&& counter < highPriorityTeamsToListen.size()
&& listenTo.size() < channelsEach) {
listenTo.add(highPriorityTeamsToListen.get(counter++));
}
if (listenTo.size() > 0 && listenTo.size() < maxPlatoonChannels) {
MessageChannel myChannel = this.outputMainChannels
.get(centres.get(i).getID());
// Add own channel if possible (for error detection)
listenTo.add(myChannel);
if (listenTo.size() < maxPlatoonChannels) {
List<MessageChannel> remaining = new ArrayList<MessageChannel>(
mainChannels);
Collections.shuffle(remaining, new Random(1234));
counter = 0;
while (listenTo.size() < maxPlatoonChannels) {
if (counter < remaining.size()) {
MessageChannel channel = remaining
.get(counter++);
if (channel.equals(myChannel)) {
// Already subscribed
continue;
} else {
// Add channel
listenTo.add(channel);
}
} else {
break;
}
}
}
}
this.centres.add(centres.get(i).getID());
this.subscribedChannels.put(centres.get(i).getID(), listenTo);
}
} // Done allocating channels to platoon centres
// Work out subscribed channels to listen to for everyone else
for (int i = 0; i < platoons.size(); i++) {
List<MessageChannel> list;
StandardEntity se = platoons.get(i);
if (maxPlatoonChannels >= mainChannels.size()) {
list = new ArrayList<MessageChannel>(mainChannels);
} else {
list = new ArrayList<MessageChannel>();
list.add(this.outputMainChannels.get(se.getID()));
int counter = 0;
List<MessageChannel> channels = new ArrayList<MessageChannel>();
channels.addAll(mainChannels);
Collections
.shuffle(channels, new Random(se.getID().getValue()));
for (int j = 1; j < maxPlatoonChannels; j++) {
MessageChannel messageChannel = channels.get(counter++);
if (messageChannel.equals(list.get(0))) {
j--;
continue;
}
list.add(messageChannel);
}
}
int counter = 0;
while (list.size() < maxPlatoonChannels) {
if (counter < highPriorityTeamsToListen.size()) {
list.add(highPriorityTeamsToListen.get(counter++));
} else {
int index = counter - highPriorityTeamsToListen.size();
if (index < lowPriorityTeamsToListen.size()) {
list.add(lowPriorityTeamsToListen.get(index));
counter++;
} else {
index = counter - highPriorityTeamsToListen.size()
- lowPriorityTeamsToListen.size();
if (index < veryLowPriorityTeamsToListen.size()) {
list.add(veryLowPriorityTeamsToListen.get(index));
counter++;
} else {
break;
}
}
}
}
this.subscribedChannels.put(se.getID(), list);
}
// Then, work out overflow channel allocations
Map<MessageChannel, List<EntityID>> overflowAssignment = ChannelDividerUtil
.divideAgents(this.overflowChannels, ChannelDividerUtil
.convertToIDs(platoons), new ArrayList<EntityID>(), 1);
// Save all in scenario
for (Entry<MessageChannel, List<EntityID>> entry : overflowAssignment
.entrySet()) {
MessageChannel channel = entry.getKey();
List<EntityID> listeners = entry.getValue();
for (EntityID entityID : listeners) {
this.outputOverflowChannels.put(entityID, channel);
}
}
this.platoons = new FastSet<EntityID>();
this.platoons.addAll(ChannelDividerUtil.convertToIDs(platoons));
this.updateChannelSenders();
}
/**
*
*/
private void updateChannelSenders() {
channelSenders = new FastMap<MessageChannel, List<EntityID>>();
for (int i = 0; i < 2; i++) {
Set<Entry<EntityID, MessageChannel>> entrySet = (i == 0) ? outputMainChannels
.entrySet()
: outputOverflowChannels.entrySet();
for (Entry<EntityID, MessageChannel> entry : entrySet) {
MessageChannel channel = entry.getValue();
EntityID sender = entry.getKey();
List<EntityID> list = channelSenders.get(channel);
if (list == null) {
list = new ArrayList<EntityID>();
channelSenders.put(channel, list);
}
list.add(sender);
}
}
}
public String toVerboseString() {
StringBuffer sb = new StringBuffer("Allocation: ");
sb.append('\n');
sb.append("\nPlatoons: ");
sb.append(platoons.toString());
sb.append('\n');
sb.append("\nCentres: ");
sb.append(centres.toString());
sb.append('\n');
sb.append("\nAllocation:");
sb.append('\n');
for (EntityID id : centres) {
MessageChannel overflow = outputOverflowChannels.get(id);
String overflowStr = overflow == null ? "none" : overflow
.getChannelNumber()
+ "";
sb.append("Centre " + id + " -> main: "
+ outputMainChannels.get(id).getChannelNumber()
+ ", overflow: " + overflowStr + "\n");
sb.append("Centre " + id + " <-");
List<MessageChannel> list = subscribedChannels.get(id);
for (MessageChannel messageChannel : list) {
sb.append(" " + messageChannel.getChannelNumber());
}
sb.append("\n");
}
for (EntityID id : platoons) {
MessageChannel overflow = outputOverflowChannels.get(id);
String overflowStr = overflow == null ? "none" : overflow
.getChannelNumber()
+ "";
sb.append("Platoon " + id + " -> main: "
+ outputMainChannels.get(id).getChannelNumber()
+ ", overflow: " + overflowStr + "\n");
sb.append("Platoon " + id + " <-");
List<MessageChannel> list = subscribedChannels.get(id);
for (MessageChannel messageChannel : list) {
sb.append(" " + messageChannel.getChannelNumber());
}
sb.append("\n");
}
sb.append("\nChannels:\n");
sb.append("\nMain Channels:\n");
for (MessageChannel channel : mainCommunicationChannels) {
sb.append(channel.getChannelNumber() + " <- "
+ channelSenders.get(channel) + "\n");
}
sb.append("\nOverflow Channels:\n");
for (MessageChannel channel : overflowChannels) {
sb.append("Channel " + channel.getChannelNumber() + " <- "
+ channelSenders.get(channel) + "\n");
}
return sb.toString();
}
public static void main(String[] args) {
List<StandardEntity> agents = new ArrayList<StandardEntity>();
agents.add(new FireBrigade(new EntityID(1)));
agents.add(new FireBrigade(new EntityID(2)));
agents.add(new FireBrigade(new EntityID(3)));
agents.add(new FireBrigade(new EntityID(4)));
agents.add(new FireStation(new EntityID(6)));
agents.add(new FireStation(new EntityID(5)));
agents.add(new FireStation(new EntityID(7)));
// MessageChannelConfig
MessageChannel mc1 = new MessageChannel(1, MessageChannelType.RADIO);
mc1.setBandwidth(1000);
mc1.setInputDropoutProbability(0.5);
MessageChannel mc2 = new MessageChannel(2, MessageChannelType.RADIO);
mc2.setBandwidth(900);
MessageChannel mc3 = new MessageChannel(3, MessageChannelType.RADIO);
mc3.setBandwidth(800);
MessageChannel other1 = new MessageChannel(4, MessageChannelType.RADIO);
other1.setBandwidth(800);
MessageChannel other2 = new MessageChannel(5, MessageChannelType.RADIO);
other2.setBandwidth(750);
MessageChannel other3 = new MessageChannel(6, MessageChannelType.RADIO);
other3.setBandwidth(800);
MessageChannel other4 = new MessageChannel(7, MessageChannelType.RADIO);
other4.setBandwidth(750);
List<MessageChannel> main = new ArrayList<MessageChannel>();
main.add(mc1);
main.add(mc2);
List<MessageChannel> overflow = new ArrayList<MessageChannel>();
overflow.add(mc3);
List<MessageChannel> other = new ArrayList<MessageChannel>();
other.add(other1);
other.add(other2);
List<MessageChannel> yetother = new ArrayList<MessageChannel>();
yetother.add(other3);
yetother.add(other4);
IAMTeamCommunicationConfiguration team = IAMTeamCommunicationConfiguration
.createTeam(main, overflow, other, yetother,
new ArrayList<MessageChannel>(), agents, 1, 3);
System.out.println(team.toVerboseString());
team.reinitialise(Collections.singleton(new EntityID(7)));
System.out.println(team.toVerboseString());
}
private static class ConfigInfo {
private List<MessageChannel> mainChannels;
private List<MessageChannel> overflowChannels;
private List<MessageChannel> highPriorityTeamsToListen;
private List<MessageChannel> lowPriorityTeamsToListen;
private List<MessageChannel> veryLowPriorityTeamsToListen;
private Collection<StandardEntity> entities;
private int maxPlatoonChannels;
private int maxCentreChannels;
public ConfigInfo(List<MessageChannel> mainChannels,
List<MessageChannel> overflowChannels,
List<MessageChannel> highPriorityTeamsToListen,
List<MessageChannel> lowPriorityTeamsToListen,
List<MessageChannel> veryLowPriorityTeamsToListen,
Collection<StandardEntity> entities, int maxPlatoonChannels,
int maxCentreChannels) {
this.mainChannels = mainChannels;
this.overflowChannels = overflowChannels;
this.highPriorityTeamsToListen = highPriorityTeamsToListen;
this.lowPriorityTeamsToListen = lowPriorityTeamsToListen;
this.veryLowPriorityTeamsToListen = veryLowPriorityTeamsToListen;
this.entities = entities;
this.maxPlatoonChannels = maxPlatoonChannels;
this.maxCentreChannels = maxCentreChannels;
}
/**
* @return the mainChannels
*/
public List<MessageChannel> getMainChannels() {
return Collections.unmodifiableList(mainChannels);
}
/**
* @return the overflowChannels
*/
public List<MessageChannel> getOverflowChannels() {
return Collections.unmodifiableList(overflowChannels);
}
/**
* @return the highPriorityTeamsToListen
*/
public List<MessageChannel> getHighPriorityTeamsToListen() {
return Collections.unmodifiableList(highPriorityTeamsToListen);
}
/**
* @return the lowPriorityTeamsToListen
*/
public List<MessageChannel> getLowPriorityTeamsToListen() {
return Collections.unmodifiableList(lowPriorityTeamsToListen);
}
/**
* @return the veryLowPriorityTeamsToListen
*/
public List<MessageChannel> getVeryLowPriorityTeamsToListen() {
return Collections.unmodifiableList(veryLowPriorityTeamsToListen);
}
/**
* @return the entities
*/
public Collection<StandardEntity> getEntities() {
return Collections.unmodifiableCollection(entities);
}
/**
* @return the maxPlatoonChannels
*/
public int getMaxPlatoonChannels() {
return maxPlatoonChannels;
}
/**
* @return the maxCentreChannels
*/
public int getMaxCentreChannels() {
return maxCentreChannels;
}
}
} | UTF-8 | Java | 23,294 | java | IAMTeamCommunicationConfiguration.java | Java | [] | null | [] | package iamrescue.communication.scenario.scenarios;
import iamrescue.communication.messages.MessageChannel;
import iamrescue.communication.messages.MessageChannelType;
import iamrescue.communication.scenario.ChannelDividerUtil;
import iamrescue.util.comparators.EntityIDComparator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Map.Entry;
import javolution.util.FastMap;
import javolution.util.FastSet;
import org.apache.log4j.Logger;
import rescuecore2.standard.entities.AmbulanceTeam;
import rescuecore2.standard.entities.FireBrigade;
import rescuecore2.standard.entities.FireStation;
import rescuecore2.standard.entities.PoliceForce;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;
public class IAMTeamCommunicationConfiguration {
public static final int RELATIVE_CENTRE_BANDIWDTH = 5;
private static Logger LOGGER = Logger
.getLogger(IAMTeamCommunicationConfiguration.class);
private List<MessageChannel> mainCommunicationChannels;
private List<MessageChannel> overflowChannels;
private Map<EntityID, MessageChannel> outputMainChannels;
private Map<EntityID, MessageChannel> outputOverflowChannels;
private Map<MessageChannel, List<EntityID>> channelSenders;
private Map<EntityID, List<MessageChannel>> subscribedChannels;
private Set<EntityID> centres;
private Set<EntityID> platoons;
private ConfigInfo configInfo;
private Set<EntityID> ignoredEntities = new FastSet<EntityID>();
private IAMTeamCommunicationConfiguration(ConfigInfo configInfo) {
this.configInfo = configInfo;
}
public void setIgnoredEntities(Collection<EntityID> ignored) {
ignoredEntities.clear();
ignoredEntities.addAll(ignored);
}
public Map<EntityID, MessageChannel> getOutputMainChannels() {
return outputMainChannels;
}
public Map<EntityID, MessageChannel> getOutputOverflowChannels() {
return outputOverflowChannels;
}
public Map<MessageChannel, List<EntityID>> getChannelSenders() {
return channelSenders;
}
public Map<EntityID, List<MessageChannel>> getSubscribedChannels() {
return subscribedChannels;
}
public Set<EntityID> getCentres() {
return centres;
}
public Set<EntityID> getPlatoons() {
return platoons;
}
public List<MessageChannel> getMainCommunicationChannels() {
return mainCommunicationChannels;
}
public List<MessageChannel> getOverflowChannels() {
return overflowChannels;
}
public static IAMTeamCommunicationConfiguration createTeam(
List<MessageChannel> mainChannels,
List<MessageChannel> overflowChannels,
List<MessageChannel> highPriorityTeamsToListen,
List<MessageChannel> lowPriorityTeamsToListen,
List<MessageChannel> veryLowPriorityTeamsToListen,
Collection<StandardEntity> entities, int maxPlatoonChannels,
int maxCentreChannels) {
ConfigInfo configInfo = new ConfigInfo(mainChannels, overflowChannels,
highPriorityTeamsToListen, lowPriorityTeamsToListen,
veryLowPriorityTeamsToListen, entities, maxPlatoonChannels,
maxCentreChannels);
IAMTeamCommunicationConfiguration config = new IAMTeamCommunicationConfiguration(
configInfo);
config.initialise();
return config;
}
public void reinitialise(Collection<EntityID> ignoredEntities) {
setIgnoredEntities(ignoredEntities);
initialise();
}
private void initialise() {
List<MessageChannel> mainChannels = configInfo.getMainChannels();
List<MessageChannel> overflowChannels = configInfo
.getOverflowChannels();
List<MessageChannel> highPriorityTeamsToListen = configInfo
.getHighPriorityTeamsToListen();
List<MessageChannel> lowPriorityTeamsToListen = configInfo
.getLowPriorityTeamsToListen();
List<MessageChannel> veryLowPriorityTeamsToListen = configInfo
.getVeryLowPriorityTeamsToListen();
int maxPlatoonChannels = configInfo.getMaxPlatoonChannels();
int maxCentreChannels = configInfo.getMaxCentreChannels();
Collection<StandardEntity> entities = new ArrayList<StandardEntity>();
for (StandardEntity se : configInfo.getEntities()) {
if (!ignoredEntities.contains(se.getID())) {
entities.add(se);
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Starting team configuration with main channels "
+ mainChannels + ", overflow channels: " + overflowChannels
+ ", high priority " + highPriorityTeamsToListen + ", low "
+ lowPriorityTeamsToListen + ", very low: "
+ veryLowPriorityTeamsToListen + ", max platoon: "
+ maxPlatoonChannels + ", maxCentre: " + maxCentreChannels
+ ", entities: " + entities);
}
this.mainCommunicationChannels = mainChannels;
this.centres = new FastSet<EntityID>();
this.subscribedChannels = new FastMap<EntityID, List<MessageChannel>>();
this.outputMainChannels = new FastMap<EntityID, MessageChannel>();
this.outputOverflowChannels = new FastMap<EntityID, MessageChannel>();
this.overflowChannels = overflowChannels;
List<StandardEntity> platoons = new ArrayList<StandardEntity>();
List<StandardEntity> centres = new ArrayList<StandardEntity>();
for (StandardEntity entity : entities) {
if (entity instanceof FireBrigade || entity instanceof PoliceForce
|| entity instanceof AmbulanceTeam) {
platoons.add(entity);
} else {
centres.add(entity);
}
}
Collections.sort(platoons, new EntityIDComparator());
Collections.sort(centres, new EntityIDComparator());
// How many normal platoon agents need to additionally listen to other
// teams.
int needToListen = 0;
int channelsEach = 1;
List<MessageChannel> channelsToListenTo = new ArrayList<MessageChannel>();
channelsToListenTo.addAll(highPriorityTeamsToListen);
channelsToListenTo.addAll(mainChannels);
channelsToListenTo.addAll(overflowChannels);
channelsToListenTo.addAll(lowPriorityTeamsToListen);
channelsToListenTo.addAll(veryLowPriorityTeamsToListen);
if (channelsToListenTo.size() > maxPlatoonChannels) {
// Only do centres if they are required.
if (centres.size() > 0) {
// There are centres
// First do high priority channels
int index = 0;
for (int i = 0; i < centres.size(); i++) {
List<MessageChannel> toSubscribe = new ArrayList<MessageChannel>();
while (toSubscribe.size() < maxCentreChannels
&& index < channelsToListenTo.size()) {
toSubscribe.add(channelsToListenTo.get(index++));
}
if (toSubscribe.size() > 0) {
if (toSubscribe.size() < maxCentreChannels) {
// Fill up with own channels if still space
Iterator<MessageChannel> iterator = mainChannels
.iterator();
while (iterator.hasNext()
&& toSubscribe.size() < maxCentreChannels) {
MessageChannel next = iterator.next();
if (!toSubscribe.contains(next)) {
toSubscribe.add(next);
}
}
}
EntityID id = centres.get(i).getID();
this.centres.add(id);
this.subscribedChannels.put(id, toSubscribe);
}
}
List<StandardEntity> newCentres = new ArrayList<StandardEntity>();
for (StandardEntity se : centres) {
if (this.centres.contains(se.getID())) {
newCentres.add(se);
}
}
/*for (StandardEntity se : centres) {
if (!newCentres.contains(se)) {
newCentres.add(se);
this.centres.add(se.getID());
this.subscribedChannels.put(se.getID(), mainChannels);
}
}*/
centres = newCentres;
int nextGoal = highPriorityTeamsToListen.size();
if (index < nextGoal) {
LOGGER.error("Could not get centres to listen "
+ "to all high priority channels.");
this.overflowChannels = new ArrayList<MessageChannel>();
} else {
nextGoal += mainChannels.size();
if (index < nextGoal) {
LOGGER.warn("Centre is not listening to all its own "
+ "team's channels. This can lead to "
+ "duplicate messages.");
this.overflowChannels = new ArrayList<MessageChannel>();
} else {
nextGoal += overflowChannels.size();
if (index < nextGoal) {
// Could not add all overflow channels
index -= (nextGoal - overflowChannels.size());
// index should now point to last overflow channel
// that
// was added
this.overflowChannels = new ArrayList<MessageChannel>();
for (int i = 0; i < index; i++) {
this.overflowChannels.add(overflowChannels
.get(i));
}
LOGGER.info("Added only " + index
+ " overflow channels.");
}
// No need to be more verbose now.
}
}
} else {
// No centres
// Assign several agents to just listen on the other channels
needToListen = highPriorityTeamsToListen.size();
channelsEach = 1;
if (needToListen > platoons.size()) {
// If too few agents, make one of them listen to all
channelsEach = needToListen;
needToListen = 1;
}
centres = new ArrayList<StandardEntity>();
// int counter = 0;
for (int i = 0; i < needToListen; i++) {
StandardEntity newCentre = platoons.remove(0);
centres.add(newCentre);
}
// No overflow channels in this case
overflowChannels = new ArrayList<MessageChannel>();
}
}
// Add any remaining centres to platoons
boolean added = false;
for (StandardEntity se : entities) {
if (!centres.contains(se)) {
if (!platoons.contains(se)) {
// Add to platoons
platoons.add(se);
added = true;
}
}
}
if (added) {
Collections.sort(platoons, new EntityIDComparator());
}
// Now work out assignments for main channel.
Map<MessageChannel, List<EntityID>> divideAgents = ChannelDividerUtil
.divideAgents(mainChannels, ChannelDividerUtil
.convertToIDs(platoons), ChannelDividerUtil
.convertToIDs(centres), RELATIVE_CENTRE_BANDIWDTH);
// Store this
for (Entry<MessageChannel, List<EntityID>> entry : divideAgents
.entrySet()) {
MessageChannel channel = entry.getKey();
List<EntityID> listeners = entry.getValue();
for (EntityID entityID : listeners) {
this.outputMainChannels.put(entityID, channel);
}
}
// Ensure centres are listening to their own allocated channels where
// possible
if (needToListen == 0) {
// Only do for real centres, otherwise next if statement takes care
// of this.
Map<EntityID, MessageChannel> needed = new FastMap<EntityID, MessageChannel>();
Map<EntityID, Set<MessageChannel>> surplus = new FastMap<EntityID, Set<MessageChannel>>();
for (EntityID centreID : this.centres) {
surplus.put(centreID, new FastSet<MessageChannel>());
MessageChannel messageChannel = this.outputMainChannels
.get(centreID);
needed.put(centreID, messageChannel);
Set<MessageChannel> mainCommsChannels = new FastSet<MessageChannel>();
mainCommsChannels.addAll(this.getMainCommunicationChannels());
boolean ok = false;
for (MessageChannel already : this.getSubscribedChannels().get(
centreID)) {
if (already.equals(messageChannel)) {
ok = true;
} else if (mainCommsChannels.contains(already)) {
surplus.get(centreID).add(already);
}
}
if (ok) {
needed.remove(centreID);
}
}
// Now swap
for (EntityID centreID : this.centres) {
MessageChannel neededChannel = needed.get(centreID);
if (neededChannel != null) {
for (EntityID otherCentreID : this.centres) {
Set<MessageChannel> otherSurplus = surplus
.get(otherCentreID);
MessageChannel toSwap = null;
if (otherSurplus.contains(neededChannel)) {
for (MessageChannel unneeded : surplus
.get(centreID)) {
if (!otherSurplus.contains(unneeded)
&& ((needed.get(otherCentreID) != null && needed
.get(otherCentreID).equals(
unneeded)) || !this
.getOutputMainChannels().get(
otherCentreID).equals(
unneeded))) {
toSwap = unneeded;
break;
}
}
if (toSwap != null) {
this.getSubscribedChannels().get(centreID).add(
neededChannel);
this.getSubscribedChannels().get(centreID)
.remove(toSwap);
this.getSubscribedChannels().get(otherCentreID)
.add(toSwap);
this.getSubscribedChannels().get(otherCentreID)
.remove(neededChannel);
needed.remove(centreID);
}
}
}
}
}
}
// Next, assign platoon centres (if any) to listen to other channels and
// their own
if (needToListen > 0) {
int counter = 0;
// Yes, there are platoon centres
for (int i = 0; i < centres.size(); i++) {
List<MessageChannel> listenTo = new ArrayList<MessageChannel>();
while (listenTo.size() < maxPlatoonChannels
&& counter < highPriorityTeamsToListen.size()
&& listenTo.size() < channelsEach) {
listenTo.add(highPriorityTeamsToListen.get(counter++));
}
if (listenTo.size() > 0 && listenTo.size() < maxPlatoonChannels) {
MessageChannel myChannel = this.outputMainChannels
.get(centres.get(i).getID());
// Add own channel if possible (for error detection)
listenTo.add(myChannel);
if (listenTo.size() < maxPlatoonChannels) {
List<MessageChannel> remaining = new ArrayList<MessageChannel>(
mainChannels);
Collections.shuffle(remaining, new Random(1234));
counter = 0;
while (listenTo.size() < maxPlatoonChannels) {
if (counter < remaining.size()) {
MessageChannel channel = remaining
.get(counter++);
if (channel.equals(myChannel)) {
// Already subscribed
continue;
} else {
// Add channel
listenTo.add(channel);
}
} else {
break;
}
}
}
}
this.centres.add(centres.get(i).getID());
this.subscribedChannels.put(centres.get(i).getID(), listenTo);
}
} // Done allocating channels to platoon centres
// Work out subscribed channels to listen to for everyone else
for (int i = 0; i < platoons.size(); i++) {
List<MessageChannel> list;
StandardEntity se = platoons.get(i);
if (maxPlatoonChannels >= mainChannels.size()) {
list = new ArrayList<MessageChannel>(mainChannels);
} else {
list = new ArrayList<MessageChannel>();
list.add(this.outputMainChannels.get(se.getID()));
int counter = 0;
List<MessageChannel> channels = new ArrayList<MessageChannel>();
channels.addAll(mainChannels);
Collections
.shuffle(channels, new Random(se.getID().getValue()));
for (int j = 1; j < maxPlatoonChannels; j++) {
MessageChannel messageChannel = channels.get(counter++);
if (messageChannel.equals(list.get(0))) {
j--;
continue;
}
list.add(messageChannel);
}
}
int counter = 0;
while (list.size() < maxPlatoonChannels) {
if (counter < highPriorityTeamsToListen.size()) {
list.add(highPriorityTeamsToListen.get(counter++));
} else {
int index = counter - highPriorityTeamsToListen.size();
if (index < lowPriorityTeamsToListen.size()) {
list.add(lowPriorityTeamsToListen.get(index));
counter++;
} else {
index = counter - highPriorityTeamsToListen.size()
- lowPriorityTeamsToListen.size();
if (index < veryLowPriorityTeamsToListen.size()) {
list.add(veryLowPriorityTeamsToListen.get(index));
counter++;
} else {
break;
}
}
}
}
this.subscribedChannels.put(se.getID(), list);
}
// Then, work out overflow channel allocations
Map<MessageChannel, List<EntityID>> overflowAssignment = ChannelDividerUtil
.divideAgents(this.overflowChannels, ChannelDividerUtil
.convertToIDs(platoons), new ArrayList<EntityID>(), 1);
// Save all in scenario
for (Entry<MessageChannel, List<EntityID>> entry : overflowAssignment
.entrySet()) {
MessageChannel channel = entry.getKey();
List<EntityID> listeners = entry.getValue();
for (EntityID entityID : listeners) {
this.outputOverflowChannels.put(entityID, channel);
}
}
this.platoons = new FastSet<EntityID>();
this.platoons.addAll(ChannelDividerUtil.convertToIDs(platoons));
this.updateChannelSenders();
}
/**
*
*/
private void updateChannelSenders() {
channelSenders = new FastMap<MessageChannel, List<EntityID>>();
for (int i = 0; i < 2; i++) {
Set<Entry<EntityID, MessageChannel>> entrySet = (i == 0) ? outputMainChannels
.entrySet()
: outputOverflowChannels.entrySet();
for (Entry<EntityID, MessageChannel> entry : entrySet) {
MessageChannel channel = entry.getValue();
EntityID sender = entry.getKey();
List<EntityID> list = channelSenders.get(channel);
if (list == null) {
list = new ArrayList<EntityID>();
channelSenders.put(channel, list);
}
list.add(sender);
}
}
}
public String toVerboseString() {
StringBuffer sb = new StringBuffer("Allocation: ");
sb.append('\n');
sb.append("\nPlatoons: ");
sb.append(platoons.toString());
sb.append('\n');
sb.append("\nCentres: ");
sb.append(centres.toString());
sb.append('\n');
sb.append("\nAllocation:");
sb.append('\n');
for (EntityID id : centres) {
MessageChannel overflow = outputOverflowChannels.get(id);
String overflowStr = overflow == null ? "none" : overflow
.getChannelNumber()
+ "";
sb.append("Centre " + id + " -> main: "
+ outputMainChannels.get(id).getChannelNumber()
+ ", overflow: " + overflowStr + "\n");
sb.append("Centre " + id + " <-");
List<MessageChannel> list = subscribedChannels.get(id);
for (MessageChannel messageChannel : list) {
sb.append(" " + messageChannel.getChannelNumber());
}
sb.append("\n");
}
for (EntityID id : platoons) {
MessageChannel overflow = outputOverflowChannels.get(id);
String overflowStr = overflow == null ? "none" : overflow
.getChannelNumber()
+ "";
sb.append("Platoon " + id + " -> main: "
+ outputMainChannels.get(id).getChannelNumber()
+ ", overflow: " + overflowStr + "\n");
sb.append("Platoon " + id + " <-");
List<MessageChannel> list = subscribedChannels.get(id);
for (MessageChannel messageChannel : list) {
sb.append(" " + messageChannel.getChannelNumber());
}
sb.append("\n");
}
sb.append("\nChannels:\n");
sb.append("\nMain Channels:\n");
for (MessageChannel channel : mainCommunicationChannels) {
sb.append(channel.getChannelNumber() + " <- "
+ channelSenders.get(channel) + "\n");
}
sb.append("\nOverflow Channels:\n");
for (MessageChannel channel : overflowChannels) {
sb.append("Channel " + channel.getChannelNumber() + " <- "
+ channelSenders.get(channel) + "\n");
}
return sb.toString();
}
public static void main(String[] args) {
List<StandardEntity> agents = new ArrayList<StandardEntity>();
agents.add(new FireBrigade(new EntityID(1)));
agents.add(new FireBrigade(new EntityID(2)));
agents.add(new FireBrigade(new EntityID(3)));
agents.add(new FireBrigade(new EntityID(4)));
agents.add(new FireStation(new EntityID(6)));
agents.add(new FireStation(new EntityID(5)));
agents.add(new FireStation(new EntityID(7)));
// MessageChannelConfig
MessageChannel mc1 = new MessageChannel(1, MessageChannelType.RADIO);
mc1.setBandwidth(1000);
mc1.setInputDropoutProbability(0.5);
MessageChannel mc2 = new MessageChannel(2, MessageChannelType.RADIO);
mc2.setBandwidth(900);
MessageChannel mc3 = new MessageChannel(3, MessageChannelType.RADIO);
mc3.setBandwidth(800);
MessageChannel other1 = new MessageChannel(4, MessageChannelType.RADIO);
other1.setBandwidth(800);
MessageChannel other2 = new MessageChannel(5, MessageChannelType.RADIO);
other2.setBandwidth(750);
MessageChannel other3 = new MessageChannel(6, MessageChannelType.RADIO);
other3.setBandwidth(800);
MessageChannel other4 = new MessageChannel(7, MessageChannelType.RADIO);
other4.setBandwidth(750);
List<MessageChannel> main = new ArrayList<MessageChannel>();
main.add(mc1);
main.add(mc2);
List<MessageChannel> overflow = new ArrayList<MessageChannel>();
overflow.add(mc3);
List<MessageChannel> other = new ArrayList<MessageChannel>();
other.add(other1);
other.add(other2);
List<MessageChannel> yetother = new ArrayList<MessageChannel>();
yetother.add(other3);
yetother.add(other4);
IAMTeamCommunicationConfiguration team = IAMTeamCommunicationConfiguration
.createTeam(main, overflow, other, yetother,
new ArrayList<MessageChannel>(), agents, 1, 3);
System.out.println(team.toVerboseString());
team.reinitialise(Collections.singleton(new EntityID(7)));
System.out.println(team.toVerboseString());
}
private static class ConfigInfo {
private List<MessageChannel> mainChannels;
private List<MessageChannel> overflowChannels;
private List<MessageChannel> highPriorityTeamsToListen;
private List<MessageChannel> lowPriorityTeamsToListen;
private List<MessageChannel> veryLowPriorityTeamsToListen;
private Collection<StandardEntity> entities;
private int maxPlatoonChannels;
private int maxCentreChannels;
public ConfigInfo(List<MessageChannel> mainChannels,
List<MessageChannel> overflowChannels,
List<MessageChannel> highPriorityTeamsToListen,
List<MessageChannel> lowPriorityTeamsToListen,
List<MessageChannel> veryLowPriorityTeamsToListen,
Collection<StandardEntity> entities, int maxPlatoonChannels,
int maxCentreChannels) {
this.mainChannels = mainChannels;
this.overflowChannels = overflowChannels;
this.highPriorityTeamsToListen = highPriorityTeamsToListen;
this.lowPriorityTeamsToListen = lowPriorityTeamsToListen;
this.veryLowPriorityTeamsToListen = veryLowPriorityTeamsToListen;
this.entities = entities;
this.maxPlatoonChannels = maxPlatoonChannels;
this.maxCentreChannels = maxCentreChannels;
}
/**
* @return the mainChannels
*/
public List<MessageChannel> getMainChannels() {
return Collections.unmodifiableList(mainChannels);
}
/**
* @return the overflowChannels
*/
public List<MessageChannel> getOverflowChannels() {
return Collections.unmodifiableList(overflowChannels);
}
/**
* @return the highPriorityTeamsToListen
*/
public List<MessageChannel> getHighPriorityTeamsToListen() {
return Collections.unmodifiableList(highPriorityTeamsToListen);
}
/**
* @return the lowPriorityTeamsToListen
*/
public List<MessageChannel> getLowPriorityTeamsToListen() {
return Collections.unmodifiableList(lowPriorityTeamsToListen);
}
/**
* @return the veryLowPriorityTeamsToListen
*/
public List<MessageChannel> getVeryLowPriorityTeamsToListen() {
return Collections.unmodifiableList(veryLowPriorityTeamsToListen);
}
/**
* @return the entities
*/
public Collection<StandardEntity> getEntities() {
return Collections.unmodifiableCollection(entities);
}
/**
* @return the maxPlatoonChannels
*/
public int getMaxPlatoonChannels() {
return maxPlatoonChannels;
}
/**
* @return the maxCentreChannels
*/
public int getMaxCentreChannels() {
return maxCentreChannels;
}
}
} | 23,294 | 0.697261 | 0.692882 | 720 | 31.354166 | 23.172503 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.686111 | false | false | 4 |
833ba8c80a1a05cbfb8a03e201f71fcf3a51dae5 | 30,434,138,305,036 | 1c85e882774b3536a19db5c5e6e07c9caebf8f55 | /app/src/main/java/com/accentype/android/softkeyboard/Themes.java | e84d6874cb8af5869bf60d7c06f63eca8df06c07 | [] | no_license | zeerakabb/zeerakabb | https://github.com/zeerakabb/zeerakabb | ac8833633c46aa6d2b4d8272a630398f69c76b68 | a3852026405c98b1a1e97df86fcee6a54ec42c15 | refs/heads/main | 2023-09-02T17:58:46.779000 | 2021-11-05T09:16:08 | 2021-11-05T09:16:08 | 424,870,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.accentype.android.softkeyboard;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdViewAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.ads.MaxAdView;
import com.google.android.gms.ads.mediation.Adapter;
import java.util.ArrayList;
public class Themes extends AppCompatActivity implements MaxAdViewAdListener {
// ListView lv_themes;
public static final String MY_PREFS_NAME = "MyPrefsFile";
//
// String mtitle[] = {"Red", "Blue", "Green", "Indigo", "Violet", };
// String subtitle[] = {"Red Color", "Blue Color", "Green Rainbow" , "Indigo Rainbow Color", "Violet Raibow Color"};
// int Images[] = {R.color.red, R.color.blue, R.color.green, R.color.indigo, R.color.violet};
//
// @Override
// protected void onCreate (Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.themes);
// lv_themes = findViewById(R.id.listThemes1);
//
// myadapter adapter = new myadapter(this, mtitle, subtitle, Images);
// lv_themes.setAdapter(adapter);
//// lv_themes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//// @Override
//// public void onItemClick(AdapterView<?> parent, View view, int position, long id)
//// {
//// if (position == 0)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// }
//
// //});
// lv_themes.setOnItemClickListener(this);
//
//// lv_themes.setOnItemClickListener(new AdapterView.OnItemClickListener()
//// {
//// @Override
//// public void onItemClick(AdapterView<?> parent, View view, int position, long id)
//// {
//// if (position == 0)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// if (position == 1)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 1);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// }
//// });
//// }
//
//
//
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
//
// }
//
// class myadapter extends ArrayAdapter
// {
// Context context;
// String rtitle[];
// String Stitle[];
// int rimages[];
//
//
// myadapter(Context c, String title[], String subtitle[], int images[])
// {
// super(c, R.layout.row1, R.id.textview1, title);
// this.context = c;
// this.rtitle = title;
// this.Stitle = subtitle;
// this.rimages = images;
// }
// @NonNull
// @Override
// public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
// {
// LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View row = layoutInflater.inflate(R.layout.row1, parent, false);
// ImageView img = row.findViewById(R.id.Image_colors_images1);
// TextView myTitle = row.findViewById(R.id.textview1);
// TextView subTitle = row.findViewById(R.id.textview2);
// img.setImageResource(rimages[position]);
// myTitle.setText(rtitle[position]);
// subTitle.setText(Stitle[position]);
// return row;
// }
// }
// @Override
// public void onBackPressed() {
// super.onBackPressed();
// Intent in =new Intent(getApplicationContext(),DashBoardActivity.class);
// startActivity(in);
// }
ListView listview;
MaxAdView adView;
String mtitle[] = {"Red Color", "blue", "indigo", "violet", "green"};
String subtitle[] = {"Change Themes Red", "Change Themes blue", "Change Themes indigo ", "Change Themes violet", "Change Themes green"};
int Images[] = {R.color.red, R.color.blue, R.color.indigo, R.color.violet, R.color.green};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.themes);
listview = findViewById(R.id.listThemes1);
adView=findViewById(R.id.bannerThemeID);
adView.setListener(this);
adView.loadAd();
myadapter adapter = new myadapter(this, mtitle, subtitle, Images);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if (position==0)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 0);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==1)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 1);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==2)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 2);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==3)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 3);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==4)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 4);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onAdExpanded(MaxAd ad) {
}
@Override
public void onAdCollapsed(MaxAd ad) {
}
@Override
public void onAdLoaded(MaxAd ad) {
adView.setVisibility(View.VISIBLE);
}
@Override
public void onAdDisplayed(MaxAd ad) {
}
@Override
public void onAdHidden(MaxAd ad) {
}
@Override
public void onAdClicked(MaxAd ad) {
}
@Override
public void onAdLoadFailed(String adUnitId, MaxError error) {
}
@Override
public void onAdDisplayFailed(MaxAd ad, MaxError error) {
}
class myadapter extends ArrayAdapter {
Context context;
String rtitle[];
String Stitle[];
int rimages[];
myadapter(Context c, String title[], String subtitle[], int images[])
{
super(c, R.layout.row, R.id.textview1, title);
this.context = c;
this.rtitle = title;
this.Stitle = subtitle;
this.rimages = images;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
{
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row, parent, false);
ImageView img = row.findViewById(R.id.Image_colors_images);
TextView myTitle = row.findViewById(R.id.textview1);
TextView subTitle = row.findViewById(R.id.textview2);
img.setImageResource(rimages[position]);
myTitle.setText(rtitle[position]);
subTitle.setText(Stitle[position]);
return row;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent in =new Intent(getApplicationContext(),DashBoardActivity.class);
startActivity(in);
}
}
| UTF-8 | Java | 10,703 | java | Themes.java | Java | [] | null | [] | package com.accentype.android.softkeyboard;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdViewAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.ads.MaxAdView;
import com.google.android.gms.ads.mediation.Adapter;
import java.util.ArrayList;
public class Themes extends AppCompatActivity implements MaxAdViewAdListener {
// ListView lv_themes;
public static final String MY_PREFS_NAME = "MyPrefsFile";
//
// String mtitle[] = {"Red", "Blue", "Green", "Indigo", "Violet", };
// String subtitle[] = {"Red Color", "Blue Color", "Green Rainbow" , "Indigo Rainbow Color", "Violet Raibow Color"};
// int Images[] = {R.color.red, R.color.blue, R.color.green, R.color.indigo, R.color.violet};
//
// @Override
// protected void onCreate (Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.themes);
// lv_themes = findViewById(R.id.listThemes1);
//
// myadapter adapter = new myadapter(this, mtitle, subtitle, Images);
// lv_themes.setAdapter(adapter);
//// lv_themes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//// @Override
//// public void onItemClick(AdapterView<?> parent, View view, int position, long id)
//// {
//// if (position == 0)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// }
//
// //});
// lv_themes.setOnItemClickListener(this);
//
//// lv_themes.setOnItemClickListener(new AdapterView.OnItemClickListener()
//// {
//// @Override
//// public void onItemClick(AdapterView<?> parent, View view, int position, long id)
//// {
//// if (position == 0)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// if (position == 1)
//// {
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 1);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
//// }
//// }
//// });
//// }
//
//
//
// }
//
// @Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//// SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
//// editor.putInt("idName", 0);
//// editor.commit();
//// Toast.makeText(Themes.this, "Theme Applied", Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
//
// }
//
// class myadapter extends ArrayAdapter
// {
// Context context;
// String rtitle[];
// String Stitle[];
// int rimages[];
//
//
// myadapter(Context c, String title[], String subtitle[], int images[])
// {
// super(c, R.layout.row1, R.id.textview1, title);
// this.context = c;
// this.rtitle = title;
// this.Stitle = subtitle;
// this.rimages = images;
// }
// @NonNull
// @Override
// public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
// {
// LayoutInflater layoutInflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View row = layoutInflater.inflate(R.layout.row1, parent, false);
// ImageView img = row.findViewById(R.id.Image_colors_images1);
// TextView myTitle = row.findViewById(R.id.textview1);
// TextView subTitle = row.findViewById(R.id.textview2);
// img.setImageResource(rimages[position]);
// myTitle.setText(rtitle[position]);
// subTitle.setText(Stitle[position]);
// return row;
// }
// }
// @Override
// public void onBackPressed() {
// super.onBackPressed();
// Intent in =new Intent(getApplicationContext(),DashBoardActivity.class);
// startActivity(in);
// }
ListView listview;
MaxAdView adView;
String mtitle[] = {"Red Color", "blue", "indigo", "violet", "green"};
String subtitle[] = {"Change Themes Red", "Change Themes blue", "Change Themes indigo ", "Change Themes violet", "Change Themes green"};
int Images[] = {R.color.red, R.color.blue, R.color.indigo, R.color.violet, R.color.green};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.themes);
listview = findViewById(R.id.listThemes1);
adView=findViewById(R.id.bannerThemeID);
adView.setListener(this);
adView.loadAd();
myadapter adapter = new myadapter(this, mtitle, subtitle, Images);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if (position==0)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 0);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==1)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 1);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==2)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 2);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==3)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 3);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
if(position==4)
{
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("idName", 4);
editor.commit();
Toast.makeText(Themes.this, "Theme Applied Successfully", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onAdExpanded(MaxAd ad) {
}
@Override
public void onAdCollapsed(MaxAd ad) {
}
@Override
public void onAdLoaded(MaxAd ad) {
adView.setVisibility(View.VISIBLE);
}
@Override
public void onAdDisplayed(MaxAd ad) {
}
@Override
public void onAdHidden(MaxAd ad) {
}
@Override
public void onAdClicked(MaxAd ad) {
}
@Override
public void onAdLoadFailed(String adUnitId, MaxError error) {
}
@Override
public void onAdDisplayFailed(MaxAd ad, MaxError error) {
}
class myadapter extends ArrayAdapter {
Context context;
String rtitle[];
String Stitle[];
int rimages[];
myadapter(Context c, String title[], String subtitle[], int images[])
{
super(c, R.layout.row, R.id.textview1, title);
this.context = c;
this.rtitle = title;
this.Stitle = subtitle;
this.rimages = images;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
{
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row, parent, false);
ImageView img = row.findViewById(R.id.Image_colors_images);
TextView myTitle = row.findViewById(R.id.textview1);
TextView subTitle = row.findViewById(R.id.textview2);
img.setImageResource(rimages[position]);
myTitle.setText(rtitle[position]);
subTitle.setText(Stitle[position]);
return row;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent in =new Intent(getApplicationContext(),DashBoardActivity.class);
startActivity(in);
}
}
| 10,703 | 0.563487 | 0.560871 | 280 | 37.214287 | 33.30418 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.85 | false | false | 4 |
19512f464143525cc07a2fdb4480d6660b91e6d1 | 13,915,694,073,080 | a560b9a03902f48b70d0865544976a70d3902d78 | /src/P24S6.java | 39b4e830bb9dea2122da4c0c3e70cbd49d632a1d | [] | no_license | huzun3517/JavaOCA | https://github.com/huzun3517/JavaOCA | d0304d0456d182eae39ef9891684dadf66b6033a | 375c104caeed14ab0c02e9e9ba8567daeddcefad | refs/heads/master | 2023-02-11T10:50:08.407000 | 2021-01-05T09:20:54 | 2021-01-05T09:20:54 | 326,947,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class P24S6 {
public static void main(String[] args) {
for (int i = 0; i <10 ; i++) {
if(i==4){
continue;
}
System.out.println(i);
}
System.out.println("********************************************************");
for (int i = 0; i <10 ; i++) {
if(i==4){
break;
}
System.out.println(i);
}
System.out.println("********************************************************");
// int data[] = {2010, 2013, 2014, 2015, 2014};
// int key = 2014;
// int count = 0;
// for (int e : data) {
// if (e != key) {
// count++;
// //break;
// continue;
// // count++;
// }
// //count++;
// //System.out.println(e);
//
//
// }
// System.out.println(count + " Found");
}
}
| UTF-8 | Java | 912 | java | P24S6.java | Java | [
{
"context": "010, 2013, 2014, 2015, 2014};\n// int key = 2014;\n// int count = 0;\n// for (int e : ",
"end": 561,
"score": 0.9989334940910339,
"start": 557,
"tag": "KEY",
"value": "2014"
}
] | null | [] | public class P24S6 {
public static void main(String[] args) {
for (int i = 0; i <10 ; i++) {
if(i==4){
continue;
}
System.out.println(i);
}
System.out.println("********************************************************");
for (int i = 0; i <10 ; i++) {
if(i==4){
break;
}
System.out.println(i);
}
System.out.println("********************************************************");
// int data[] = {2010, 2013, 2014, 2015, 2014};
// int key = 2014;
// int count = 0;
// for (int e : data) {
// if (e != key) {
// count++;
// //break;
// continue;
// // count++;
// }
// //count++;
// //System.out.println(e);
//
//
// }
// System.out.println(count + " Found");
}
}
| 912 | 0.319079 | 0.279605 | 42 | 20.714285 | 20.712643 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.02381 | false | false | 4 |
f530c4e3735d75b2578b04848ac184140f4c6076 | 18,829,136,678,350 | e5c9fc4dc73536e75cf4ab119bbc642c28d44591 | /src/leetcodejava/dp/BestTimeBuy714.java | 29bf6186b77bd930dd736aa2095aa84e64ac4257 | [
"MIT"
] | permissive | zhangyu345293721/leetcode | https://github.com/zhangyu345293721/leetcode | 0a22034ac313e3c09e8defd2d351257ec9f285d0 | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | refs/heads/master | 2023-09-01T06:03:18.231000 | 2023-08-31T15:23:03 | 2023-08-31T15:23:03 | 163,050,773 | 101 | 29 | null | false | 2020-12-09T06:26:35 | 2018-12-25T05:58:16 | 2020-12-07T07:30:02 | 2020-12-09T06:26:35 | 2,597 | 79 | 24 | 1 | Java | false | false | package leetcodejava.dp;
import org.junit.Assert;
import org.junit.Test;
/**
* This is the solution of No.714 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
* <p>
* The description of problem is as follow:
* ==========================================================================================================
* 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
* <p>
* 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
* <p>
* 返回获得利润的最大值。
* <p>
* 注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
* <p>
* 示例 1:
* <p>
* 输入:prices = [1, 3, 2, 8, 4, 9], fee = 2
* 输出:8
* 解释:能够达到的最大利润:
* 在此处买入 prices[0] = 1
* 在此处卖出 prices[3] = 8
* 在此处买入 prices[4] = 4
* 在此处卖出 prices[5] = 9
* 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
* 示例 2:
* <p>
* 输入:prices = [1,3,7,5,10,3], fee = 3
* 输出:6
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* ==========================================================================================================
*
* @author zhangyu (zhangyuyu417@gmail.com)
*/
public class BestTimeBuy714 {
@Test
public void bestTimeBuyTest() {
int[] prices = {1, 3, 2, 8, 4, 9};
int fee = 2;
int result = maxProfit(prices, fee);
System.out.println(result);
Assert.assertEquals(result, 8);
}
/**
* 最大利润
*
* @param prices 最大利润
* @param fee 小费
* @return 利润
*/
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length < 1) {
return 0;
}
int n = prices.length;
//定义数组
int[][] dp = new int[2][n];
// 初始化数组
dp[0][0] = -prices[0]; // 第i天后持有股票,⼿⾥利润的最⼤值
dp[0][1] = 0; // 第i天后不持有股票,⼿⾥利润的最⼤值
// 状态转移方程
for (int i = 1; i < n; ++i) {
dp[0][i] = Math.max(dp[0][i - 1], dp[1][i - 1] - prices[i]);
dp[1][i] = Math.max(dp[1][i - 1], dp[0][i - 1] + prices[i] - fee);
}
return Math.max(dp[0][n - 1], dp[1][n - 1]);
}
}
| UTF-8 | Java | 2,868 | java | BestTimeBuy714.java | Java | [
{
"context": "====================================\n *\n * @author zhangyu (zhangyuyu417@gmail.com)\n */\npublic class BestTim",
"end": 1218,
"score": 0.7996928095817566,
"start": 1211,
"tag": "NAME",
"value": "zhangyu"
},
{
"context": "==========================\n *\n * @author zhangyu (zhangyuyu417@gmail.com)\n */\npublic class BestTimeBuy714 {\n\n @Test\n ",
"end": 1242,
"score": 0.9999115467071533,
"start": 1220,
"tag": "EMAIL",
"value": "zhangyuyu417@gmail.com"
}
] | null | [] | package leetcodejava.dp;
import org.junit.Assert;
import org.junit.Test;
/**
* This is the solution of No.714 problem in the LeetCode,
* the website of the problem is as follow:
* https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
* <p>
* The description of problem is as follow:
* ==========================================================================================================
* 给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;整数 fee 代表了交易股票的手续费用。
* <p>
* 你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
* <p>
* 返回获得利润的最大值。
* <p>
* 注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
* <p>
* 示例 1:
* <p>
* 输入:prices = [1, 3, 2, 8, 4, 9], fee = 2
* 输出:8
* 解释:能够达到的最大利润:
* 在此处买入 prices[0] = 1
* 在此处卖出 prices[3] = 8
* 在此处买入 prices[4] = 4
* 在此处卖出 prices[5] = 9
* 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
* 示例 2:
* <p>
* 输入:prices = [1,3,7,5,10,3], fee = 3
* 输出:6
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* ==========================================================================================================
*
* @author zhangyu (<EMAIL>)
*/
public class BestTimeBuy714 {
@Test
public void bestTimeBuyTest() {
int[] prices = {1, 3, 2, 8, 4, 9};
int fee = 2;
int result = maxProfit(prices, fee);
System.out.println(result);
Assert.assertEquals(result, 8);
}
/**
* 最大利润
*
* @param prices 最大利润
* @param fee 小费
* @return 利润
*/
public int maxProfit(int[] prices, int fee) {
if (prices == null || prices.length < 1) {
return 0;
}
int n = prices.length;
//定义数组
int[][] dp = new int[2][n];
// 初始化数组
dp[0][0] = -prices[0]; // 第i天后持有股票,⼿⾥利润的最⼤值
dp[0][1] = 0; // 第i天后不持有股票,⼿⾥利润的最⼤值
// 状态转移方程
for (int i = 1; i < n; ++i) {
dp[0][i] = Math.max(dp[0][i - 1], dp[1][i - 1] - prices[i]);
dp[1][i] = Math.max(dp[1][i - 1], dp[0][i - 1] + prices[i] - fee);
}
return Math.max(dp[0][n - 1], dp[1][n - 1]);
}
}
| 2,853 | 0.49151 | 0.457998 | 78 | 27.692308 | 25.327753 | 109 | false | false | 0 | 0 | 0 | 0 | 107 | 0.095621 | 0.564103 | false | false | 4 |
59bd78f573a0825e782598e7d070d71246413178 | 60,129,549,721 | 96c0cdb1e0f860cee533ec77b7148f8045ee772e | /src/main/java/io/r2dbc/postgresql/codec/PostgresqlObjectId.java | c9cea88c0624270d0e1e49639d6af03d367df40e | [
"Apache-2.0"
] | permissive | pgjdbc/r2dbc-postgresql | https://github.com/pgjdbc/r2dbc-postgresql | 645b148b68158306c10a5edbeb7fc0441f28871f | 543f5ccbd7797a1b7d8a2520a159dc55a1a48aab | refs/heads/main | 2023-09-05T23:12:21.075000 | 2023-07-14T07:44:25 | 2023-07-14T07:44:25 | 136,984,786 | 396 | 105 | Apache-2.0 | false | 2023-08-27T15:05:36 | 2018-06-11T21:50:49 | 2023-08-27T09:28:56 | 2023-08-27T15:05:35 | 3,516 | 951 | 166 | 16 | Java | false | false | /*
* Copyright 2020 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.postgresql.codec;
import io.r2dbc.postgresql.api.RefCursor;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.spi.Clob;
import io.r2dbc.spi.R2dbcType;
import io.r2dbc.spi.Type;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import io.r2dbc.postgresql.util.Assert;
import reactor.util.annotation.Nullable;
/**
* Object IDs for well know PostgreSQL data types.
* <p>Extension Object IDs that are provided by Postgres extensions such as PostGIS are not constants of this enumeration and must be looked up from {@code pg_type}.
* <p>
* Lightweight {@link PostgresTypeIdentifier} identifier returning {@code Object.class} when calling {@link #getJavaType()}.
*/
public enum PostgresqlObjectId implements Type, PostgresTypeIdentifier {
/**
* The bit object id.
*/
BIT(1560),
/**
* The bit array object id.
*/
BIT_ARRAY(1561),
/**
* The bool object id.
*/
BOOL(16, Boolean.class),
/**
* The bool array object id.
*/
BOOL_ARRAY(1000, Boolean[].class),
/**
* The box object id.
*/
BOX(603, Box.class),
/**
* The box array object id.
*/
BOX_ARRAY(1020, Box[].class),
/**
* The bpchar object id.
*/
BPCHAR(1042, String.class),
/**
* The bpchar array object id.
*/
BPCHAR_ARRAY(1014, String[].class),
/**
* The bytea object id.
*/
BYTEA(17, ByteBuffer.class),
/**
* They bytea array object id.
*/
BYTEA_ARRAY(1001, ByteBuffer[].class),
/**
* The char object id.
*/
CHAR(18, Character.class),
/**
* The char array object id.
*/
CHAR_ARRAY(1002, Character[].class),
/**
* The circle object id
*/
CIRCLE(718, Circle.class),
/**
* The circle array object id
*/
CIRCLE_ARRAY(719, Circle[].class),
/**
* The date object id.
*/
DATE(1082, LocalDate.class),
/**
* The date array object id.
*/
DATE_ARRAY(1182, LocalDate[].class),
/**
* The float4 object id.
*/
FLOAT4(700, Float.class),
/**
* The float4 array object id.
*/
FLOAT4_ARRAY(1021, Float[].class),
/**
* The float8 object id.
*/
FLOAT8(701, Double.class),
/**
* The float8 array object id.
*/
FLOAT8_ARRAY(1022, Double[].class),
/**
* The inet object id.
*/
INET(869, InetAddress.class),
/**
* The inet array object id.
*/
INET_ARRAY(1041, InetAddress[].class),
/**
* The int2 object id.
*/
INT2(21, Short.class),
/**
* The int2 array object id.
*/
INT2_ARRAY(1005, Short[].class),
/**
* The int4 object id.
*/
INT4(23, Integer.class),
/**
* The int4 array object id.
*/
INT4_ARRAY(1007, Integer[].class),
/**
* The int8 object id.
*/
INT8(20, Long.class),
/**
* The int8 array object id.
*/
INT8_ARRAY(1016, Long[].class),
/**
* The interval object id.
*/
INTERVAL(1186, Interval.class),
/**
* The interval array object id.
*/
INTERVAL_ARRAY(1187, Interval[].class),
/**
* The JSON object id.
*/
JSON(114, Json.class),
/**
* The JSON array object id.
*/
JSON_ARRAY(199, Json[].class),
/**
* The JSONB array object id.
*/
JSONB(3802, Json.class),
/**
* The JSONB array object id.
*/
JSONB_ARRAY(3807, Json.class),
/**
* The line object id.
*/
LINE(628, Line.class),
/**
* The line array object id.
*/
LINE_ARRAY(629, Line[].class),
/**
* The line segment object id.
*/
LSEG(601, Lseg.class),
/**
* The line segment array object id.
*/
LSEG_ARRAY(1018, Lseg[].class),
/**
* The money object id.
*/
MONEY(790),
/**
* The money array object id.
*/
MONEY_ARRAY(791),
/**
* The name object id.
*/
NAME(19, String.class),
/**
* The name array object id.
*/
NAME_ARRAY(1003, String[].class),
/**
* The numberic object id.
*/
NUMERIC(1700, BigDecimal.class),
/**
* The numeric array object id.
*/
NUMERIC_ARRAY(1231, BigDecimal[].class),
/**
* The oid object id.
*/
OID(26, Integer.class),
/**
* The oid array object id.
*/
OID_ARRAY(1028, Integer[].class),
/**
* The path object id.
*/
PATH(602, Path.class),
/**
* The path array object id.
*/
PATH_ARRAY(1019, Path[].class),
/**
* The point object id.
*/
POINT(600, Point.class),
/**
* The point array object id.
*/
POINT_ARRAY(1017, Point[].class),
/**
* the polygon object id.
*/
POLYGON(604, Polygon.class),
/**
* the polygon array object id.
*/
POLYGON_ARRAY(1027, Polygon[].class),
/**
* The ref cursor object id.
*/
REF_CURSOR(1790, RefCursor.class),
/**
* The ref cursor array object id.
*/
REF_CURSOR_ARRAY(2201, RefCursor[].class),
/**
* The text object id.
*/
TEXT(25, Clob.class),
/**
* The text array object id.
*/
TEXT_ARRAY(1009, Clob[].class),
/**
* The time object id.
*/
TIME(1083, LocalTime.class),
/**
* The time array object id.
*/
TIME_ARRAY(1183, LocalTime[].class),
/**
* The timestamp object id.
*/
TIMESTAMP(1114, LocalDateTime.class),
/**
* The timestamp array object id.
*/
TIMESTAMP_ARRAY(1115, LocalDateTime[].class),
/**
* The timestamptz object id.
*/
TIMESTAMPTZ(1184, OffsetDateTime.class),
/**
* The timestamptz array object id.
*/
TIMESTAMPTZ_ARRAY(1185, OffsetDateTime[].class),
/**
* The timetz object id.
*/
TIMETZ(1266, OffsetTime.class),
/**
* The timetz array object id.
*/
TIMETZ_ARRAY(1270, OffsetTime[].class),
/**
* UNKNOWN type
* PostgreSQL will sometimes return this type
* an example might be select 'hello' as foo
* newer versions return TEXT but some older
* versions will return UNKNOWN
*/
UNKNOWN(705),
/**
* The unspecified object id.
* This can be sent as a parameter type
* to tell the backend to infer the type
*/
UNSPECIFIED(0),
/**
* The UUID object id.
*/
UUID(2950, java.util.UUID.class),
/**
* The UUID array object id.
*/
UUID_ARRAY(2951, java.util.UUID[].class),
/**
* The varbit object id.
*/
VARBIT(1562),
/**
* The varbit array object id.
*/
VARBIT_ARRAY(1563),
/**
* The varchar object id.
*/
VARCHAR(1043, String.class),
/**
* The varchar array object id.
*/
VARCHAR_ARRAY(1015, String[].class),
/**
* The void object id.
*/
VOID(2278, Void.class),
/**
* The XML object id.
*/
XML(142),
/**
* The XML Array object id.
*/
XML_ARRAY(143);
public static final int OID_CACHE_SIZE = 3810; // JSON_ARRAY is currently the highest one
private static final PostgresqlObjectId[] CACHE = new PostgresqlObjectId[OID_CACHE_SIZE];
private final int objectId;
private final Class<?> defaultJavaType;
static {
for (PostgresqlObjectId oid : values()) {
CACHE[oid.getObjectId()] = oid;
}
}
PostgresqlObjectId(int objectId) {
this(objectId, Object.class);
}
PostgresqlObjectId(int objectId, Class<?> defaultJavaType) {
this.objectId = objectId;
this.defaultJavaType = Assert.requireNonNull(defaultJavaType, "defaultJavaType must not be null");
}
public static PostgresqlObjectId from(PostgresTypeIdentifier dataType) {
if (dataType instanceof PostgresqlObjectId) {
return (PostgresqlObjectId) dataType;
}
return valueOf(dataType.getObjectId());
}
/**
* Returns if the {@code objectId} is a known and valid {@code objectId}.
*
* @param objectId the object id to match
* @return {@code true} if the {@code objectId} is a valid and known (static) objectId;{@code false} otherwise.
*/
public static boolean isValid(int objectId) {
if (objectId >= 0 && objectId < OID_CACHE_SIZE) {
PostgresqlObjectId oid = CACHE[objectId];
return oid != null;
}
return false;
}
/**
* Returns the {@link PostgresqlObjectId} matching a given object id.
*
* @param objectId the object id to match
* @return the {@link PostgresqlObjectId} matching a given object id
* @throws IllegalArgumentException if {@code objectId} isn't a valid object id
*/
public static PostgresqlObjectId valueOf(int objectId) {
PostgresqlObjectId oid = null;
if (objectId >= 0 && objectId < OID_CACHE_SIZE) {
oid = CACHE[objectId];
}
if (oid == null) {
throw new IllegalArgumentException(String.format("%d is not a valid object id", objectId));
}
return oid;
}
/**
* Returns the {@link PostgresqlObjectId} matching a given {@link R2dbcType R2DBC type}.
*
* @param type the R2DBC type
* @return the {@link PostgresqlObjectId}
* @throws IllegalArgumentException if {@code type} is {@code null}
* @throws UnsupportedOperationException if the given {@code type} is not supported
* @since 0.9
*/
public static PostgresqlObjectId valueOf(R2dbcType type) {
Assert.requireNonNull(type, "type must not be null");
switch (type) {
case NCHAR:
case CHAR:
return CHAR;
case NVARCHAR:
case VARCHAR:
return VARCHAR;
case CLOB:
case NCLOB:
return TEXT;
case BOOLEAN:
return BOOL;
case BINARY:
case VARBINARY:
case BLOB:
return BYTEA;
case INTEGER:
return INT4;
case TINYINT:
return BIT;
case SMALLINT:
return INT2;
case BIGINT:
return INT8;
case NUMERIC:
case DECIMAL:
return NUMERIC;
case FLOAT:
case REAL:
return FLOAT4;
case DOUBLE:
return FLOAT8;
case DATE:
return DATE;
case TIME:
return TIME;
case TIME_WITH_TIME_ZONE:
return TIMETZ;
case TIMESTAMP:
return TIMESTAMP;
case TIMESTAMP_WITH_TIME_ZONE:
return TIMESTAMPTZ;
case COLLECTION:
throw new UnsupportedOperationException("Raw collection (without component type) is not supported");
}
throw new UnsupportedOperationException("Type " + type + " not supported");
}
@Override
public Class<?> getJavaType() {
return this.defaultJavaType;
}
@Override
public String getName() {
return name();
}
/**
* Returns the object id represented by each return value.
*
* @return the object id represented by each return value
*/
@Override
public int getObjectId() {
return this.objectId;
}
public static int toInt(@Nullable Long oid) {
Assert.requireNonNull(oid, "OID must not be null");
return toInt(oid.longValue());
}
public static int toInt(long oid) {
if ((oid & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Value is not an OID:" + oid);
}
return (int) oid;
}
public static long toLong(int oid) {
return Integer.toUnsignedLong(oid);
}
}
| UTF-8 | Java | 12,882 | java | PostgresqlObjectId.java | Java | [] | null | [] | /*
* Copyright 2020 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.postgresql.codec;
import io.r2dbc.postgresql.api.RefCursor;
import io.r2dbc.postgresql.util.Assert;
import io.r2dbc.spi.Clob;
import io.r2dbc.spi.R2dbcType;
import io.r2dbc.spi.Type;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import io.r2dbc.postgresql.util.Assert;
import reactor.util.annotation.Nullable;
/**
* Object IDs for well know PostgreSQL data types.
* <p>Extension Object IDs that are provided by Postgres extensions such as PostGIS are not constants of this enumeration and must be looked up from {@code pg_type}.
* <p>
* Lightweight {@link PostgresTypeIdentifier} identifier returning {@code Object.class} when calling {@link #getJavaType()}.
*/
public enum PostgresqlObjectId implements Type, PostgresTypeIdentifier {
/**
* The bit object id.
*/
BIT(1560),
/**
* The bit array object id.
*/
BIT_ARRAY(1561),
/**
* The bool object id.
*/
BOOL(16, Boolean.class),
/**
* The bool array object id.
*/
BOOL_ARRAY(1000, Boolean[].class),
/**
* The box object id.
*/
BOX(603, Box.class),
/**
* The box array object id.
*/
BOX_ARRAY(1020, Box[].class),
/**
* The bpchar object id.
*/
BPCHAR(1042, String.class),
/**
* The bpchar array object id.
*/
BPCHAR_ARRAY(1014, String[].class),
/**
* The bytea object id.
*/
BYTEA(17, ByteBuffer.class),
/**
* They bytea array object id.
*/
BYTEA_ARRAY(1001, ByteBuffer[].class),
/**
* The char object id.
*/
CHAR(18, Character.class),
/**
* The char array object id.
*/
CHAR_ARRAY(1002, Character[].class),
/**
* The circle object id
*/
CIRCLE(718, Circle.class),
/**
* The circle array object id
*/
CIRCLE_ARRAY(719, Circle[].class),
/**
* The date object id.
*/
DATE(1082, LocalDate.class),
/**
* The date array object id.
*/
DATE_ARRAY(1182, LocalDate[].class),
/**
* The float4 object id.
*/
FLOAT4(700, Float.class),
/**
* The float4 array object id.
*/
FLOAT4_ARRAY(1021, Float[].class),
/**
* The float8 object id.
*/
FLOAT8(701, Double.class),
/**
* The float8 array object id.
*/
FLOAT8_ARRAY(1022, Double[].class),
/**
* The inet object id.
*/
INET(869, InetAddress.class),
/**
* The inet array object id.
*/
INET_ARRAY(1041, InetAddress[].class),
/**
* The int2 object id.
*/
INT2(21, Short.class),
/**
* The int2 array object id.
*/
INT2_ARRAY(1005, Short[].class),
/**
* The int4 object id.
*/
INT4(23, Integer.class),
/**
* The int4 array object id.
*/
INT4_ARRAY(1007, Integer[].class),
/**
* The int8 object id.
*/
INT8(20, Long.class),
/**
* The int8 array object id.
*/
INT8_ARRAY(1016, Long[].class),
/**
* The interval object id.
*/
INTERVAL(1186, Interval.class),
/**
* The interval array object id.
*/
INTERVAL_ARRAY(1187, Interval[].class),
/**
* The JSON object id.
*/
JSON(114, Json.class),
/**
* The JSON array object id.
*/
JSON_ARRAY(199, Json[].class),
/**
* The JSONB array object id.
*/
JSONB(3802, Json.class),
/**
* The JSONB array object id.
*/
JSONB_ARRAY(3807, Json.class),
/**
* The line object id.
*/
LINE(628, Line.class),
/**
* The line array object id.
*/
LINE_ARRAY(629, Line[].class),
/**
* The line segment object id.
*/
LSEG(601, Lseg.class),
/**
* The line segment array object id.
*/
LSEG_ARRAY(1018, Lseg[].class),
/**
* The money object id.
*/
MONEY(790),
/**
* The money array object id.
*/
MONEY_ARRAY(791),
/**
* The name object id.
*/
NAME(19, String.class),
/**
* The name array object id.
*/
NAME_ARRAY(1003, String[].class),
/**
* The numberic object id.
*/
NUMERIC(1700, BigDecimal.class),
/**
* The numeric array object id.
*/
NUMERIC_ARRAY(1231, BigDecimal[].class),
/**
* The oid object id.
*/
OID(26, Integer.class),
/**
* The oid array object id.
*/
OID_ARRAY(1028, Integer[].class),
/**
* The path object id.
*/
PATH(602, Path.class),
/**
* The path array object id.
*/
PATH_ARRAY(1019, Path[].class),
/**
* The point object id.
*/
POINT(600, Point.class),
/**
* The point array object id.
*/
POINT_ARRAY(1017, Point[].class),
/**
* the polygon object id.
*/
POLYGON(604, Polygon.class),
/**
* the polygon array object id.
*/
POLYGON_ARRAY(1027, Polygon[].class),
/**
* The ref cursor object id.
*/
REF_CURSOR(1790, RefCursor.class),
/**
* The ref cursor array object id.
*/
REF_CURSOR_ARRAY(2201, RefCursor[].class),
/**
* The text object id.
*/
TEXT(25, Clob.class),
/**
* The text array object id.
*/
TEXT_ARRAY(1009, Clob[].class),
/**
* The time object id.
*/
TIME(1083, LocalTime.class),
/**
* The time array object id.
*/
TIME_ARRAY(1183, LocalTime[].class),
/**
* The timestamp object id.
*/
TIMESTAMP(1114, LocalDateTime.class),
/**
* The timestamp array object id.
*/
TIMESTAMP_ARRAY(1115, LocalDateTime[].class),
/**
* The timestamptz object id.
*/
TIMESTAMPTZ(1184, OffsetDateTime.class),
/**
* The timestamptz array object id.
*/
TIMESTAMPTZ_ARRAY(1185, OffsetDateTime[].class),
/**
* The timetz object id.
*/
TIMETZ(1266, OffsetTime.class),
/**
* The timetz array object id.
*/
TIMETZ_ARRAY(1270, OffsetTime[].class),
/**
* UNKNOWN type
* PostgreSQL will sometimes return this type
* an example might be select 'hello' as foo
* newer versions return TEXT but some older
* versions will return UNKNOWN
*/
UNKNOWN(705),
/**
* The unspecified object id.
* This can be sent as a parameter type
* to tell the backend to infer the type
*/
UNSPECIFIED(0),
/**
* The UUID object id.
*/
UUID(2950, java.util.UUID.class),
/**
* The UUID array object id.
*/
UUID_ARRAY(2951, java.util.UUID[].class),
/**
* The varbit object id.
*/
VARBIT(1562),
/**
* The varbit array object id.
*/
VARBIT_ARRAY(1563),
/**
* The varchar object id.
*/
VARCHAR(1043, String.class),
/**
* The varchar array object id.
*/
VARCHAR_ARRAY(1015, String[].class),
/**
* The void object id.
*/
VOID(2278, Void.class),
/**
* The XML object id.
*/
XML(142),
/**
* The XML Array object id.
*/
XML_ARRAY(143);
public static final int OID_CACHE_SIZE = 3810; // JSON_ARRAY is currently the highest one
private static final PostgresqlObjectId[] CACHE = new PostgresqlObjectId[OID_CACHE_SIZE];
private final int objectId;
private final Class<?> defaultJavaType;
static {
for (PostgresqlObjectId oid : values()) {
CACHE[oid.getObjectId()] = oid;
}
}
PostgresqlObjectId(int objectId) {
this(objectId, Object.class);
}
PostgresqlObjectId(int objectId, Class<?> defaultJavaType) {
this.objectId = objectId;
this.defaultJavaType = Assert.requireNonNull(defaultJavaType, "defaultJavaType must not be null");
}
public static PostgresqlObjectId from(PostgresTypeIdentifier dataType) {
if (dataType instanceof PostgresqlObjectId) {
return (PostgresqlObjectId) dataType;
}
return valueOf(dataType.getObjectId());
}
/**
* Returns if the {@code objectId} is a known and valid {@code objectId}.
*
* @param objectId the object id to match
* @return {@code true} if the {@code objectId} is a valid and known (static) objectId;{@code false} otherwise.
*/
public static boolean isValid(int objectId) {
if (objectId >= 0 && objectId < OID_CACHE_SIZE) {
PostgresqlObjectId oid = CACHE[objectId];
return oid != null;
}
return false;
}
/**
* Returns the {@link PostgresqlObjectId} matching a given object id.
*
* @param objectId the object id to match
* @return the {@link PostgresqlObjectId} matching a given object id
* @throws IllegalArgumentException if {@code objectId} isn't a valid object id
*/
public static PostgresqlObjectId valueOf(int objectId) {
PostgresqlObjectId oid = null;
if (objectId >= 0 && objectId < OID_CACHE_SIZE) {
oid = CACHE[objectId];
}
if (oid == null) {
throw new IllegalArgumentException(String.format("%d is not a valid object id", objectId));
}
return oid;
}
/**
* Returns the {@link PostgresqlObjectId} matching a given {@link R2dbcType R2DBC type}.
*
* @param type the R2DBC type
* @return the {@link PostgresqlObjectId}
* @throws IllegalArgumentException if {@code type} is {@code null}
* @throws UnsupportedOperationException if the given {@code type} is not supported
* @since 0.9
*/
public static PostgresqlObjectId valueOf(R2dbcType type) {
Assert.requireNonNull(type, "type must not be null");
switch (type) {
case NCHAR:
case CHAR:
return CHAR;
case NVARCHAR:
case VARCHAR:
return VARCHAR;
case CLOB:
case NCLOB:
return TEXT;
case BOOLEAN:
return BOOL;
case BINARY:
case VARBINARY:
case BLOB:
return BYTEA;
case INTEGER:
return INT4;
case TINYINT:
return BIT;
case SMALLINT:
return INT2;
case BIGINT:
return INT8;
case NUMERIC:
case DECIMAL:
return NUMERIC;
case FLOAT:
case REAL:
return FLOAT4;
case DOUBLE:
return FLOAT8;
case DATE:
return DATE;
case TIME:
return TIME;
case TIME_WITH_TIME_ZONE:
return TIMETZ;
case TIMESTAMP:
return TIMESTAMP;
case TIMESTAMP_WITH_TIME_ZONE:
return TIMESTAMPTZ;
case COLLECTION:
throw new UnsupportedOperationException("Raw collection (without component type) is not supported");
}
throw new UnsupportedOperationException("Type " + type + " not supported");
}
@Override
public Class<?> getJavaType() {
return this.defaultJavaType;
}
@Override
public String getName() {
return name();
}
/**
* Returns the object id represented by each return value.
*
* @return the object id represented by each return value
*/
@Override
public int getObjectId() {
return this.objectId;
}
public static int toInt(@Nullable Long oid) {
Assert.requireNonNull(oid, "OID must not be null");
return toInt(oid.longValue());
}
public static int toInt(long oid) {
if ((oid & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Value is not an OID:" + oid);
}
return (int) oid;
}
public static long toLong(int oid) {
return Integer.toUnsignedLong(oid);
}
}
| 12,882 | 0.560006 | 0.534932 | 597 | 20.57789 | 21.444784 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358459 | false | false | 4 |
90564162eae0e7084b37387c20f56148d5f492ea | 18,665,927,900,622 | 689d6182ba6563e195e7dab20f051e8e21ad647d | /app/src/main/java/com/bamboolmc/zhiqu/ui/adapter/MtMovieStarRelPeopleAdapter.java | 4e04d593b221ae2f43804bbe33aa16f588819b9a | [] | no_license | bambooblacklee/ZhiQu | https://github.com/bambooblacklee/ZhiQu | 02763ed9a5abd72b7d6b7aec378175dda337402e | 872eb86575bf9621b2e392966b376d47c8e455cc | refs/heads/master | 2021-01-23T20:26:21.019000 | 2018-04-16T15:05:22 | 2018-04-16T15:05:22 | 102,859,633 | 9 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bamboolmc.zhiqu.ui.adapter;
import android.view.View;
import android.widget.ImageView;
import com.bamboolmc.zhiqu.R;
import com.bamboolmc.zhiqu.model.bean.MtMovieStarRelPeopleBean;
import com.bamboolmc.zhiqu.util.ImgResetUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;
/**
* Created by limc on 17/5/23.
*/
public class MtMovieStarRelPeopleAdapter extends BaseQuickAdapter<MtMovieStarRelPeopleBean.DataBean.RelationsBean, BaseViewHolder> {
public MtMovieStarRelPeopleAdapter() {
super(R.layout.item_related_star, null);
}
@Override
protected void convert(BaseViewHolder helper, MtMovieStarRelPeopleBean.DataBean.RelationsBean item) {
helper.setText(R.id.tv_related_star_name, item.getName())
.setText(R.id.tv_cooperate_time, item.getRelation());
String img = ImgResetUtil.processUrl(item.getAvatar(), 255, 345);
if (img.trim().length() == 0) {
helper.setImageResource(R.id.iv_related_star,R.mipmap.ic_launcher);
}else {
Picasso.with(mContext)
.load(img)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into((ImageView) helper.getView(R.id.iv_related_star));
}
helper.convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// MovieStarActivity.start(mContext,item.getId());
}
});
}
}
| UTF-8 | Java | 1,622 | java | MtMovieStarRelPeopleAdapter.java | Java | [
{
"context": "t com.squareup.picasso.Picasso;\n\n/**\n * Created by limc on 17/5/23.\n */\npublic class MtMovieStarRelPeople",
"end": 409,
"score": 0.9996145367622375,
"start": 405,
"tag": "USERNAME",
"value": "limc"
}
] | null | [] | package com.bamboolmc.zhiqu.ui.adapter;
import android.view.View;
import android.widget.ImageView;
import com.bamboolmc.zhiqu.R;
import com.bamboolmc.zhiqu.model.bean.MtMovieStarRelPeopleBean;
import com.bamboolmc.zhiqu.util.ImgResetUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;
/**
* Created by limc on 17/5/23.
*/
public class MtMovieStarRelPeopleAdapter extends BaseQuickAdapter<MtMovieStarRelPeopleBean.DataBean.RelationsBean, BaseViewHolder> {
public MtMovieStarRelPeopleAdapter() {
super(R.layout.item_related_star, null);
}
@Override
protected void convert(BaseViewHolder helper, MtMovieStarRelPeopleBean.DataBean.RelationsBean item) {
helper.setText(R.id.tv_related_star_name, item.getName())
.setText(R.id.tv_cooperate_time, item.getRelation());
String img = ImgResetUtil.processUrl(item.getAvatar(), 255, 345);
if (img.trim().length() == 0) {
helper.setImageResource(R.id.iv_related_star,R.mipmap.ic_launcher);
}else {
Picasso.with(mContext)
.load(img)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into((ImageView) helper.getView(R.id.iv_related_star));
}
helper.convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// MovieStarActivity.start(mContext,item.getId());
}
});
}
}
| 1,622 | 0.664612 | 0.657213 | 44 | 35.863636 | 30.722801 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.568182 | false | false | 4 |
bfed6311af8a12884f93a8102d4e4f8886dabf22 | 8,022,998,979,103 | 27ff92112503263911d35a5336a5cd93dcd5c247 | /opensrp-chw-core/src/main/java/org/smartregister/chw/core/activity/CoreStockInventoryReportActivity.java | 25ab7353d4b9cdb8bf12c99c86d4fb60a145daed | [
"Apache-2.0"
] | permissive | SoftmedTanzania/opensrp-client-chw-core | https://github.com/SoftmedTanzania/opensrp-client-chw-core | 77441d7481dbe4d78dea91151dd9d469bf6be152 | ac6859bd51fd23572f0d8ed82a86f103376dd57b | refs/heads/tanzania-ministry-of-health-nacp | 2023-05-13T01:44:10.012000 | 2023-05-11T18:58:03 | 2023-05-11T18:58:03 | 425,199,013 | 0 | 2 | NOASSERTION | true | 2023-04-18T09:51:24 | 2021-11-06T09:02:04 | 2022-01-03T07:37:53 | 2023-04-18T09:51:22 | 109,863 | 0 | 1 | 2 | Java | false | false | package org.smartregister.chw.core.activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
import org.smartregister.chw.core.R;
import org.smartregister.chw.core.adapter.CoreStockMonthlyReportAdapter;
import org.smartregister.chw.core.adapter.CoreStockUsageItemAdapter;
import org.smartregister.chw.core.application.CoreChwApplication;
import org.smartregister.chw.core.dao.StockUsageReportDao;
import org.smartregister.chw.core.model.MonthStockUsageModel;
import org.smartregister.chw.core.model.StockUsageItemModel;
import org.smartregister.chw.core.utils.StockUsageReportUtils;
import org.smartregister.view.activity.SecuredActivity;
import org.smartregister.view.customcontrols.CustomFontTextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class CoreStockInventoryReportActivity extends SecuredActivity {
protected AppBarLayout appBarLayout;
protected RecyclerView recyclerView;
protected CustomFontTextView toolBarTextView;
public static List<String> getItems() {
return new ArrayList<>(
Arrays.asList("ORS 5", "Zinc 10", "Panadol", "COC", "POP", "Male condom", "Female condom", "Standard day method", "Emergency contraceptive", "RDTs", "ALU 6", "ALU 12", "ALU 18", "ALU 24")
);
}
protected List<MonthStockUsageModel> getMonthStockUsageReportList() {
List<MonthStockUsageModel> monthStockUsageReportList = new ArrayList<>();
if (StockUsageReportUtils.getPreviousMonths(this).size() > 0) {
for (Map.Entry<String, String> entry : StockUsageReportUtils.getPreviousMonths(this).entrySet()) {
monthStockUsageReportList.add(new MonthStockUsageModel(entry.getKey(), entry.getValue()));
}
}
return monthStockUsageReportList;
}
public List<StockUsageItemModel> getStockUsageItemReportList(String month, String year) {
List<StockUsageItemModel> stockUsageItemModelsList = new ArrayList<>();
String providerName = getProviderName();
for (String item : getItems()) {
String usage = getStockUsageForMonth(month, item, year, providerName);
stockUsageItemModelsList.add(new StockUsageItemModel(StockUsageReportUtils.getFormattedItem(item, this), StockUsageReportUtils.getUnitOfMeasure(item, this), usage, providerName));
}
return stockUsageItemModelsList;
}
public String getProviderName() {
return CoreChwApplication.getInstance().getContext().allSharedPreferences().fetchRegisteredANM();
}
public String getStockUsageForMonth(String month, String stockName, String year, String providerName) {
return StockUsageReportDao.getStockUsageForMonth(month, stockName, year, providerName);
}
protected void reloadRecycler(MonthStockUsageModel selected) {
String stockMonth = StockUsageReportUtils.getMonthNumber(selected.getMonth().substring(0, 3));
String stockYear = selected.getYear();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
CoreStockUsageItemAdapter coreStockUsageItemAdapter = new CoreStockUsageItemAdapter(getStockUsageItemReportList(stockMonth, stockYear), this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(coreStockUsageItemAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
}
@Override
protected void onCreation() {
setContentView(R.layout.activity_stock_usage_report);
Spinner spinner = findViewById(R.id.spinner);
CoreStockMonthlyReportAdapter adapter = new CoreStockMonthlyReportAdapter(getMonthStockUsageReportList(), this);
spinner.setAdapter(adapter);
recyclerView = findViewById(R.id.rv_stock_usage_report);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MonthStockUsageModel selected = getMonthStockUsageReportList().get(position);
reloadRecycler(selected);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//Implements Method From super Class
}
});
Toolbar toolbar = findViewById(R.id.back_to_nav_toolbar);
toolBarTextView = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
upArrow.setColorFilter(getResources().getColor(R.color.text_blue), PorterDuff.Mode.SRC_ATOP);
actionBar.setHomeAsUpIndicator(upArrow);
actionBar.setElevation(0);
}
toolbar.setNavigationOnClickListener(v -> finish());
toolBarTextView.setText(getString(R.string.stock_usage_report));
toolBarTextView.setOnClickListener(v -> finish());
appBarLayout = findViewById(R.id.app_bar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
appBarLayout.setOutlineProvider(null);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
@Override
protected void onResumption() {
//Implements Method From super Class
}
}
| UTF-8 | Java | 6,164 | java | CoreStockInventoryReportActivity.java | Java | [] | null | [] | package org.smartregister.chw.core.activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
import org.smartregister.chw.core.R;
import org.smartregister.chw.core.adapter.CoreStockMonthlyReportAdapter;
import org.smartregister.chw.core.adapter.CoreStockUsageItemAdapter;
import org.smartregister.chw.core.application.CoreChwApplication;
import org.smartregister.chw.core.dao.StockUsageReportDao;
import org.smartregister.chw.core.model.MonthStockUsageModel;
import org.smartregister.chw.core.model.StockUsageItemModel;
import org.smartregister.chw.core.utils.StockUsageReportUtils;
import org.smartregister.view.activity.SecuredActivity;
import org.smartregister.view.customcontrols.CustomFontTextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class CoreStockInventoryReportActivity extends SecuredActivity {
protected AppBarLayout appBarLayout;
protected RecyclerView recyclerView;
protected CustomFontTextView toolBarTextView;
public static List<String> getItems() {
return new ArrayList<>(
Arrays.asList("ORS 5", "Zinc 10", "Panadol", "COC", "POP", "Male condom", "Female condom", "Standard day method", "Emergency contraceptive", "RDTs", "ALU 6", "ALU 12", "ALU 18", "ALU 24")
);
}
protected List<MonthStockUsageModel> getMonthStockUsageReportList() {
List<MonthStockUsageModel> monthStockUsageReportList = new ArrayList<>();
if (StockUsageReportUtils.getPreviousMonths(this).size() > 0) {
for (Map.Entry<String, String> entry : StockUsageReportUtils.getPreviousMonths(this).entrySet()) {
monthStockUsageReportList.add(new MonthStockUsageModel(entry.getKey(), entry.getValue()));
}
}
return monthStockUsageReportList;
}
public List<StockUsageItemModel> getStockUsageItemReportList(String month, String year) {
List<StockUsageItemModel> stockUsageItemModelsList = new ArrayList<>();
String providerName = getProviderName();
for (String item : getItems()) {
String usage = getStockUsageForMonth(month, item, year, providerName);
stockUsageItemModelsList.add(new StockUsageItemModel(StockUsageReportUtils.getFormattedItem(item, this), StockUsageReportUtils.getUnitOfMeasure(item, this), usage, providerName));
}
return stockUsageItemModelsList;
}
public String getProviderName() {
return CoreChwApplication.getInstance().getContext().allSharedPreferences().fetchRegisteredANM();
}
public String getStockUsageForMonth(String month, String stockName, String year, String providerName) {
return StockUsageReportDao.getStockUsageForMonth(month, stockName, year, providerName);
}
protected void reloadRecycler(MonthStockUsageModel selected) {
String stockMonth = StockUsageReportUtils.getMonthNumber(selected.getMonth().substring(0, 3));
String stockYear = selected.getYear();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
CoreStockUsageItemAdapter coreStockUsageItemAdapter = new CoreStockUsageItemAdapter(getStockUsageItemReportList(stockMonth, stockYear), this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(coreStockUsageItemAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
}
@Override
protected void onCreation() {
setContentView(R.layout.activity_stock_usage_report);
Spinner spinner = findViewById(R.id.spinner);
CoreStockMonthlyReportAdapter adapter = new CoreStockMonthlyReportAdapter(getMonthStockUsageReportList(), this);
spinner.setAdapter(adapter);
recyclerView = findViewById(R.id.rv_stock_usage_report);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MonthStockUsageModel selected = getMonthStockUsageReportList().get(position);
reloadRecycler(selected);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
//Implements Method From super Class
}
});
Toolbar toolbar = findViewById(R.id.back_to_nav_toolbar);
toolBarTextView = toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp);
upArrow.setColorFilter(getResources().getColor(R.color.text_blue), PorterDuff.Mode.SRC_ATOP);
actionBar.setHomeAsUpIndicator(upArrow);
actionBar.setElevation(0);
}
toolbar.setNavigationOnClickListener(v -> finish());
toolBarTextView.setText(getString(R.string.stock_usage_report));
toolBarTextView.setOnClickListener(v -> finish());
appBarLayout = findViewById(R.id.app_bar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
appBarLayout.setOutlineProvider(null);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
@Override
protected void onResumption() {
//Implements Method From super Class
}
}
| 6,164 | 0.727774 | 0.725178 | 143 | 42.104897 | 37.819542 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.783217 | false | false | 4 |
395fcda9dbb2d88fd5533928cc25991acf597995 | 1,709,397,037,562 | 1a2842f576579c49748ec78ac13f742e9b1ee11a | /OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/ColorUtils.java | 6adc85a45a5f112a6529dafe8392d48c5afa7db9 | [
"Apache-2.0"
] | permissive | aesean/science-journal | https://github.com/aesean/science-journal | 8df0ace268e5bc53cb43a28cbf3f3a20326c8d20 | 22aa1cbab7c4aed5b1604271e71f5b2b3675ddb2 | refs/heads/master | 2021-01-14T08:21:33.837000 | 2017-02-09T17:58:20 | 2017-02-09T17:58:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.apps.forscience.whistlepunk;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
/**
* Utility class for coloring icons.
*/
public class ColorUtils {
// TODO: Find all setColorFilter methods and update them to use this utility function.
public static Drawable colorDrawable(Context context, Drawable drawable, int colorId) {
Drawable result = drawable.mutate();
result.setColorFilter(context.getResources().getColor(colorId), PorterDuff.Mode.MULTIPLY);
return result;
}
}
| UTF-8 | Java | 599 | java | ColorUtils.java | Java | [] | null | [] | package com.google.android.apps.forscience.whistlepunk;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
/**
* Utility class for coloring icons.
*/
public class ColorUtils {
// TODO: Find all setColorFilter methods and update them to use this utility function.
public static Drawable colorDrawable(Context context, Drawable drawable, int colorId) {
Drawable result = drawable.mutate();
result.setColorFilter(context.getResources().getColor(colorId), PorterDuff.Mode.MULTIPLY);
return result;
}
}
| 599 | 0.751252 | 0.751252 | 18 | 32.277779 | 32.138252 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 4 |
cf06c9436083c996e3d9d8af56d060c594c3d274 | 2,697,239,527,239 | 0fa8aaf6657807a91dd1af554cdaca8d95d3eef2 | /app/src/main/java/com/example/videotophotos/ListVideoFragment.java | 88a4c90d59641c310c422060ace072735e5f24f4 | [] | no_license | Shynltd/VideoToPhotos | https://github.com/Shynltd/VideoToPhotos | 374f3aed3095f92925e5caa67a04d012eb6e096e | 36d52d02a70517499e4c39aab77167af68d12f35 | refs/heads/master | 2023-01-08T13:13:31.350000 | 2020-11-02T09:53:47 | 2020-11-02T09:53:47 | 309,326,605 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.videotophotos;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.Image;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.videotophotos.adapter.ImageCropAdapter;
import java.util.ArrayList;
import java.util.List;
public class ListVideoFragment extends Fragment {
private VideoView videoView;
private RecyclerView rvImageCrop;
// TODO: Rename and change types of parameters
private String path;
public ListVideoFragment(String path) {
this.path = path;
// Required empty public constructor
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
videoView.setVideoPath(path);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
final List<Bitmap> bitmapList = new ArrayList<>();
final ImageCropAdapter imageCropAdapter =new ImageCropAdapter(bitmapList,getContext());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL,false);
rvImageCrop.setLayoutManager(linearLayoutManager);
rvImageCrop.setHasFixedSize(true);
rvImageCrop.setAdapter(imageCropAdapter);
final MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(path);
Log.d("TAG11", "getDuration: " + videoView.getDuration());
final MediaController mediaController = new MediaController(getContext());
mediaController.setAnchorView(videoView);
mediaController.setPrevNextListeners(new View.OnClickListener() {
@Override
public void onClick(View view) {
long time = (long) videoView.getCurrentPosition();
bitmapList.add(media.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST));
imageCropAdapter.notifyItemInserted(bitmapList.size() - 1);
imageCropAdapter.notifyDataSetChanged();
Toast.makeText(getContext(), ""+time, Toast.LENGTH_SHORT).show();
}
}, new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "pre", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(mediaController);
videoView.start();
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
videoView.start();
}
});
mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i1) {
}
});
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_view_video, container, false);
videoView = (VideoView) view.findViewById(R.id.videoView);
rvImageCrop = (RecyclerView) view.findViewById(R.id.rvImageCrop);
return view;
}
} | UTF-8 | Java | 4,416 | java | ListVideoFragment.java | Java | [] | null | [] | package com.example.videotophotos;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.Image;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.videotophotos.adapter.ImageCropAdapter;
import java.util.ArrayList;
import java.util.List;
public class ListVideoFragment extends Fragment {
private VideoView videoView;
private RecyclerView rvImageCrop;
// TODO: Rename and change types of parameters
private String path;
public ListVideoFragment(String path) {
this.path = path;
// Required empty public constructor
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
videoView.setVideoPath(path);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
final List<Bitmap> bitmapList = new ArrayList<>();
final ImageCropAdapter imageCropAdapter =new ImageCropAdapter(bitmapList,getContext());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL,false);
rvImageCrop.setLayoutManager(linearLayoutManager);
rvImageCrop.setHasFixedSize(true);
rvImageCrop.setAdapter(imageCropAdapter);
final MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(path);
Log.d("TAG11", "getDuration: " + videoView.getDuration());
final MediaController mediaController = new MediaController(getContext());
mediaController.setAnchorView(videoView);
mediaController.setPrevNextListeners(new View.OnClickListener() {
@Override
public void onClick(View view) {
long time = (long) videoView.getCurrentPosition();
bitmapList.add(media.getFrameAtTime(time,MediaMetadataRetriever.OPTION_CLOSEST));
imageCropAdapter.notifyItemInserted(bitmapList.size() - 1);
imageCropAdapter.notifyDataSetChanged();
Toast.makeText(getContext(), ""+time, Toast.LENGTH_SHORT).show();
}
}, new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "pre", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(mediaController);
videoView.start();
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
videoView.start();
}
});
mediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int i, int i1) {
}
});
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_view_video, container, false);
videoView = (VideoView) view.findViewById(R.id.videoView);
rvImageCrop = (RecyclerView) view.findViewById(R.id.rvImageCrop);
return view;
}
} | 4,416 | 0.64923 | 0.648324 | 115 | 37.408695 | 29.805134 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.669565 | false | false | 4 |
99ac842f47d6f64b49bd10f9926bd7571ff714f4 | 24,550,033,130,374 | 30ca2dc63d75ddaec9bdeb31ff1c836d2cf5dedf | /Projekat web David Vogronic in-20-2017/src/main/java/config/AppInitializer.java | 9c00b58421cff6a78183c29c2112c5a6c9a3d220 | [] | no_license | csNoMaD/proj-prodavnica | https://github.com/csNoMaD/proj-prodavnica | e2c0d9e5a29220d02447d90cdfa8a8a9ea2cb8a1 | 44a691e8453b3dc1b2c47cf39a2b109249fc6d9b | refs/heads/master | 2022-12-21T20:18:27.323000 | 2019-09-27T02:39:48 | 2019-09-27T02:39:48 | 204,159,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{MongoConfiguration.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
String[] init={"/"};
return init;
}
}
| UTF-8 | Java | 523 | java | AppInitializer.java | Java | [] | null | [] | package config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{MongoConfiguration.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
String[] init={"/"};
return init;
}
}
| 523 | 0.770554 | 0.770554 | 23 | 21.73913 | 28.270767 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
212a42862a22a3c2744e9abf7f52fe4bcacf78ef | 7,550,552,520,836 | ec5b1dfacd9942c660b0dfa0e840ccc9ecd3ff3e | /app/src/main/java/com/gxysj/shareysj/bean/LoginUserBean.java | b6910ca686565fa4e0c433af436b693b2f082889 | [] | no_license | ljrRookie/ShareYSJ | https://github.com/ljrRookie/ShareYSJ | 3e4c27a7d8e4ddc0c826bd2568cbd35920060953 | 56b14f4f336c433ce3073b083a97f2ef9bb07043 | refs/heads/master | 2020-03-21T12:12:36.116000 | 2018-06-25T03:51:34 | 2018-06-25T03:51:34 | 138,540,618 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gxysj.shareysj.bean;
/**
* Created by 林佳荣 on 2018/3/28.
* Github:https://github.com/ljrRookie
* Function :
*/
public class LoginUserBean {
/**
* code : 0
* userid : 2
* token : eabb18f0a40c9b3552370c9e1bc1d61e
*/
private String code;
private String userid;
private String token;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| UTF-8 | Java | 755 | java | LoginUserBean.java | Java | [
{
"context": "ckage com.gxysj.shareysj.bean;\n\n/**\n * Created by 林佳荣 on 2018/3/28.\n * Github:https://github.com/ljrRoo",
"end": 55,
"score": 0.9979782104492188,
"start": 52,
"tag": "NAME",
"value": "林佳荣"
},
{
"context": "by 林佳荣 on 2018/3/28.\n * Github:https://github.com/ljrRookie\n * Function :\n */\n\npublic class LoginUserBean {\n\n",
"end": 108,
"score": 0.9995816946029663,
"start": 99,
"tag": "USERNAME",
"value": "ljrRookie"
},
{
"context": "*\n * code : 0\n * userid : 2\n * token : eabb18f0a40c9b3552370c9e1bc1d61e\n */\n\n private String code;\n private Str",
"end": 247,
"score": 0.9769726395606995,
"start": 215,
"tag": "KEY",
"value": "eabb18f0a40c9b3552370c9e1bc1d61e"
}
] | null | [] | package com.gxysj.shareysj.bean;
/**
* Created by 林佳荣 on 2018/3/28.
* Github:https://github.com/ljrRookie
* Function :
*/
public class LoginUserBean {
/**
* code : 0
* userid : 2
* token : <KEY>
*/
private String code;
private String userid;
private String token;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 728 | 0.58255 | 0.546309 | 44 | 15.931818 | 14.389703 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 4 |
ea371f557a08af43ba4247af56312f5c18413d83 | 1,013,612,295,764 | 4f986f7139ba5d761523bf0038ad7da624d3e834 | /evpop/src/main/java/com/zx/evpop/jdbc/dao/ApiLogMapper.java | d50d70f9efa6a0f924447f9cef5daad5a22f0b8d | [] | no_license | jiangmenglin/zx | https://github.com/jiangmenglin/zx | 4e367ffa20a1bc6443f873519f2f681784ce0639 | cbd911db4dfbf85f3c963e4911ce12dd2235ad0a | refs/heads/master | 2020-04-30T09:36:59.759000 | 2019-03-20T14:50:17 | 2019-03-20T14:50:17 | 176,753,352 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zx.evpop.jdbc.dao;
import com.zx.evpop.jdbc.entity.ApiLog;
import com.zx.evpop.jdbc.entity.ApiLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ApiLogMapper {
int countByExample(ApiLogExample example);
int deleteByPrimaryKey(Long salId);
int insert(ApiLog record);
int insertSelective(ApiLog record);
List<ApiLog> selectByExampleWithBLOBs(ApiLogExample example);
List<ApiLog> selectByExample(ApiLogExample example);
ApiLog selectByPrimaryKey(Long salId);
int updateByExampleSelective(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByExampleWithBLOBs(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByExample(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByPrimaryKeySelective(ApiLog record);
int updateByPrimaryKeyWithBLOBs(ApiLog record);
int updateByPrimaryKey(ApiLog record);
} | UTF-8 | Java | 1,015 | java | ApiLogMapper.java | Java | [] | null | [] | package com.zx.evpop.jdbc.dao;
import com.zx.evpop.jdbc.entity.ApiLog;
import com.zx.evpop.jdbc.entity.ApiLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ApiLogMapper {
int countByExample(ApiLogExample example);
int deleteByPrimaryKey(Long salId);
int insert(ApiLog record);
int insertSelective(ApiLog record);
List<ApiLog> selectByExampleWithBLOBs(ApiLogExample example);
List<ApiLog> selectByExample(ApiLogExample example);
ApiLog selectByPrimaryKey(Long salId);
int updateByExampleSelective(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByExampleWithBLOBs(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByExample(@Param("record") ApiLog record, @Param("example") ApiLogExample example);
int updateByPrimaryKeySelective(ApiLog record);
int updateByPrimaryKeyWithBLOBs(ApiLog record);
int updateByPrimaryKey(ApiLog record);
} | 1,015 | 0.769458 | 0.769458 | 34 | 28.882353 | 31.389175 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617647 | false | false | 4 |
5d96dc7b8fb65b42428a627d1b3538a1e1c6612a | 25,907,242,740,652 | eca91c4474d16d2eaeca0e609f47efcf877fd209 | /app/src/main/java/com/rock/advancedday01/adapters/TeachAdapter.java | 9c17b8d889ff97b05e3ccb8af27e0c49ccbf5dc3 | [] | no_license | liuyanchao007/AdvancedDay01 | https://github.com/liuyanchao007/AdvancedDay01 | 6a64e894ea2e5371a42c53fc03cce8c514fe8c52 | 2709794d46b74e57c6985e7eb2689e9694e2da8c | refs/heads/master | 2021-01-10T23:39:18.842000 | 2016-10-09T15:16:55 | 2016-10-09T15:16:57 | 70,410,740 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rock.advancedday01.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rock.advancedday01.R;
import com.rock.advancedday01.model.Model;
import java.util.List;
/**
* RecyclerView 为Child的位置提供了一个计算方式
*
*/
public class TeachAdapter extends RecyclerView.Adapter<TeachAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = TeachAdapter.class.getSimpleName();
private List<Model> data;
private LayoutInflater inflater;
// 用来计算child位置
private RecyclerView mRecycler;
// 持有接口引用
private OnItemClickListener listener;
// 对外提供接口初始化方法
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
public TeachAdapter(Context context, List<Model> data) {
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* 获取数据源的数量 (itemView的数量)
* @return
*/
@Override
public int getItemCount() {
return data != null ? data.size() : 0;
}
/**
* 创建ViewHolder
* @param parent itemView的父控件
* @param viewType 根据ViewType去加载不同的布局 没有从 0 开始的限制了
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = inflater.inflate(R.layout.item,parent,false);
// 导入itemView,为itemView设置点击事件
itemView.setOnClickListener(this);
return new ViewHolder(itemView);
}
/**
* 加载数据
* @param holder 里面装的是View
* @param position 用来获取对应的数据源
*/
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(data.get(position).getName());
// 布局参数 设置高度
ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
params.height = data.get(position).getHeight();
holder.itemView.setLayoutParams(params);
}
/**
* 适配器绑定到RecyclerView的时候 会将绑定适配器的RecyclerView传递过来
* @param recyclerView
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecycler = recyclerView;
}
/**
* @param v 点击的View
*/
@Override
public void onClick(View v) {
// RecyclerView可以算出这是第几个child
int childAdapterPosition = mRecycler.getChildAdapterPosition(v);
Log.e(TAG, "onClick: " + childAdapterPosition );
if (listener != null) {
listener.onItemClick(childAdapterPosition,data.get(childAdapterPosition));
}
}
/**
* 接口回调
* ① 定义接口,定义接口中的 方法
* ② 在数据产生的地方持有接口,并提供初始化方法,在数据产生的时候调用接口中的方法
* ③ 在需要处理数据的地方实现接口,实现接口接口中的方法,并将接口传递到数据产生的地方
*/
public interface OnItemClickListener{
void onItemClick(int position,Model model);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView name;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.teach_item_name);
}
}
}
| UTF-8 | Java | 3,801 | java | TeachAdapter.java | Java | [] | null | [] | package com.rock.advancedday01.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.rock.advancedday01.R;
import com.rock.advancedday01.model.Model;
import java.util.List;
/**
* RecyclerView 为Child的位置提供了一个计算方式
*
*/
public class TeachAdapter extends RecyclerView.Adapter<TeachAdapter.ViewHolder> implements View.OnClickListener {
private static final String TAG = TeachAdapter.class.getSimpleName();
private List<Model> data;
private LayoutInflater inflater;
// 用来计算child位置
private RecyclerView mRecycler;
// 持有接口引用
private OnItemClickListener listener;
// 对外提供接口初始化方法
public void setListener(OnItemClickListener listener) {
this.listener = listener;
}
public TeachAdapter(Context context, List<Model> data) {
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* 获取数据源的数量 (itemView的数量)
* @return
*/
@Override
public int getItemCount() {
return data != null ? data.size() : 0;
}
/**
* 创建ViewHolder
* @param parent itemView的父控件
* @param viewType 根据ViewType去加载不同的布局 没有从 0 开始的限制了
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = inflater.inflate(R.layout.item,parent,false);
// 导入itemView,为itemView设置点击事件
itemView.setOnClickListener(this);
return new ViewHolder(itemView);
}
/**
* 加载数据
* @param holder 里面装的是View
* @param position 用来获取对应的数据源
*/
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText(data.get(position).getName());
// 布局参数 设置高度
ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
params.height = data.get(position).getHeight();
holder.itemView.setLayoutParams(params);
}
/**
* 适配器绑定到RecyclerView的时候 会将绑定适配器的RecyclerView传递过来
* @param recyclerView
*/
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecycler = recyclerView;
}
/**
* @param v 点击的View
*/
@Override
public void onClick(View v) {
// RecyclerView可以算出这是第几个child
int childAdapterPosition = mRecycler.getChildAdapterPosition(v);
Log.e(TAG, "onClick: " + childAdapterPosition );
if (listener != null) {
listener.onItemClick(childAdapterPosition,data.get(childAdapterPosition));
}
}
/**
* 接口回调
* ① 定义接口,定义接口中的 方法
* ② 在数据产生的地方持有接口,并提供初始化方法,在数据产生的时候调用接口中的方法
* ③ 在需要处理数据的地方实现接口,实现接口接口中的方法,并将接口传递到数据产生的地方
*/
public interface OnItemClickListener{
void onItemClick(int position,Model model);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView name;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.teach_item_name);
}
}
}
| 3,801 | 0.669581 | 0.665963 | 124 | 25.75 | 24.486212 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354839 | false | false | 4 |
dde2b4c414c1220cc36ab9619cbc1286a760e717 | 31,233,002,194,720 | e3b65ef6a19853643716a62bd10b187920d641b4 | /smqtt-rule/smqtt-rule-source/smqtt-rule-source-db/src/main/java/io/github/quickmsg/source/db/config/DruidConnectionProvider.java | b7f2f8be3e0dd78c82b6c175b86546de9631aa56 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | zhuzhengDL/smqtt | https://github.com/zhuzhengDL/smqtt | da19549dc74a6788b7fd770f8f1fbccd5aa54bc7 | bf03c12eaa737abd4539741ede79cec1bf12c72c | refs/heads/main | 2023-08-24T15:45:21.388000 | 2021-10-26T10:48:15 | 2021-10-26T10:48:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.quickmsg.source.db.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhaopeng
*/
@Slf4j
public class DruidConnectionProvider implements ConnectionProvider {
private DruidConnectionProvider() {
}
private static DruidConnectionProvider connectionProvider = new DruidConnectionProvider();
public static DruidConnectionProvider singleTon() {
return connectionProvider;
}
private DruidDataSource druidDataSource;
private AtomicInteger startUp = new AtomicInteger(0);
@Override
public void init(Properties properties) {
if (startUp.compareAndSet(0, 1)) {
try {
this.druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public Connection getConnection() {
try {
return druidDataSource.getConnection();
} catch (SQLException e) {
log.error("getConnection error", e);
return null;
}
}
@Override
public void shutdown() {
if (druidDataSource != null) {
druidDataSource.close();
}
}
} | UTF-8 | Java | 1,491 | java | DruidConnectionProvider.java | Java | [
{
"context": ".concurrent.atomic.AtomicInteger;\n\n\n/**\n * @author zhaopeng\n */\n@Slf4j\npublic class DruidConnectionProvider i",
"end": 345,
"score": 0.9995071887969971,
"start": 337,
"tag": "USERNAME",
"value": "zhaopeng"
}
] | null | [] | package io.github.quickmsg.source.db.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhaopeng
*/
@Slf4j
public class DruidConnectionProvider implements ConnectionProvider {
private DruidConnectionProvider() {
}
private static DruidConnectionProvider connectionProvider = new DruidConnectionProvider();
public static DruidConnectionProvider singleTon() {
return connectionProvider;
}
private DruidDataSource druidDataSource;
private AtomicInteger startUp = new AtomicInteger(0);
@Override
public void init(Properties properties) {
if (startUp.compareAndSet(0, 1)) {
try {
this.druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public Connection getConnection() {
try {
return druidDataSource.getConnection();
} catch (SQLException e) {
log.error("getConnection error", e);
return null;
}
}
@Override
public void shutdown() {
if (druidDataSource != null) {
druidDataSource.close();
}
}
} | 1,491 | 0.66063 | 0.656606 | 61 | 23.459017 | 24.046795 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327869 | false | false | 4 |
b0f48de764d5f6625e342875d9b7b213abad16e0 | 22,823,456,228,271 | d9c4ce91c509319e14050cc1d55f8ab942dfc8ec | /hw1/abby/poker/OldMain.java | cf9420395377bfae24a20866bc70bb5c15659575 | [] | no_license | leafinity/JavaPratice | https://github.com/leafinity/JavaPratice | 4024983b03474106abea25dc95f3a8dba9a53e9b | 99b41db3b8cc6de18b33c5679c123d57d3eddc33 | refs/heads/master | 2021-01-01T03:41:19.468000 | 2016-01-24T11:40:33 | 2016-01-24T11:40:33 | 59,670,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package abby.poker;
import java.util.*;
/**
* Created by abby on 9/27/15.
*/
public class OldMain {
private static int _DECK_SIZE = 54;
private static int _REGULAR_DECK_SIZE = 52;
private static int _RED_JOKER_POS = 52;
private static int _BLACK_JOKER_POS = 53;
private List<Player> _playerList;
private int _initPlayerNum;
private boolean _bonus;
private Card[] _deck;
private Stage _stage;
private enum Stage {
BASIC, BONUS, OVER;
public Stage nextStage(boolean somebodyWin, List<Player> playerList, boolean bonus) {
if (somebodyWin) {
if (this.compareTo(BASIC) == 0) {
System.out.println("Basic game over");
if (bonus) {
System.out.println("Continue");
return BONUS;
}
else
return OVER;
} else {
if(playerList.size() == 1) {
System.out.println("Bonus game over");
return OVER;
}
else
return BONUS;
}
} else {
return this;
}
}
}
public OldMain(int playerNum, boolean hasBonusGame) {
_initPlayerNum = playerNum;
_bonus = hasBonusGame;
_playerList = new ArrayList<Player>();
_deck = new Card[_DECK_SIZE];
_stage = Stage.BASIC;
}
public void start() {
_initGame();
System.out.println("Game start");
_checkSpecialWinCase();
while (_gameRound());
}
private boolean _gameRound() {
Player to = _getPlayerTo();
Player from = _getPlayerFrom();
Card draw = to.drawCard(from);
System.out.println("Player" + to.get_ID()
+ " draws a card from Player" + from.get_ID() + " " + draw.toString());
to.showHand();
from.showHand();
return _keepGoing(to, from);
}
private Player _getPlayerTo() {
return _playerList.get(0);
}
private Player _getPlayerFrom() {
return _playerList.get(1);
}
private void _checkSpecialWinCase() {
Player p1 = _playerList.get(0);
Player p2 = _playerList.get(1);
_stage = _stage.nextStage(_isSomebodyWin(p1, p2, false), _playerList, _bonus);
}
private boolean _keepGoing(Player to, Player from) {
_stage = _stage.nextStage(_isSomebodyWin(to, from, true), _playerList, _bonus);
return _stage.compareTo(Stage.OVER) != 0;
}
private boolean _isSomebodyWin(Player to, Player from, boolean goingNextRound) {
boolean somebodyWin = true;
if (to.isWin() && from.isWin()) {
int ID1 = to.get_ID() > from.get_ID()?
from.get_ID(): to.get_ID();
int ID2 = to.get_ID() < from.get_ID()?
from.get_ID(): to.get_ID();
System.out.println("Player" + ID1 + " and Player" + ID2 + " win");
//remove playerTo and playerFrom
_popPlayer();
_popPlayer();
} else if (to.isWin()) {
System.out.println("Player" + to.get_ID() + " wins");
//remove playerTo and playerFrom
_popPlayer();
} else if (from.isWin()) {
System.out.println("Player" + from.get_ID() + " wins");
//remove playerTo and playerFrom, add back PlayerTo
if (goingNextRound) {
Player p = _popPlayer();
_popPlayer();
_pushPlayer(p);
} else {
_playerList.remove(from);
}
} else {
somebodyWin = false;
//remove playerTo, and add back PlayerTo
if (goingNextRound) {
Player p = _popPlayer();
_pushPlayer(p);
}
}
return somebodyWin;
}
private void _initGame() {
_initPlayer();
_initDeck();
System.out.println("Deal cards");
_dealCard();
_showPlayersHand();
System.out.println("Drop cards");
_initHands();
_showPlayersHand();
}
private void _initPlayer() {
for (int i = 0; i < _initPlayerNum; i++) {
_playerList.add(new Player(i));
}
}
private void _initDeck() {
ArrayList<Card.Suit> suits = new ArrayList<Card.Suit>(4);
suits.add(Card.Suit.CLUB);
suits.add(Card.Suit.DIAMOND);
suits.add(Card.Suit.HEART);
suits.add(Card.Suit.SPADE);
for(int i = 0; i < _REGULAR_DECK_SIZE; i++) {
_deck[i] = new Card(suits.get(i % Card.Suit.num), (i / Card.Suit.num + 1));
}
// add Jokers
_deck[_RED_JOKER_POS] = new Card(Card.Suit.RED, 0);
_deck[_BLACK_JOKER_POS] = new Card(Card.Suit.BLACK, 0);
}
private void _dealCard(){
//shuffle: get a non-repeated array(set)
Random random = new Random();
Set<Integer> randomSet = new LinkedHashSet<Integer>();
while (randomSet.size() < _DECK_SIZE) {
Integer next = random.nextInt(_DECK_SIZE);
// Set will automatically do a containment check
randomSet.add(next);
}
Integer[] nonRepeatArray = randomSet.toArray(new Integer[randomSet.size()]);
/**test for spicail cases**/
/* Integer[] nonRepeatArray = new Integer[54];
for (int i = 0, target = 1; target < 15 ; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 1, target = 16; target < 30; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 2, target = 30; target < 43; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 3, target = 43; target < 54 ; target++) {
nonRepeatArray[i] = target;
i+=4;
}
nonRepeatArray[51] = 0;
nonRepeatArray[47] = 15;
*/
//deal
int playerNum = _playerList.size();
int handSize = _DECK_SIZE / playerNum;
int restSize = _DECK_SIZE % playerNum;
for(int i = 0; i < _DECK_SIZE; i++) {
_playerList.get(i % playerNum).setNewCard(_deck[nonRepeatArray[i]]);
}
}
private Player _popPlayer() {
Player p = _playerList.get(0);
_playerList.remove(p);
return p;
}
private void _pushPlayer(Player p) {
_playerList.add(p);
}
private void _initHands() {
_playerList.forEach(player -> player.initHand());
}
private void _showPlayersHand() {
_playerList.forEach(player -> player.showHand());
}
}
| UTF-8 | Java | 6,858 | java | OldMain.java | Java | [
{
"context": "bby.poker;\n\nimport java.util.*;\n\n/**\n * Created by abby on 9/27/15.\n */\npublic class OldMain {\n privat",
"end": 64,
"score": 0.9996144771575928,
"start": 60,
"tag": "USERNAME",
"value": "abby"
}
] | null | [] | package abby.poker;
import java.util.*;
/**
* Created by abby on 9/27/15.
*/
public class OldMain {
private static int _DECK_SIZE = 54;
private static int _REGULAR_DECK_SIZE = 52;
private static int _RED_JOKER_POS = 52;
private static int _BLACK_JOKER_POS = 53;
private List<Player> _playerList;
private int _initPlayerNum;
private boolean _bonus;
private Card[] _deck;
private Stage _stage;
private enum Stage {
BASIC, BONUS, OVER;
public Stage nextStage(boolean somebodyWin, List<Player> playerList, boolean bonus) {
if (somebodyWin) {
if (this.compareTo(BASIC) == 0) {
System.out.println("Basic game over");
if (bonus) {
System.out.println("Continue");
return BONUS;
}
else
return OVER;
} else {
if(playerList.size() == 1) {
System.out.println("Bonus game over");
return OVER;
}
else
return BONUS;
}
} else {
return this;
}
}
}
public OldMain(int playerNum, boolean hasBonusGame) {
_initPlayerNum = playerNum;
_bonus = hasBonusGame;
_playerList = new ArrayList<Player>();
_deck = new Card[_DECK_SIZE];
_stage = Stage.BASIC;
}
public void start() {
_initGame();
System.out.println("Game start");
_checkSpecialWinCase();
while (_gameRound());
}
private boolean _gameRound() {
Player to = _getPlayerTo();
Player from = _getPlayerFrom();
Card draw = to.drawCard(from);
System.out.println("Player" + to.get_ID()
+ " draws a card from Player" + from.get_ID() + " " + draw.toString());
to.showHand();
from.showHand();
return _keepGoing(to, from);
}
private Player _getPlayerTo() {
return _playerList.get(0);
}
private Player _getPlayerFrom() {
return _playerList.get(1);
}
private void _checkSpecialWinCase() {
Player p1 = _playerList.get(0);
Player p2 = _playerList.get(1);
_stage = _stage.nextStage(_isSomebodyWin(p1, p2, false), _playerList, _bonus);
}
private boolean _keepGoing(Player to, Player from) {
_stage = _stage.nextStage(_isSomebodyWin(to, from, true), _playerList, _bonus);
return _stage.compareTo(Stage.OVER) != 0;
}
private boolean _isSomebodyWin(Player to, Player from, boolean goingNextRound) {
boolean somebodyWin = true;
if (to.isWin() && from.isWin()) {
int ID1 = to.get_ID() > from.get_ID()?
from.get_ID(): to.get_ID();
int ID2 = to.get_ID() < from.get_ID()?
from.get_ID(): to.get_ID();
System.out.println("Player" + ID1 + " and Player" + ID2 + " win");
//remove playerTo and playerFrom
_popPlayer();
_popPlayer();
} else if (to.isWin()) {
System.out.println("Player" + to.get_ID() + " wins");
//remove playerTo and playerFrom
_popPlayer();
} else if (from.isWin()) {
System.out.println("Player" + from.get_ID() + " wins");
//remove playerTo and playerFrom, add back PlayerTo
if (goingNextRound) {
Player p = _popPlayer();
_popPlayer();
_pushPlayer(p);
} else {
_playerList.remove(from);
}
} else {
somebodyWin = false;
//remove playerTo, and add back PlayerTo
if (goingNextRound) {
Player p = _popPlayer();
_pushPlayer(p);
}
}
return somebodyWin;
}
private void _initGame() {
_initPlayer();
_initDeck();
System.out.println("Deal cards");
_dealCard();
_showPlayersHand();
System.out.println("Drop cards");
_initHands();
_showPlayersHand();
}
private void _initPlayer() {
for (int i = 0; i < _initPlayerNum; i++) {
_playerList.add(new Player(i));
}
}
private void _initDeck() {
ArrayList<Card.Suit> suits = new ArrayList<Card.Suit>(4);
suits.add(Card.Suit.CLUB);
suits.add(Card.Suit.DIAMOND);
suits.add(Card.Suit.HEART);
suits.add(Card.Suit.SPADE);
for(int i = 0; i < _REGULAR_DECK_SIZE; i++) {
_deck[i] = new Card(suits.get(i % Card.Suit.num), (i / Card.Suit.num + 1));
}
// add Jokers
_deck[_RED_JOKER_POS] = new Card(Card.Suit.RED, 0);
_deck[_BLACK_JOKER_POS] = new Card(Card.Suit.BLACK, 0);
}
private void _dealCard(){
//shuffle: get a non-repeated array(set)
Random random = new Random();
Set<Integer> randomSet = new LinkedHashSet<Integer>();
while (randomSet.size() < _DECK_SIZE) {
Integer next = random.nextInt(_DECK_SIZE);
// Set will automatically do a containment check
randomSet.add(next);
}
Integer[] nonRepeatArray = randomSet.toArray(new Integer[randomSet.size()]);
/**test for spicail cases**/
/* Integer[] nonRepeatArray = new Integer[54];
for (int i = 0, target = 1; target < 15 ; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 1, target = 16; target < 30; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 2, target = 30; target < 43; target++) {
nonRepeatArray[i] = target;
i+=4;
}
for (int i = 3, target = 43; target < 54 ; target++) {
nonRepeatArray[i] = target;
i+=4;
}
nonRepeatArray[51] = 0;
nonRepeatArray[47] = 15;
*/
//deal
int playerNum = _playerList.size();
int handSize = _DECK_SIZE / playerNum;
int restSize = _DECK_SIZE % playerNum;
for(int i = 0; i < _DECK_SIZE; i++) {
_playerList.get(i % playerNum).setNewCard(_deck[nonRepeatArray[i]]);
}
}
private Player _popPlayer() {
Player p = _playerList.get(0);
_playerList.remove(p);
return p;
}
private void _pushPlayer(Player p) {
_playerList.add(p);
}
private void _initHands() {
_playerList.forEach(player -> player.initHand());
}
private void _showPlayersHand() {
_playerList.forEach(player -> player.showHand());
}
}
| 6,858 | 0.505395 | 0.49548 | 226 | 29.345133 | 21.582224 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632743 | false | false | 4 |
ff5ea9ab33612931ab2a8dbdef5b562061cf899d | 22,960,895,187,817 | 5fd919f0ce5449a160546d5e1ca7b871e7f6c0ec | /mediniOCLInterpreter/source/OCLCommon/srcgen/org/oslo/ocl20/semantics/bridge/ModelElement.java | 7bf13caaa3c8f63eda2b0294cebc1b5f513b6fa7 | [] | no_license | mabilov/medini | https://github.com/mabilov/medini | 0a5ff0652b9176011b4d788a76a1cee8fc8da310 | 99ede9dcbc990c77f04a0169f0ee5b8735849247 | refs/heads/master | 2018-05-02T23:54:57.133000 | 2015-05-20T07:48:37 | 2015-05-20T07:48:37 | 35,933,295 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.oslo.ocl20.semantics.bridge;
import org.oslo.ocl20.semantics.SemanticsVisitable;
/**
* <!-- begin-user-doc --> A representation of the model object '<em><b>Model Element</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.oslo.ocl20.semantics.bridge.ModelElement#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see org.oslo.ocl20.semantics.bridge.BridgePackage#getModelElement()
* @model
* @generated
*/
public interface ModelElement extends SemanticsVisitable, Element {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute. <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear, there really should be more of a
* description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.oslo.ocl20.semantics.bridge.BridgePackage#getModelElement_Name()
* @model required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.oslo.ocl20.semantics.bridge.ModelElement#getName
* <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @param value
* the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @model kind="operation" dataType="org.oslo.ocl20.semantics.Object"
* @generated
*/
Object getDelegate();
} // ModelElement
| UTF-8 | Java | 1,609 | java | ModelElement.java | Java | [] | null | [] | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.oslo.ocl20.semantics.bridge;
import org.oslo.ocl20.semantics.SemanticsVisitable;
/**
* <!-- begin-user-doc --> A representation of the model object '<em><b>Model Element</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.oslo.ocl20.semantics.bridge.ModelElement#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see org.oslo.ocl20.semantics.bridge.BridgePackage#getModelElement()
* @model
* @generated
*/
public interface ModelElement extends SemanticsVisitable, Element {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute. <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear, there really should be more of a
* description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.oslo.ocl20.semantics.bridge.BridgePackage#getModelElement_Name()
* @model required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.oslo.ocl20.semantics.bridge.ModelElement#getName
* <em>Name</em>}' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @param value
* the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @model kind="operation" dataType="org.oslo.ocl20.semantics.Object"
* @generated
*/
Object getDelegate();
} // ModelElement
| 1,609 | 0.62399 | 0.615289 | 61 | 25.377048 | 28.65176 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.639344 | false | false | 4 |
a110748973620bad7a4550c88fcca3521361c07f | 32,779,190,420,184 | 217fb9048e3646bf8a05e446e9389a3fda09fc8a | /Main/src/com/eshsprogramming/dash_or_smash/processor/PedestrianController.java | 8dc13eb2173616bae0bde7f57e8fc2002f89b01d | [] | no_license | unidev-games/dash-or-smash | https://github.com/unidev-games/dash-or-smash | 26bb2bf94586d47812a60aa932fa402254fa7469 | 0f0c3783998680d918caa352efd941f473143443 | refs/heads/master | 2021-05-27T03:10:23.037000 | 2013-05-02T07:41:06 | 2013-05-02T07:41:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eshsprogramming.dash_or_smash.processor;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.eshsprogramming.dash_or_smash.DashOrSmash;
import com.eshsprogramming.dash_or_smash.model.entity.pedestrian.PedestrianEntity;
import com.eshsprogramming.dash_or_smash.view.Renderer;
/**
* Improved version of multi touch processor that can better deal with controlling pedestrians
*
* @author Benjamin Landers
*/
public class PedestrianController extends EntityController
{
int[] controlling = null;
boolean[] isControlling = null;
/**
* Creates a new MultiTouchProcessor instance. Also sets the max touches that it can deal with.
*
* @param maxTouches the max number of touches
*/
public PedestrianController(DashOrSmash game, int maxTouches)
{
super(game, maxTouches);
controlling = new int[maxTouches];
isControlling = new boolean[maxTouches];
}
/**
* updates the positions of the group of pedestrians
*
* @param pedestrians an array of pedestrians that are controllable
*/
public void updatePedestrians(Array<PedestrianEntity> pedestrians)
{
Vector2 temp;
PedestrianEntity pedestrian;
for(int i = 0; i < getPositions().length; i++)
{
temp = getPositions()[i];
if(temp.x == -5 || temp.y == -5)
{
continue;
}
for(int i2 = 0; i2 < pedestrians.size; i2++)
{
pedestrian = pedestrians.get(i2);
if(controlling[i] == i2)
{
if(temp.x - .5f < pedestrian.getPosition().x + PedestrianEntity.SIZEX && temp.x + .5f
> pedestrian.getPosition().x)
{
pedestrian.getPosition().x = temp.x - PedestrianEntity.SIZEX / 2;
isControlling[i] = true;
}
}
else
{
if(!isControlling[i] && temp.x < pedestrian.getPosition().x + PedestrianEntity.SIZEX && temp.x
> pedestrian.getPosition().x)
{
pedestrian.getPosition().x = temp.x - PedestrianEntity.SIZEX / 2;
controlling[i] = i2;
isControlling[i] = true;
}
}
pedestrian.getPosition().x = (pedestrian.getPosition().x > 0) ? pedestrian.getPosition().x : 0;
pedestrian.getPosition().x = (pedestrian.getPosition().x <
Renderer.CAMERA_WIDTH - PedestrianEntity.SIZEX) ? pedestrian.getPosition().x :
Renderer.CAMERA_WIDTH - PedestrianEntity.SIZEX;
}
isControlling[i] = false;
}
}
}
| UTF-8 | Java | 2,938 | java | PedestrianController.java | Java | [
{
"context": "er deal with controlling pedestrians\n *\n * @author Benjamin Landers\n */\npublic class PedestrianController extends Ent",
"end": 452,
"score": 0.999669075012207,
"start": 436,
"tag": "NAME",
"value": "Benjamin Landers"
}
] | null | [] | package com.eshsprogramming.dash_or_smash.processor;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.eshsprogramming.dash_or_smash.DashOrSmash;
import com.eshsprogramming.dash_or_smash.model.entity.pedestrian.PedestrianEntity;
import com.eshsprogramming.dash_or_smash.view.Renderer;
/**
* Improved version of multi touch processor that can better deal with controlling pedestrians
*
* @author <NAME>
*/
public class PedestrianController extends EntityController
{
int[] controlling = null;
boolean[] isControlling = null;
/**
* Creates a new MultiTouchProcessor instance. Also sets the max touches that it can deal with.
*
* @param maxTouches the max number of touches
*/
public PedestrianController(DashOrSmash game, int maxTouches)
{
super(game, maxTouches);
controlling = new int[maxTouches];
isControlling = new boolean[maxTouches];
}
/**
* updates the positions of the group of pedestrians
*
* @param pedestrians an array of pedestrians that are controllable
*/
public void updatePedestrians(Array<PedestrianEntity> pedestrians)
{
Vector2 temp;
PedestrianEntity pedestrian;
for(int i = 0; i < getPositions().length; i++)
{
temp = getPositions()[i];
if(temp.x == -5 || temp.y == -5)
{
continue;
}
for(int i2 = 0; i2 < pedestrians.size; i2++)
{
pedestrian = pedestrians.get(i2);
if(controlling[i] == i2)
{
if(temp.x - .5f < pedestrian.getPosition().x + PedestrianEntity.SIZEX && temp.x + .5f
> pedestrian.getPosition().x)
{
pedestrian.getPosition().x = temp.x - PedestrianEntity.SIZEX / 2;
isControlling[i] = true;
}
}
else
{
if(!isControlling[i] && temp.x < pedestrian.getPosition().x + PedestrianEntity.SIZEX && temp.x
> pedestrian.getPosition().x)
{
pedestrian.getPosition().x = temp.x - PedestrianEntity.SIZEX / 2;
controlling[i] = i2;
isControlling[i] = true;
}
}
pedestrian.getPosition().x = (pedestrian.getPosition().x > 0) ? pedestrian.getPosition().x : 0;
pedestrian.getPosition().x = (pedestrian.getPosition().x <
Renderer.CAMERA_WIDTH - PedestrianEntity.SIZEX) ? pedestrian.getPosition().x :
Renderer.CAMERA_WIDTH - PedestrianEntity.SIZEX;
}
isControlling[i] = false;
}
}
}
| 2,928 | 0.544248 | 0.538121 | 84 | 33.976189 | 32.151047 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.380952 | false | false | 4 |
a53b7b35a2986f193ddbbc994fc5f60c79fba30a | 1,640,677,510,219 | ec5a1acd64b87978d7d8108fdac0f119b17924fb | /src/main/java/techit/rest/security/LoginController.java | 9e041bc37003f6208721b96807abfb3eedb47346 | [] | no_license | Jagan0411/TechIT_SpringMVC | https://github.com/Jagan0411/TechIT_SpringMVC | da0c02ee7a47a68636ae22a9be2cb2487946d7c5 | 112e373a83ed751c5d312c78283280b9dcfb59bb | refs/heads/master | 2023-05-12T20:43:36.638000 | 2022-01-06T08:14:08 | 2022-01-06T08:14:08 | 166,607,440 | 0 | 0 | null | false | 2023-05-09T17:56:12 | 2019-01-20T00:19:56 | 2022-01-06T08:14:11 | 2023-05-09T17:56:09 | 46 | 0 | 0 | 2 | Java | false | false | package techit.rest.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import techit.model.User;
import techit.model.dao.UserDao;
import techit.rest.error.RestException;
@RestController
public class LoginController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {
if (username == null || password == null) {
throw new RestException(401, "Username and/or password is null");
}
User user = userDao.getUser(username);
if (user == null) {
throw new RestException(401, "Invalid Username and/or password");
}
if (!SecurityUtil.checkPasswordMatch(password, user.getPassword())) {
throw new RestException(401, "Invalid Username and/or password");
}
String compactJws = SecurityUtil.convertToJWT(username);
return compactJws;
}
}
| UTF-8 | Java | 1,296 | java | LoginController.java | Java | [] | null | [] | package techit.rest.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import techit.model.User;
import techit.model.dao.UserDao;
import techit.rest.error.RestException;
@RestController
public class LoginController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password) {
if (username == null || password == null) {
throw new RestException(401, "Username and/or password is null");
}
User user = userDao.getUser(username);
if (user == null) {
throw new RestException(401, "Invalid Username and/or password");
}
if (!SecurityUtil.checkPasswordMatch(password, user.getPassword())) {
throw new RestException(401, "Invalid Username and/or password");
}
String compactJws = SecurityUtil.convertToJWT(username);
return compactJws;
}
}
| 1,296 | 0.710648 | 0.703704 | 39 | 32.23077 | 26.365732 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 4 |
ba92d745d3f63e04cf2b81eb6088e6702eb70419 | 14,620,068,698,020 | d3fa8ded9d393ba9b03388ba7f05fc559cf31d1e | /Codes/probe/monitor/impl/src/com/broada/carrier/monitor/method/cli/parser/ParserRule.java | 78ad4e05ac40918635422b0e06a0e50ce010e8ce | [] | no_license | lengxu/YouYun | https://github.com/lengxu/YouYun | e20c4d8f553ccb245e96de177a67f776666e986f | b0ad8fd0b0e70dd2445cecb9ae7b00f7e0a20815 | refs/heads/master | 2020-09-13T22:30:49.642000 | 2017-11-27T03:13:34 | 2017-11-27T03:13:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.broada.carrier.monitor.method.cli.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* @pdOid 1be855af-2742-4a8b-955e-541abc1b803a
* 解析规则类
*
*/
public class ParserRule {
/** @pdOid f3b4f01d-a352-46c0-913a-6c6562f68eb7 */
private int start;
/** @pdOid 7331f77d-5359-4347-8e63-d389ff2ea8ab */
private int end;
/** @pdOid d6cfd030-444b-4517-88e9-ff7ffbf00753 */
private String delimeter;
private Pattern delimeterPattern;
/** @pdOid 39cadadc-50db-476a-bbf9-5135921bbc96 */
private List<ParserItem> parserItems = new ArrayList<ParserItem>();
public Bsh bsh;
private String datatype;
/**
* 数据表格的标题行的行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为-1,表示未指定标题行号。
*/
private int titleLineNo = -1;
/**
* 数据表格的标题行的关键字。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为null,表示未指定标题行关键字。
*/
private String titleKeyword = null;
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
private String titleIgnore;
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
private Pattern titleIgnorePattern;
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public Bsh getBsh() {
return bsh;
}
public void setBsh(Bsh bsh) {
this.bsh = bsh;
}
public String getDelimeter() {
return delimeter;
}
public void setDelimeter(String delimeter) {
this.delimeter = delimeter;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public List<ParserItem> getParserItems() {
return parserItems;
}
public void addParserItem(ParserItem parserItem) {
parserItems.add(parserItem);
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
/**
* 数据表格的标题行的行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为-1,表示未指定标题行号。
*/
public int getTitleLineNo() {
return titleLineNo;
}
/**
* 数据表格的标题行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若返回-1,表示标题行未找到。
*/
public int getTitleLineNo(String[] lines) {
if (titleLineNo >= 0)
return titleLineNo < lines.length ? titleLineNo : -1;
if (titleKeyword != null) {
for (int i = 0; i<lines.length; i++) {
if (StringUtils.contains(lines[i], titleKeyword))
return i;
}
}
return -1;
}
/**
* 数据表格的标题行的行号或关键字。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
*/
public void setTitle(String title) {
titleLineNo = -1;
titleKeyword = null;
try {
this.titleLineNo = Integer.parseInt(title);
} catch (NumberFormatException e) {
titleKeyword = title;
}
}
/**
* 是否有数据表格的标题行。
*/
public boolean hasTitle() {
return titleLineNo >= 0 || titleKeyword != null;
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
public String getTitleIgnore() {
return titleIgnore;
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
public void setTitleIgnore(String titleIgnore) {
if (StringUtils.isBlank(titleIgnore)) {
this.titleIgnore = null;
titleIgnorePattern = null;
} else {
this.titleIgnore = titleIgnore.trim();
titleIgnorePattern = Pattern.compile(this.titleIgnore);
}
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
Pattern getTitleIgnorePattern() {
return titleIgnorePattern;
}
public Pattern getDelimeterPattern() {
if (delimeterPattern == null) {
if (delimeter.endsWith("+"))
delimeterPattern = Pattern.compile(delimeter);
else
delimeterPattern = Pattern.compile(delimeter + "+");
}
return delimeterPattern;
}
} | UTF-8 | Java | 5,319 | java | ParserRule.java | Java | [] | null | [] | package com.broada.carrier.monitor.method.cli.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* @pdOid 1be855af-2742-4a8b-955e-541abc1b803a
* 解析规则类
*
*/
public class ParserRule {
/** @pdOid f3b4f01d-a352-46c0-913a-6c6562f68eb7 */
private int start;
/** @pdOid 7331f77d-5359-4347-8e63-d389ff2ea8ab */
private int end;
/** @pdOid d6cfd030-444b-4517-88e9-ff7ffbf00753 */
private String delimeter;
private Pattern delimeterPattern;
/** @pdOid 39cadadc-50db-476a-bbf9-5135921bbc96 */
private List<ParserItem> parserItems = new ArrayList<ParserItem>();
public Bsh bsh;
private String datatype;
/**
* 数据表格的标题行的行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为-1,表示未指定标题行号。
*/
private int titleLineNo = -1;
/**
* 数据表格的标题行的关键字。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为null,表示未指定标题行关键字。
*/
private String titleKeyword = null;
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
private String titleIgnore;
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
private Pattern titleIgnorePattern;
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public Bsh getBsh() {
return bsh;
}
public void setBsh(Bsh bsh) {
this.bsh = bsh;
}
public String getDelimeter() {
return delimeter;
}
public void setDelimeter(String delimeter) {
this.delimeter = delimeter;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public List<ParserItem> getParserItems() {
return parserItems;
}
public void addParserItem(ParserItem parserItem) {
parserItems.add(parserItem);
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
/**
* 数据表格的标题行的行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若为-1,表示未指定标题行号。
*/
public int getTitleLineNo() {
return titleLineNo;
}
/**
* 数据表格的标题行号。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
* 若返回-1,表示标题行未找到。
*/
public int getTitleLineNo(String[] lines) {
if (titleLineNo >= 0)
return titleLineNo < lines.length ? titleLineNo : -1;
if (titleKeyword != null) {
for (int i = 0; i<lines.length; i++) {
if (StringUtils.contains(lines[i], titleKeyword))
return i;
}
}
return -1;
}
/**
* 数据表格的标题行的行号或关键字。标题行表明表格中数据的含义。
* 它可以用来决定哪些数据是可获取的。
* 由于操作系统的版本问题,可能导致某些监测数据在某些版本上不可获取,如linux的io监测器。
*/
public void setTitle(String title) {
titleLineNo = -1;
titleKeyword = null;
try {
this.titleLineNo = Integer.parseInt(title);
} catch (NumberFormatException e) {
titleKeyword = title;
}
}
/**
* 是否有数据表格的标题行。
*/
public boolean hasTitle() {
return titleLineNo >= 0 || titleKeyword != null;
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
public String getTitleIgnore() {
return titleIgnore;
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
public void setTitleIgnore(String titleIgnore) {
if (StringUtils.isBlank(titleIgnore)) {
this.titleIgnore = null;
titleIgnorePattern = null;
} else {
this.titleIgnore = titleIgnore.trim();
titleIgnorePattern = Pattern.compile(this.titleIgnore);
}
}
/**
* 数据表格的标题行的被忽略的字符串的正则表达式。匹配的字符串部分将被忽略。
*/
Pattern getTitleIgnorePattern() {
return titleIgnorePattern;
}
public Pattern getDelimeterPattern() {
if (delimeterPattern == null) {
if (delimeter.endsWith("+"))
delimeterPattern = Pattern.compile(delimeter);
else
delimeterPattern = Pattern.compile(delimeter + "+");
}
return delimeterPattern;
}
} | 5,319 | 0.664996 | 0.637434 | 189 | 20.121693 | 18.032042 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.396825 | false | false | 4 |
439bc083e1a43f17080af368093bb48d66f2010a | 7,267,084,684,991 | 64a9afc21a8364e895c5ad6b7c1c29a4d207c58d | /src/main/java/com/example/demo/system/mysql/entity/Node.java | 6339e3a7191da4299e52c6c7ba125085eb4ce15d | [] | no_license | AIteach/AIteach | https://github.com/AIteach/AIteach | 589bc785f3557f7e2f0eb35ec8d45fe69a02634f | 7793afb5b6fd3b58013b9515dbea1f96dc2c199d | refs/heads/master | 2023-04-08T05:29:56.094000 | 2020-07-28T15:24:57 | 2020-07-28T15:24:57 | 253,407,150 | 0 | 0 | null | false | 2023-03-23T20:34:08 | 2020-04-06T05:51:06 | 2020-07-28T15:25:27 | 2023-03-23T20:34:04 | 45,648 | 0 | 0 | 2 | JavaScript | false | false | /**
* 时间:2018年4月6日
* 地点:
* 包名:com.example.demo.system.entity
* 项目名:grap
*/
package com.example.demo.system.mysql.entity;
import com.example.demo.system.es.esentity.EsNode;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
/**
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity(name = "node")
public class Node implements Serializable { //结点信息
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int category;
private String name;
private String value;
private int symbolSize;
private String url = "/login";
public Node(String name, int category, int symbolSize, String url, int nodeId) {
this.name = name;
this.category = category;
this.symbolSize = symbolSize;
this.url = url;
this.id = nodeId;
}
public Node(String name, int category, int symbolSize, String url) {
this.name = name;
this.category = category;
this.symbolSize = symbolSize;
this.url = url;
}
public EsNode toEs() {
EsNode esNode = new EsNode();
esNode.setValue(this.value);
esNode.setUrl(this.url);
esNode.setSymbolSize(this.symbolSize);
esNode.setName(this.name);
esNode.setId(this.id);
esNode.setCategory(this.category);
return esNode;
}
}
| UTF-8 | Java | 1,564 | java | Node.java | Java | [
{
"context": "e.Id;\nimport java.io.Serializable;\n\n/**\n * @author Administrator\n */\n@Data\n@AllArgsConstructor\n@NoArgsConstructor\n",
"end": 398,
"score": 0.7449874877929688,
"start": 385,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /**
* 时间:2018年4月6日
* 地点:
* 包名:com.example.demo.system.entity
* 项目名:grap
*/
package com.example.demo.system.mysql.entity;
import com.example.demo.system.es.esentity.EsNode;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
/**
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity(name = "node")
public class Node implements Serializable { //结点信息
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int category;
private String name;
private String value;
private int symbolSize;
private String url = "/login";
public Node(String name, int category, int symbolSize, String url, int nodeId) {
this.name = name;
this.category = category;
this.symbolSize = symbolSize;
this.url = url;
this.id = nodeId;
}
public Node(String name, int category, int symbolSize, String url) {
this.name = name;
this.category = category;
this.symbolSize = symbolSize;
this.url = url;
}
public EsNode toEs() {
EsNode esNode = new EsNode();
esNode.setValue(this.value);
esNode.setUrl(this.url);
esNode.setSymbolSize(this.symbolSize);
esNode.setName(this.name);
esNode.setId(this.id);
esNode.setCategory(this.category);
return esNode;
}
}
| 1,564 | 0.663386 | 0.659449 | 62 | 23.580645 | 18.145067 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 4 |
9de81ecd941dc7f866d833173192c6d4ab71241a | 10,746,008,205,891 | c529be14df59234512b07e00b33eb543569ad664 | /server/src/main/java/edu/colostate/cs/cs414/cteam/p4/controller/ServerListener.java | f485573466dd7b350ed4a430bff4c13274e0521a | [] | no_license | cs414-C-Team/cs414-f18-001-C-Team | https://github.com/cs414-C-Team/cs414-f18-001-C-Team | befd9b52f74b8f6d8ca433300c63d70869d506cc | dfe2d0fdd2cf7484def0cc0ce2e7ea798eb5df1e | refs/heads/master | 2020-03-29T00:46:04.816000 | 2018-12-13T03:45:56 | 2018-12-13T03:45:56 | 149,355,210 | 4 | 0 | null | false | 2018-12-13T03:45:57 | 2018-09-18T21:38:35 | 2018-12-10T06:52:50 | 2018-12-13T03:45:56 | 10,235 | 2 | 0 | 37 | Java | false | null | package edu.colostate.cs.cs414.cteam.p4.controller;
import java.io.PrintWriter;
public class ServerListener {
FacadeController controller = new FacadeController();
public void ServerListener() {
}
public void clientConnected(ClientInstance client, PrintWriter out) {
// TODO Auto-generated method stub
}
public void clientDisconnected(ClientInstance client) {
// TODO Auto-generated method stub
}
public String recivedInput(ClientInstance client, String msg) {
// TODO Auto-generated method stub
if (msg == null || msg.equals("")) {
return "";
}
System.out.println("System: recieved message: " + msg);
switch(msg.charAt(0)) {
case '1':
controller.newMatch(msg.substring(1,msg.length()));
System.out.println("System: stored match for client " + client.toString());
return "System: Match created for client " + client.toString();
case '2':
System.out.println("Code 2: Store new invite.");
return controller.storeInvite(msg.substring(1, msg.length()));
case '3':
int result = controller.processTurn(msg.substring(1, msg.length()));
if(result == -1) {
return "failure";
} else if (result == 0) {
return "success";
} else {
return Integer.toString(result);
}
case '4':
return Integer.toString(controller.register(msg.substring(1,msg.length())));
case '5':
return Integer.toString(controller.login(msg.substring(1,msg.length())));
case '6':
return controller.retrieveMatch(msg.substring(1,msg.length()));
case '7':
return Integer.toString(controller.newGameID());
case '8':
return controller.searchUsers(msg.substring(1,msg.length()));
case '9':
System.out.println("Code 9: Query matches");
return controller.queryMatches(msg.substring(1,msg.length()));
default:
return "System:ERROR: Unrecognizable message format.";
}
}
public void serverClosed() {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 1,933 | java | ServerListener.java | Java | [] | null | [] | package edu.colostate.cs.cs414.cteam.p4.controller;
import java.io.PrintWriter;
public class ServerListener {
FacadeController controller = new FacadeController();
public void ServerListener() {
}
public void clientConnected(ClientInstance client, PrintWriter out) {
// TODO Auto-generated method stub
}
public void clientDisconnected(ClientInstance client) {
// TODO Auto-generated method stub
}
public String recivedInput(ClientInstance client, String msg) {
// TODO Auto-generated method stub
if (msg == null || msg.equals("")) {
return "";
}
System.out.println("System: recieved message: " + msg);
switch(msg.charAt(0)) {
case '1':
controller.newMatch(msg.substring(1,msg.length()));
System.out.println("System: stored match for client " + client.toString());
return "System: Match created for client " + client.toString();
case '2':
System.out.println("Code 2: Store new invite.");
return controller.storeInvite(msg.substring(1, msg.length()));
case '3':
int result = controller.processTurn(msg.substring(1, msg.length()));
if(result == -1) {
return "failure";
} else if (result == 0) {
return "success";
} else {
return Integer.toString(result);
}
case '4':
return Integer.toString(controller.register(msg.substring(1,msg.length())));
case '5':
return Integer.toString(controller.login(msg.substring(1,msg.length())));
case '6':
return controller.retrieveMatch(msg.substring(1,msg.length()));
case '7':
return Integer.toString(controller.newGameID());
case '8':
return controller.searchUsers(msg.substring(1,msg.length()));
case '9':
System.out.println("Code 9: Query matches");
return controller.queryMatches(msg.substring(1,msg.length()));
default:
return "System:ERROR: Unrecognizable message format.";
}
}
public void serverClosed() {
// TODO Auto-generated method stub
}
}
| 1,933 | 0.68598 | 0.67253 | 71 | 26.225351 | 25.352833 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.366197 | false | false | 4 |
d0584a094bfdae77083072c6e3a9c24a572d3361 | 5,617,817,269,557 | 086eb9716aedda6ada7bcc7d37470c0f7d57e7cf | /src/main/java/GESTIHIPER_MAVEN/GESTIHIPER_MAVEN/Hipermercado.java | 370d699839c85759f35cfc8ac78168c9e9f33f36 | [] | no_license | LuisLSilva/GESTIHIPER-MAVEN | https://github.com/LuisLSilva/GESTIHIPER-MAVEN | b5326acf1c0ec4c5683e1ba81acb0d32fe37f0a3 | bc064cdf8ceefc6e8db8a6b62057708a66e46b78 | refs/heads/master | 2020-04-26T17:10:10.656000 | 2019-03-08T17:22:03 | 2019-03-08T17:22:03 | 173,704,631 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package GESTIHIPER_MAVEN.GESTIHIPER_MAVEN;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Hipermercado {
private List<Ccliente> listCcliente = new ArrayList<Ccliente>();
private List<Cproduto> listCproduto = new ArrayList<Cproduto>();
private List<Compra> listCompra = new ArrayList<Compra>();
private Ccliente catalogoClientes;
private Cproduto catalogoProdutos;
private Validador validador;
private HashSet<String> clientesDistintos = new HashSet<String>();
private Map<String, DadosCliente> sortedMap;
private Map<String, DadosProduto> sortedMapCXP;
public Hipermercado(Validador validador) {
super();
catalogoClientes = new Ccliente();
catalogoProdutos = new Cproduto();
this.validador = validador;
}
public void addCompra(Compra compra){
listCompra.add(compra);
catalogoProdutos.addCompraProduto(compra);
catalogoClientes.addCompraCliente(compra);
}
public List<Ccliente> getListCcliente() {
return listCcliente;
}
public void setListCcliente(List<Ccliente> listCcliente) {
this.listCcliente = listCcliente;
}
public Ccliente getCatalogoClientes() {
return catalogoClientes;
}
public void setCatalogoClientes(Ccliente catalogoClientes) {
this.catalogoClientes = catalogoClientes;
}
public Cproduto getCatalogoProdutos() {
return catalogoProdutos;
}
public void setCatalogoProdutos(Cproduto catalogoProdutos) {
this.catalogoProdutos = catalogoProdutos;
}
public List<Cproduto> getListCproduto() {
return listCproduto;
}
public void setListCproduto(List<Cproduto> listCproduto) {
this.listCproduto = listCproduto;
}
public List<Compra> getListCompra() {
return listCompra;
}
public void setListCompra(List<Compra> listCompra) {
this.listCompra = listCompra;
}
public void addCcliente(Ccliente ccliente) {
listCcliente.add(ccliente);
}
public void addCproduto(Cproduto cproduto) {
listCproduto.add(cproduto);
}
@Override
public String toString() {
return "Hipermercado [listCcliente=" + listCcliente + ", listCproduto=" + listCproduto + ", listCompra="
+ listCompra+"]";
}
//Query 1 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------
public void totalComprasMes() {
int quantidadeTotal = 0;
for (int j = 1; j < 13; j++) {
for (int i = 0; i < this.getListCompra().size(); i++) {
if (j == this.getListCompra().get(i).getMes()) {
quantidadeTotal = quantidadeTotal + this.getListCompra().get(i).getQuantidade();
}
}
System.out.println("O mês:" + j + " foram feitas:" + quantidadeTotal+" compras.");
quantidadeTotal = 0;
}
}
//Query 2 - Consulta Estatística -------------------------------------------------------------------------------------------------------------------------------------
public void totalGlobal() {
double totalMes = 0;
double totalGlobal = 0;
for (int j = 1; j < 13; j++) {
for (int i = 0; i < this.getListCompra().size(); i++) {
if (j == this.getListCompra().get(i).getMes()) {
totalMes = totalMes
+ this.getListCompra().get(i).getPreco() * this.getListCompra().get(i).getQuantidade();
}
}
System.out.println("O mês:" + j + " totalidade do mes:" + totalMes + " euros");
double temp = totalMes;
totalMes = 0;
totalGlobal += temp;
}
System.out.println("\nA faturaçãoo Global: " + totalGlobal + " euros");
}
//Query 3 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------------------------------------------------
public void clientesDistintos() {
for (int j = 1; j < 13; j++) {
for (Compra i : this.getListCompra()) {
if (j == i.getMes()) {
this.clientesDistintos.add(i.getIdCliente());
}
}
System.out.println("\nClientes do mes: " + j);
for (String temp : clientesDistintos) {
System.out.println(temp);
}
clientesDistintos.clear();
}
}
//Query 4 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void comprasInvalidas() {
System.out.println("Existem " + validador.getComprasInvalidas().size()
+ " compras inv�lidas\nConsulte o ficheiro ComprasInvalidas.txt");
try {
BufferedWriter objWriter = new BufferedWriter(new FileWriter("ComprasInvalidas.txt"));
String newLine = System.getProperty("line.separator");
for (int i = 0; i < validador.getComprasInvalidas().size(); i++) {
objWriter.write(validador.getComprasInvalidas().get(i) + " " + newLine);
}
objWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Query 1 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void produtosNaoComprados() {
int cnt=0;
Map<String, DadosProduto> tMap = new TreeMap<String, DadosProduto>(getCatalogoProdutos().getGavetaProdutos());
System.out.println("Códigos de produtos nunca comprado:");
for(Entry<String, DadosProduto> entry: tMap.entrySet()){
if(entry.getValue()== null){
System.out.println("ID do Produto: " + entry.getKey());
cnt++;
}
}
System.out.println("\nO número total de produtos nunca comprados: "+cnt);
}
// Query 2 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void clientesNuncaCompraram(){
int cnt=0;
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(getCatalogoClientes().getGavetaClientes());
System.out.println("Códigos de clientes que nunca compraram:");
for(Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue()== null){
System.out.println("ID do Cliente: " + entry.getKey());
cnt++;
}
}
System.out.println("\nO número de clientes que nunca compraram: "+cnt);
}
// Query 3 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void numeroComprasEclientesPorMes() {
System.out.print("Insira um mês de 1 a 12: ");
Scanner sc = new Scanner(System.in);
int mes = sc.nextInt();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getMensal().containsKey(mes)) {
System.out.println("Produto comprado: " + entry.getKey() + ", Quantidade: "
+ entry.getValue().getMensal().get(mes).getTotalCompras() + ", Clientes Distintos: "
+ entry.getValue().getMensal().get(mes).getClientesDistintos());
}
}
}
}
// Query 4 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoClienteParaMes() {
System.out.print("Introduza o código de um cliente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("\nO cliente "+input+":");
for (Entry<String, DadosCliente> entry : getCatalogoClientes().getGavetaClientes().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdCliente().equals(input)) {
for (Entry<Integer, DadosMesCliente> entry2 : entry.getValue().getMensalCliente().entrySet()) {
System.out.println("No Mês:"+entry2.getKey() + ", fez um total número de compras:" + entry2.getValue().getTotalCompras() + ", adquiriu os seguintes produtos:"
+ entry2.getValue().getProdutosDistintos() + " e gastou na totalidade:" + entry2.getValue().getFaturacao()+" euros");
}
}
}
}
}
// Query 5 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoProdutoMesaMes() {
System.out.print("Introduza um código de um produto existente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdProduto().equals(input)) {
for (Entry<Integer, DadosMesProduto> entry2 : entry.getValue().getMensal().entrySet()) {
System.out.println("No Mês: " + entry2.getKey() + ", Total Número de Compras: "
+ entry2.getValue().getTotalCompras() + ", Clientes Distintos: "
+ entry2.getValue().getClientesDistintos() + ", Total Faturado: "
+ entry2.getValue().getFaturacao()+" euros.");
}
}
}
}
}
//Query 6 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoProdutoNP() {
System.out.print("Introduza um código de um produto existente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdProduto().equals(input)) {
for (Entry<Integer, DadosMesProduto> entry2 : entry.getValue().getMensal().entrySet()) {
System.out.println("No mês: " + entry2.getKey() + ", Total Número de Compras em modo Promoção: "
+ entry2.getValue().getComprasModoP() + ", Total Número de Compras em Modo Normal: "
+ entry2.getValue().getComprasModoN() + ", Total Faturado: "
+ entry2.getValue().getFaturacao());
}
}
}
}
}
// Query 7 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void clienteListaProdutos() {
System.out.print("Introduza um código de um cliente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("\nO cliente " + input + " comprou os seguintes produtos:");
DadosCliente dadosClienteInput = this.getCatalogoClientes().getGavetaClientes().get(input);
if (dadosClienteInput == null)
return;
Map<String, DadosClienteProduto> tMap = new TreeMap<String, DadosClienteProduto>(dadosClienteInput.getQuantidadeProdutoPorCliente());
if (tMap == null)
return;
Map<String, DadosClienteProduto> sortedMap = sortByValue(tMap);
printMapPQ(sortedMap);
}
public static <K,V> void printMapPQ(Map<K,V> map){
for(Map.Entry<K, V> entry: map.entrySet()){
System.out.println("Produto comprado: " + entry.getKey() + " "+entry.getValue());
}
}
// Ordena por valor descendente, o conte�do do HashMap
public static Map<String, DadosClienteProduto> sortByValue(Map<String, DadosClienteProduto> unsortMap) {
List<Map.Entry<String, DadosClienteProduto>> list = new LinkedList<Map.Entry<String, DadosClienteProduto>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosClienteProduto>>() {
public int compare(Map.Entry<String, DadosClienteProduto> o1, Map.Entry<String, DadosClienteProduto> o2) {
return o2.getValue().getQuantidade().compareTo(o1.getValue().getQuantidade());
}
});
Map<String, DadosClienteProduto> sortedMap = new LinkedHashMap<String, DadosClienteProduto>();
for (Map.Entry<String, DadosClienteProduto> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
// Query 8 - Consulta Interactiva ---------------------------------------------------------------------------------------------------------------------------------------
public void conjuntoXprodutos() {
Map<String, DadosProduto> tMap = new TreeMap<String, DadosProduto>(this.getCatalogoProdutos().getGavetaProdutos());
int cnt = -1;
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
System.out.print("Introduza um número que determine o conjunto dos produtos mais vendidos:");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
System.out.println("\nOutput de Dados:");
for (Entry<String, DadosProduto> entry : tMap.entrySet()) {
if (entry.getValue() != null) {
sortedMapCXP = sortByValueCXP(tMap);
}
}
for(Map.Entry<String, DadosProduto> entry: sortedMapCXP.entrySet()){
cnt++;
//System.out.println(cnt++);
if(cnt != input){
System.out.println("Produto:" + entry.getKey() + ", Quantidade:" + entry.getValue().getNumeroCompras()+ ", Número de clientes distintos:" + entry.getValue().getClientesDistintos().size());
}
else{
return;
}
}
}
// Ordena por valor descendente, o conteúdo do HashMap
public static Map<String, DadosProduto> sortByValueCXP(Map<String, DadosProduto> unsortMap) {
List<Map.Entry<String, DadosProduto>> list = new LinkedList<Map.Entry<String, DadosProduto>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosProduto>>() {
public int compare(Map.Entry<String, DadosProduto> o1, Map.Entry<String, DadosProduto> o2) {
return o2.getValue().getNumeroCompras().compareTo(o1.getValue().getNumeroCompras());
}
});
Map<String, DadosProduto> sortedMap = new LinkedHashMap<String, DadosProduto>();
for (Map.Entry<String, DadosProduto> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
//Query 9 - Consulta Interactiva -------------------------------------------------------------------------------------------------------------------------------------------
public void clientesDiferentesProdutos() {
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(this.getCatalogoClientes().getGavetaClientes());
int cnt=-1;
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
System.out.print("Introduza um número que determine o conjunto dos clientes mais que mais compraram:");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
System.out.println("\nOutput de Dados:");
for(Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue() != null){
sortedMap = sortByValueCDP(tMap);
}
}
for(Map.Entry<String, DadosCliente> entry: sortedMap.entrySet()){
cnt++;
if(cnt != input){
System.out.println("O cliente: "+entry.getKey()+", comprou " +entry.getValue().getProdutosDistintos().size()+" produtos distintos.");
}
else{
return;
}
}
}
public static Map<String, DadosCliente> sortByValueCDP(Map<String, DadosCliente> unsortMap) {
Set<Entry<String, DadosCliente>> set = unsortMap.entrySet();
List<Entry<String, DadosCliente>> listOfEntry = new ArrayList<Entry<String, DadosCliente>>(set);
Collections.sort(listOfEntry, new Comparator<Map.Entry<String, DadosCliente>>() {
public int compare(Map.Entry<String, DadosCliente> o1, Map.Entry<String, DadosCliente> o2) {
if(o1.getValue().getClientesDistintos().size()< o2.getValue().getClientesDistintos().size())
return 1;
if(o1.getValue().getClientesDistintos().size() > o2.getValue().getClientesDistintos().size())
return -1;
if(o1.getValue().getClientesDistintos().size() == o2.getValue().getClientesDistintos().size())
return o1.getKey().compareTo(o2.getKey());
return 0;
}
});
return unsortMap;
}
//Query 10 - Consulta Interactiva -----------------------------------------------------------------------------------------------------------------------------------------
public void produtoClientesQueMaisCompraram() {
int cnt=-1;
System.out.print("Introduza o código de um produto:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.print("Introduza um número que determine o conjunto dos clientes que mais compraram e o valor que gastaram:");
int inputInt = sc.nextInt();
System.out.println("\nOutput de Dados:");
DadosProduto dadosProdutoInput = this.getCatalogoProdutos().getGavetaProdutos().get(input);
if (dadosProdutoInput == null)
return;
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(this.getCatalogoClientes().getGavetaClientes());
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
for(Map.Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue() !=null){
sortedMap = sortByValuePC(tMap);
}
}
System.out.println("O produto inserido: "+dadosProdutoInput.getIdProduto()+", "+ "foi vendido aos seguintes clientes: "+ dadosProdutoInput.getClientesDistintos()+", foi comprado: "+dadosProdutoInput.getNumeroCompras()+" vezes, e faturou: "+ dadosProdutoInput.getTotalFaturado()+"\n");
for(Map.Entry<String, DadosCliente> entry: sortedMap.entrySet()){
cnt++;
if(cnt!= inputInt){
System.out.println("Cliente: " + entry.getKey() + ", Número de compras: "+entry.getValue().getNumeroCompras()+ ", Valor Gasto: "+entry.getValue().getValorGasto());
}
else{
return;
}
}
}
// Ordena por valor descendente, o conte�do do HashMap
public static Map<String, DadosCliente> sortByValuePC(Map<String, DadosCliente> unsortMap) {
List<Map.Entry<String, DadosCliente>> list = new LinkedList<Map.Entry<String, DadosCliente>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosCliente>>() {
public int compare(Map.Entry<String, DadosCliente> o1, Map.Entry<String, DadosCliente> o2) {
return o2.getValue().getNumeroCompras().compareTo(o1.getValue().getNumeroCompras());
}
});
Map<String, DadosCliente> sortedMap = new LinkedHashMap<String, DadosCliente>();
for (Map.Entry<String, DadosCliente> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
| UTF-8 | Java | 19,499 | java | Hipermercado.java | Java | [] | null | [] | package GESTIHIPER_MAVEN.GESTIHIPER_MAVEN;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Hipermercado {
private List<Ccliente> listCcliente = new ArrayList<Ccliente>();
private List<Cproduto> listCproduto = new ArrayList<Cproduto>();
private List<Compra> listCompra = new ArrayList<Compra>();
private Ccliente catalogoClientes;
private Cproduto catalogoProdutos;
private Validador validador;
private HashSet<String> clientesDistintos = new HashSet<String>();
private Map<String, DadosCliente> sortedMap;
private Map<String, DadosProduto> sortedMapCXP;
public Hipermercado(Validador validador) {
super();
catalogoClientes = new Ccliente();
catalogoProdutos = new Cproduto();
this.validador = validador;
}
public void addCompra(Compra compra){
listCompra.add(compra);
catalogoProdutos.addCompraProduto(compra);
catalogoClientes.addCompraCliente(compra);
}
public List<Ccliente> getListCcliente() {
return listCcliente;
}
public void setListCcliente(List<Ccliente> listCcliente) {
this.listCcliente = listCcliente;
}
public Ccliente getCatalogoClientes() {
return catalogoClientes;
}
public void setCatalogoClientes(Ccliente catalogoClientes) {
this.catalogoClientes = catalogoClientes;
}
public Cproduto getCatalogoProdutos() {
return catalogoProdutos;
}
public void setCatalogoProdutos(Cproduto catalogoProdutos) {
this.catalogoProdutos = catalogoProdutos;
}
public List<Cproduto> getListCproduto() {
return listCproduto;
}
public void setListCproduto(List<Cproduto> listCproduto) {
this.listCproduto = listCproduto;
}
public List<Compra> getListCompra() {
return listCompra;
}
public void setListCompra(List<Compra> listCompra) {
this.listCompra = listCompra;
}
public void addCcliente(Ccliente ccliente) {
listCcliente.add(ccliente);
}
public void addCproduto(Cproduto cproduto) {
listCproduto.add(cproduto);
}
@Override
public String toString() {
return "Hipermercado [listCcliente=" + listCcliente + ", listCproduto=" + listCproduto + ", listCompra="
+ listCompra+"]";
}
//Query 1 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------
public void totalComprasMes() {
int quantidadeTotal = 0;
for (int j = 1; j < 13; j++) {
for (int i = 0; i < this.getListCompra().size(); i++) {
if (j == this.getListCompra().get(i).getMes()) {
quantidadeTotal = quantidadeTotal + this.getListCompra().get(i).getQuantidade();
}
}
System.out.println("O mês:" + j + " foram feitas:" + quantidadeTotal+" compras.");
quantidadeTotal = 0;
}
}
//Query 2 - Consulta Estatística -------------------------------------------------------------------------------------------------------------------------------------
public void totalGlobal() {
double totalMes = 0;
double totalGlobal = 0;
for (int j = 1; j < 13; j++) {
for (int i = 0; i < this.getListCompra().size(); i++) {
if (j == this.getListCompra().get(i).getMes()) {
totalMes = totalMes
+ this.getListCompra().get(i).getPreco() * this.getListCompra().get(i).getQuantidade();
}
}
System.out.println("O mês:" + j + " totalidade do mes:" + totalMes + " euros");
double temp = totalMes;
totalMes = 0;
totalGlobal += temp;
}
System.out.println("\nA faturaçãoo Global: " + totalGlobal + " euros");
}
//Query 3 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------------------------------------------------
public void clientesDistintos() {
for (int j = 1; j < 13; j++) {
for (Compra i : this.getListCompra()) {
if (j == i.getMes()) {
this.clientesDistintos.add(i.getIdCliente());
}
}
System.out.println("\nClientes do mes: " + j);
for (String temp : clientesDistintos) {
System.out.println(temp);
}
clientesDistintos.clear();
}
}
//Query 4 - Consulta Estatística ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void comprasInvalidas() {
System.out.println("Existem " + validador.getComprasInvalidas().size()
+ " compras inv�lidas\nConsulte o ficheiro ComprasInvalidas.txt");
try {
BufferedWriter objWriter = new BufferedWriter(new FileWriter("ComprasInvalidas.txt"));
String newLine = System.getProperty("line.separator");
for (int i = 0; i < validador.getComprasInvalidas().size(); i++) {
objWriter.write(validador.getComprasInvalidas().get(i) + " " + newLine);
}
objWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Query 1 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void produtosNaoComprados() {
int cnt=0;
Map<String, DadosProduto> tMap = new TreeMap<String, DadosProduto>(getCatalogoProdutos().getGavetaProdutos());
System.out.println("Códigos de produtos nunca comprado:");
for(Entry<String, DadosProduto> entry: tMap.entrySet()){
if(entry.getValue()== null){
System.out.println("ID do Produto: " + entry.getKey());
cnt++;
}
}
System.out.println("\nO número total de produtos nunca comprados: "+cnt);
}
// Query 2 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void clientesNuncaCompraram(){
int cnt=0;
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(getCatalogoClientes().getGavetaClientes());
System.out.println("Códigos de clientes que nunca compraram:");
for(Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue()== null){
System.out.println("ID do Cliente: " + entry.getKey());
cnt++;
}
}
System.out.println("\nO número de clientes que nunca compraram: "+cnt);
}
// Query 3 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void numeroComprasEclientesPorMes() {
System.out.print("Insira um mês de 1 a 12: ");
Scanner sc = new Scanner(System.in);
int mes = sc.nextInt();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getMensal().containsKey(mes)) {
System.out.println("Produto comprado: " + entry.getKey() + ", Quantidade: "
+ entry.getValue().getMensal().get(mes).getTotalCompras() + ", Clientes Distintos: "
+ entry.getValue().getMensal().get(mes).getClientesDistintos());
}
}
}
}
// Query 4 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoClienteParaMes() {
System.out.print("Introduza o código de um cliente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("\nO cliente "+input+":");
for (Entry<String, DadosCliente> entry : getCatalogoClientes().getGavetaClientes().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdCliente().equals(input)) {
for (Entry<Integer, DadosMesCliente> entry2 : entry.getValue().getMensalCliente().entrySet()) {
System.out.println("No Mês:"+entry2.getKey() + ", fez um total número de compras:" + entry2.getValue().getTotalCompras() + ", adquiriu os seguintes produtos:"
+ entry2.getValue().getProdutosDistintos() + " e gastou na totalidade:" + entry2.getValue().getFaturacao()+" euros");
}
}
}
}
}
// Query 5 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoProdutoMesaMes() {
System.out.print("Introduza um código de um produto existente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdProduto().equals(input)) {
for (Entry<Integer, DadosMesProduto> entry2 : entry.getValue().getMensal().entrySet()) {
System.out.println("No Mês: " + entry2.getKey() + ", Total Número de Compras: "
+ entry2.getValue().getTotalCompras() + ", Clientes Distintos: "
+ entry2.getValue().getClientesDistintos() + ", Total Faturado: "
+ entry2.getValue().getFaturacao()+" euros.");
}
}
}
}
}
//Query 6 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void codigoProdutoNP() {
System.out.print("Introduza um código de um produto existente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
for (Entry<String, DadosProduto> entry : getCatalogoProdutos().getGavetaProdutos().entrySet()) {
if (entry.getValue() != null) {
if (entry.getValue().getIdProduto().equals(input)) {
for (Entry<Integer, DadosMesProduto> entry2 : entry.getValue().getMensal().entrySet()) {
System.out.println("No mês: " + entry2.getKey() + ", Total Número de Compras em modo Promoção: "
+ entry2.getValue().getComprasModoP() + ", Total Número de Compras em Modo Normal: "
+ entry2.getValue().getComprasModoN() + ", Total Faturado: "
+ entry2.getValue().getFaturacao());
}
}
}
}
}
// Query 7 - Consulta Interactiva ------------------------------------------------------------------------------------------------------------------------------------------
public void clienteListaProdutos() {
System.out.print("Introduza um código de um cliente:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.println("\nO cliente " + input + " comprou os seguintes produtos:");
DadosCliente dadosClienteInput = this.getCatalogoClientes().getGavetaClientes().get(input);
if (dadosClienteInput == null)
return;
Map<String, DadosClienteProduto> tMap = new TreeMap<String, DadosClienteProduto>(dadosClienteInput.getQuantidadeProdutoPorCliente());
if (tMap == null)
return;
Map<String, DadosClienteProduto> sortedMap = sortByValue(tMap);
printMapPQ(sortedMap);
}
public static <K,V> void printMapPQ(Map<K,V> map){
for(Map.Entry<K, V> entry: map.entrySet()){
System.out.println("Produto comprado: " + entry.getKey() + " "+entry.getValue());
}
}
// Ordena por valor descendente, o conte�do do HashMap
public static Map<String, DadosClienteProduto> sortByValue(Map<String, DadosClienteProduto> unsortMap) {
List<Map.Entry<String, DadosClienteProduto>> list = new LinkedList<Map.Entry<String, DadosClienteProduto>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosClienteProduto>>() {
public int compare(Map.Entry<String, DadosClienteProduto> o1, Map.Entry<String, DadosClienteProduto> o2) {
return o2.getValue().getQuantidade().compareTo(o1.getValue().getQuantidade());
}
});
Map<String, DadosClienteProduto> sortedMap = new LinkedHashMap<String, DadosClienteProduto>();
for (Map.Entry<String, DadosClienteProduto> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
// Query 8 - Consulta Interactiva ---------------------------------------------------------------------------------------------------------------------------------------
public void conjuntoXprodutos() {
Map<String, DadosProduto> tMap = new TreeMap<String, DadosProduto>(this.getCatalogoProdutos().getGavetaProdutos());
int cnt = -1;
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
System.out.print("Introduza um número que determine o conjunto dos produtos mais vendidos:");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
System.out.println("\nOutput de Dados:");
for (Entry<String, DadosProduto> entry : tMap.entrySet()) {
if (entry.getValue() != null) {
sortedMapCXP = sortByValueCXP(tMap);
}
}
for(Map.Entry<String, DadosProduto> entry: sortedMapCXP.entrySet()){
cnt++;
//System.out.println(cnt++);
if(cnt != input){
System.out.println("Produto:" + entry.getKey() + ", Quantidade:" + entry.getValue().getNumeroCompras()+ ", Número de clientes distintos:" + entry.getValue().getClientesDistintos().size());
}
else{
return;
}
}
}
// Ordena por valor descendente, o conteúdo do HashMap
public static Map<String, DadosProduto> sortByValueCXP(Map<String, DadosProduto> unsortMap) {
List<Map.Entry<String, DadosProduto>> list = new LinkedList<Map.Entry<String, DadosProduto>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosProduto>>() {
public int compare(Map.Entry<String, DadosProduto> o1, Map.Entry<String, DadosProduto> o2) {
return o2.getValue().getNumeroCompras().compareTo(o1.getValue().getNumeroCompras());
}
});
Map<String, DadosProduto> sortedMap = new LinkedHashMap<String, DadosProduto>();
for (Map.Entry<String, DadosProduto> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
//Query 9 - Consulta Interactiva -------------------------------------------------------------------------------------------------------------------------------------------
public void clientesDiferentesProdutos() {
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(this.getCatalogoClientes().getGavetaClientes());
int cnt=-1;
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
System.out.print("Introduza um número que determine o conjunto dos clientes mais que mais compraram:");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
System.out.println("\nOutput de Dados:");
for(Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue() != null){
sortedMap = sortByValueCDP(tMap);
}
}
for(Map.Entry<String, DadosCliente> entry: sortedMap.entrySet()){
cnt++;
if(cnt != input){
System.out.println("O cliente: "+entry.getKey()+", comprou " +entry.getValue().getProdutosDistintos().size()+" produtos distintos.");
}
else{
return;
}
}
}
public static Map<String, DadosCliente> sortByValueCDP(Map<String, DadosCliente> unsortMap) {
Set<Entry<String, DadosCliente>> set = unsortMap.entrySet();
List<Entry<String, DadosCliente>> listOfEntry = new ArrayList<Entry<String, DadosCliente>>(set);
Collections.sort(listOfEntry, new Comparator<Map.Entry<String, DadosCliente>>() {
public int compare(Map.Entry<String, DadosCliente> o1, Map.Entry<String, DadosCliente> o2) {
if(o1.getValue().getClientesDistintos().size()< o2.getValue().getClientesDistintos().size())
return 1;
if(o1.getValue().getClientesDistintos().size() > o2.getValue().getClientesDistintos().size())
return -1;
if(o1.getValue().getClientesDistintos().size() == o2.getValue().getClientesDistintos().size())
return o1.getKey().compareTo(o2.getKey());
return 0;
}
});
return unsortMap;
}
//Query 10 - Consulta Interactiva -----------------------------------------------------------------------------------------------------------------------------------------
public void produtoClientesQueMaisCompraram() {
int cnt=-1;
System.out.print("Introduza o código de um produto:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
System.out.print("Introduza um número que determine o conjunto dos clientes que mais compraram e o valor que gastaram:");
int inputInt = sc.nextInt();
System.out.println("\nOutput de Dados:");
DadosProduto dadosProdutoInput = this.getCatalogoProdutos().getGavetaProdutos().get(input);
if (dadosProdutoInput == null)
return;
Map<String, DadosCliente> tMap = new TreeMap<String, DadosCliente>(this.getCatalogoClientes().getGavetaClientes());
for (Iterator<?> it = tMap.values().iterator(); it.hasNext();) {
if (it.next() == null) {
it.remove();
}
}
for(Map.Entry<String, DadosCliente> entry: tMap.entrySet()){
if(entry.getValue() !=null){
sortedMap = sortByValuePC(tMap);
}
}
System.out.println("O produto inserido: "+dadosProdutoInput.getIdProduto()+", "+ "foi vendido aos seguintes clientes: "+ dadosProdutoInput.getClientesDistintos()+", foi comprado: "+dadosProdutoInput.getNumeroCompras()+" vezes, e faturou: "+ dadosProdutoInput.getTotalFaturado()+"\n");
for(Map.Entry<String, DadosCliente> entry: sortedMap.entrySet()){
cnt++;
if(cnt!= inputInt){
System.out.println("Cliente: " + entry.getKey() + ", Número de compras: "+entry.getValue().getNumeroCompras()+ ", Valor Gasto: "+entry.getValue().getValorGasto());
}
else{
return;
}
}
}
// Ordena por valor descendente, o conte�do do HashMap
public static Map<String, DadosCliente> sortByValuePC(Map<String, DadosCliente> unsortMap) {
List<Map.Entry<String, DadosCliente>> list = new LinkedList<Map.Entry<String, DadosCliente>>(
unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, DadosCliente>>() {
public int compare(Map.Entry<String, DadosCliente> o1, Map.Entry<String, DadosCliente> o2) {
return o2.getValue().getNumeroCompras().compareTo(o1.getValue().getNumeroCompras());
}
});
Map<String, DadosCliente> sortedMap = new LinkedHashMap<String, DadosCliente>();
for (Map.Entry<String, DadosCliente> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
| 19,499 | 0.584789 | 0.580678 | 515 | 36.786407 | 45.340576 | 287 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.704854 | false | false | 4 |
fac1f0e8157c764db14cb9a40ff4dfbf2c8a7990 | 10,050,223,505,612 | ed062a73d312b1c3c3498ae4574df0dc20ca1599 | /src/main/java/com/example/demo/util/UNGZ.java | a30e7b7915ab78911198e74a2d54643ef8fd7f9e | [] | no_license | eratong/LinuxFileTime | https://github.com/eratong/LinuxFileTime | 35a79fefbaaf4f917a9d282f58f01a2302e4c8aa | c33ac84dad2bb7e3966f837a716979a0f29d404f | refs/heads/master | 2021-08-03T18:22:51.633000 | 2020-01-20T01:18:47 | 2020-01-20T01:18:47 | 234,880,162 | 0 | 0 | null | false | 2021-08-02T17:20:23 | 2020-01-19T10:19:35 | 2020-01-20T01:19:44 | 2021-08-02T17:20:20 | 66 | 0 | 0 | 2 | Java | false | false | package com.example.demo.util;
/**
* tar.gz文件的byte[]数据和文件名
*/
public class UNGZ {
public byte[] data;
// tar文件存放的第二个文件的 数据 .text结尾
public byte[] textData;
public String textFilename;
public String filename;
}
| UTF-8 | Java | 268 | java | UNGZ.java | Java | [] | null | [] | package com.example.demo.util;
/**
* tar.gz文件的byte[]数据和文件名
*/
public class UNGZ {
public byte[] data;
// tar文件存放的第二个文件的 数据 .text结尾
public byte[] textData;
public String textFilename;
public String filename;
}
| 268 | 0.709091 | 0.709091 | 14 | 14.714286 | 12.132769 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 4 |
2f051216e9bb183945a8f058ea8c633ea0cfbf3c | 16,690,242,950,911 | d4c29c18455c03ec90c575677a922630df791c90 | /src/main/java/com/lf/gw/domain/package-info.java | 42094fe659281ad647f099af00a0848e22b5f8c0 | [] | no_license | zhao-tuo/lfgw | https://github.com/zhao-tuo/lfgw | f96e92f1ba655fc90fc699165b87d4b71208803c | 894276b3bdc3c0118f861a5edb09ff26e423703d | refs/heads/master | 2021-05-12T05:18:38.333000 | 2018-01-11T06:36:11 | 2018-01-11T06:36:11 | 117,188,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* JPA domain objects.
*/
package com.lf.gw.domain;
| UTF-8 | Java | 57 | java | package-info.java | Java | [] | null | [] | /**
* JPA domain objects.
*/
package com.lf.gw.domain;
| 57 | 0.631579 | 0.631579 | 4 | 13.25 | 10.304732 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
213fc50eeccbe04824a0f0fcf49697f98eddc477 | 32,160,715,146,205 | 8e24a581d39fe918d1f7437850a7ecfe9c920425 | /jpa/odata-jpa-metadata/src/main/java/com/sap/olingo/jpa/metadata/api/JPARequestParameterMap.java | 49125a1b58d1bb0e61ef4d1caecef547e75effe4 | [
"Apache-2.0"
] | permissive | SAP/olingo-jpa-processor-v4 | https://github.com/SAP/olingo-jpa-processor-v4 | 4f840bdcb66ccf3a85e0155d40a901af74b1c291 | 6da94c5f6a18900adba1577878e0310278cd8cbb | refs/heads/main | 2023-07-19T08:25:24.856000 | 2023-04-11T20:32:49 | 2023-04-11T20:32:49 | 77,145,569 | 122 | 63 | Apache-2.0 | false | 2023-09-04T20:42:49 | 2016-12-22T13:10:48 | 2023-08-10T06:57:05 | 2023-09-04T20:42:48 | 14,766 | 107 | 66 | 64 | Java | false | false | package com.sap.olingo.jpa.metadata.api;
import java.util.Map;
/**
*
* @author Oliver Grande
* @since 1.0.3
* 20.05.2021
*/
public interface JPARequestParameterMap extends Map<String, Object> {
}
| UTF-8 | Java | 217 | java | JPARequestParameterMap.java | Java | [
{
"context": "i;\r\n\r\nimport java.util.Map;\r\n\r\n/**\r\n *\r\n * @author Oliver Grande\r\n * @since 1.0.3\r\n * 20.05.2021\r\n */\r\npublic inte",
"end": 102,
"score": 0.9996225833892822,
"start": 89,
"tag": "NAME",
"value": "Oliver Grande"
}
] | null | [] | package com.sap.olingo.jpa.metadata.api;
import java.util.Map;
/**
*
* @author <NAME>
* @since 1.0.3
* 20.05.2021
*/
public interface JPARequestParameterMap extends Map<String, Object> {
}
| 210 | 0.658986 | 0.608295 | 13 | 14.692307 | 19.589577 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 4 |
5348cf917aa9811d8fa7d0a94105e877f8ea4561 | 13,108,240,188,010 | 279652fad6675ad2864ad5f4061a5e8616dd881d | /app/src/main/java/com/example/LegendsOfAndor/FalconTrade.java | 6aa5b517012a109197318407b42b7d18062ec2bb | [] | no_license | tshih17110/LegendsOfAndor | https://github.com/tshih17110/LegendsOfAndor | a85a45bb86296985f8b540c4f13d6dfcf49cda67 | fcb281e0039e3f2b4f93d865011904933d1a9091 | refs/heads/master | 2022-05-26T05:58:43.361000 | 2020-04-30T22:08:35 | 2020-04-30T22:08:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.LegendsOfAndor;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.util.ArrayList;
enum ProcessFalconTradeResponses{
TRADE_PROCESSED,TRADE_FAILED, CANNOT_ACCEPT_ITEMS
}
public class FalconTrade extends AppCompatActivity {
Spinner p1_gold;
Spinner p1_runestone_blue;
Spinner p1_wineskin;
Spinner p1_runestone_green;
Spinner p1_telescope;
Spinner p1_helm;
Spinner p1_medicinal_herb;
Spinner p1_witch_brew;
Spinner p1_runestone_yellow;
ImageButton p1_pic_gold;
ImageButton p1_pic_runestone_blue;
ImageButton p1_pic_wineskin;
ImageButton p1_pic_runestone_green;
ImageButton p1_pic_telescope;
ImageButton p1_pic_helm;
ImageButton p1_pic_medicinal_herb;
ImageButton p1_pic_witch_brew;
ImageButton p1_pic_runestone_yellow;
Spinner p2_gold;
Spinner p2_runestone_blue;
Spinner p2_wineskin;
Spinner p2_runestone_green;
Spinner p2_telescope;
Spinner p2_helm;
Spinner p2_medicinal_herb;
Spinner p2_witch_brew;
Spinner p2_runestone_yellow;
ImageButton p2_pic_gold;
ImageButton p2_pic_runestone_blue;
ImageButton p2_pic_wineskin;
ImageButton p2_pic_runestone_green;
ImageButton p2_pic_telescope;
ImageButton p2_pic_helm;
ImageButton p2_pic_medicinal_herb;
ImageButton p2_pic_witch_brew;
ImageButton p2_pic_runestone_yellow;
MyPlayer myPlayer;
TextView p1_heroclass;
TextView p2_heroclass;
HeroClass p2_hero_class;
HeroClass p1_hero_class;
private Thread t;
private boolean threadTerminated = false;
FalconTradeObject clientTrade;
Boolean isPlayer1;
Button p1_confirm;
Button p2_confirm;
TextView p1_hasConfirmed;
TextView p2_hasConfirmed;
Button trade;
@Override
public void onBackPressed(){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.falcon_trade);
p1_gold = findViewById(R.id.p1_gold);
p1_runestone_yellow = findViewById(R.id.p1_runestone_yellow);
p1_runestone_blue = findViewById(R.id.p1_runestone_blue);
p1_runestone_green = findViewById(R.id.p1_runestone_green);
p1_helm = findViewById(R.id.p1_helm);
p1_medicinal_herb = findViewById(R.id.p1_medicinal_herb);
p1_wineskin = findViewById(R.id.p1_wineskin);
p1_telescope = findViewById(R.id.p1_telescope);
p1_witch_brew = findViewById(R.id.p1_witch_brew);
p1_gold.setVisibility(View.INVISIBLE);
p1_runestone_yellow.setVisibility(View.INVISIBLE);
p1_runestone_blue.setVisibility(View.INVISIBLE);
p1_runestone_green.setVisibility(View.INVISIBLE);
p1_helm.setVisibility(View.INVISIBLE);
p1_medicinal_herb.setVisibility(View.INVISIBLE);
p1_wineskin.setVisibility(View.INVISIBLE);
p1_telescope.setVisibility(View.INVISIBLE);
p1_witch_brew.setVisibility(View.INVISIBLE);
p1_pic_gold = findViewById(R.id.p1_gold_pic);
p1_pic_runestone_yellow = findViewById(R.id.p1_runestone_yellow_pic);
p1_pic_runestone_blue = findViewById(R.id.p1_runestone_blue_pic);
p1_pic_runestone_green = findViewById(R.id.p1_runestone_green_pic);
p1_pic_helm = findViewById(R.id.p1_helm_pic);
p1_pic_medicinal_herb = findViewById(R.id.p1_medicinal_herb_pic);
p1_pic_wineskin = findViewById(R.id.p1_wineskin_pic);
p1_pic_telescope = findViewById(R.id.p1_telescope_pic);
p1_pic_witch_brew = findViewById(R.id.p1_witch_brew_pic);
p1_pic_gold.setVisibility(View.INVISIBLE);
p1_pic_runestone_yellow.setVisibility(View.INVISIBLE);
p1_pic_runestone_blue.setVisibility(View.INVISIBLE);
p1_pic_runestone_green.setVisibility(View.INVISIBLE);
p1_pic_helm.setVisibility(View.INVISIBLE);
p1_pic_medicinal_herb.setVisibility(View.INVISIBLE);
p1_pic_wineskin.setVisibility(View.INVISIBLE);
p1_pic_telescope.setVisibility(View.INVISIBLE);
p1_pic_witch_brew.setVisibility(View.INVISIBLE);
p2_gold = findViewById(R.id.p2_gold);
p2_runestone_yellow = findViewById(R.id.p2_runestone_yellow);
p2_runestone_blue = findViewById(R.id.p2_runestone_blue);
p2_runestone_green = findViewById(R.id.p2_runestone_green);
p2_helm = findViewById(R.id.p2_helm);
p2_medicinal_herb = findViewById(R.id.p2_medicinal_herb);
p2_wineskin = findViewById(R.id.p2_wineskin);
p2_telescope = findViewById(R.id.p2_telescope);
p2_witch_brew = findViewById(R.id.p2_witch_brew);
p2_gold.setVisibility(View.INVISIBLE);
p2_runestone_yellow.setVisibility(View.INVISIBLE);
p2_runestone_blue.setVisibility(View.INVISIBLE);
p2_runestone_green.setVisibility(View.INVISIBLE);
p2_helm.setVisibility(View.INVISIBLE);
p2_medicinal_herb.setVisibility(View.INVISIBLE);
p2_wineskin.setVisibility(View.INVISIBLE);
p2_telescope.setVisibility(View.INVISIBLE);
p2_witch_brew.setVisibility(View.INVISIBLE);
p2_pic_gold = findViewById(R.id.p2_gold_pic);
p2_pic_runestone_yellow = findViewById(R.id.p2_runestone_yellow_pic);
p2_pic_runestone_blue = findViewById(R.id.p2_runestone_blue_pic);
p2_pic_runestone_green = findViewById(R.id.p2_runestone_green_pic);
p2_pic_helm = findViewById(R.id.p2_helm_pic);
p2_pic_medicinal_herb = findViewById(R.id.p2_medicinal_herb_pic);
p2_pic_wineskin = findViewById(R.id.p2_wineskin_pic);
p2_pic_telescope = findViewById(R.id.p2_telescope_pic);
p2_pic_witch_brew = findViewById(R.id.p2_witch_brew_pic);
p2_pic_gold.setVisibility(View.INVISIBLE);
p2_pic_runestone_yellow.setVisibility(View.INVISIBLE);
p2_pic_runestone_blue.setVisibility(View.INVISIBLE);
p2_pic_runestone_green.setVisibility(View.INVISIBLE);
p2_pic_helm.setVisibility(View.INVISIBLE);
p2_pic_medicinal_herb.setVisibility(View.INVISIBLE);
p2_pic_wineskin.setVisibility(View.INVISIBLE);
p2_pic_telescope.setVisibility(View.INVISIBLE);
p2_pic_witch_brew.setVisibility(View.INVISIBLE);
myPlayer = MyPlayer.getInstance();
p1_heroclass = findViewById(R.id.p1_heroclass);
p2_heroclass = findViewById(R.id.p2_heroclass);
p2_hero_class = null;
p1_hero_class = null;
p1_confirm = findViewById(R.id.p1_confirm);
p2_confirm = findViewById(R.id.p2_confirm);
p1_hasConfirmed = findViewById(R.id.p1_has_confirmed);
p2_hasConfirmed = findViewById(R.id.p2_has_confirmed);
trade = findViewById(R.id.trade_items_falcon);
try{
AsyncTask<String, Void, Game> asyncTaskGame;
Game gameToSet;
GetGame getGame = new GetGame();
asyncTaskGame = getGame.execute();
gameToSet = asyncTaskGame.get();
System.out.println(gameToSet);
myPlayer.setGame(gameToSet);
for(int i = 0; i < gameToSet.getCurrentNumPlayers(); i++){
if(gameToSet.getPlayers()[i].getUsername().equals(myPlayer.getPlayer().getUsername())){
myPlayer.setPlayer(gameToSet.getPlayers()[i]);
}
}
}catch (Exception e){
e.printStackTrace();
}
String p1_hero_string = getIntent().getExtras().getString("p1");
if(p1_hero_string != null){
p1_hero_class = getHeroClass(p1_hero_string);
p1_heroclass.setText(p1_hero_string);
}
String p2_hero_string = getIntent().getExtras().getString("p2");
if(p2_hero_string != null){
p2_hero_class = getHeroClass(p2_hero_string);
p2_heroclass.setText(p2_hero_string);
}
if(p1_hero_class != null){
if(p1_hero_class == myPlayer.getPlayer().getHero().getHeroClass()){
isPlayer1 = true;
}else{
isPlayer1 = false;
}
Hero p1_hero = null;
for(int i = 0; i < myPlayer.getGame().getCurrentNumPlayers(); i++){
if(myPlayer.getGame().getPlayers()[i].getHero().getHeroClass() == p1_hero_class){
p1_hero = myPlayer.getGame().getPlayers()[i].getHero();
clientTrade = myPlayer.getGame().getPlayers()[i].getHero().getCurrentFalconTrade();
break;
}
}
if(p1_hero != null){
int p1_num_helms = getNumItems(p1_hero, ItemType.HELM);
int p1_num_telescopes = getNumItems(p1_hero, ItemType.TELESCOPE);
int p1_num_wineskins = getNumItems(p1_hero, ItemType.WINESKIN);
int p1_num_medicinal_herbs = getNumItems(p1_hero, ItemType.MEDICINAL_HERB);
int p1_num_witch_brew = getNumItems(p1_hero, ItemType.WITCH_BREW);
int p1_num_gold = p1_hero.getGold();
int p1_num_runestone_yellow = 0;
int p1_num_runestone_blue = 0;
int p1_num_runestone_green = 0;
for(RuneStone runeStone : p1_hero.getRuneStones()){
if(runeStone.getColour() == Colour.YELLOW){
p1_num_runestone_yellow++;
}
if(runeStone.getColour() == Colour.BLUE){
p1_num_runestone_blue++;
}
if(runeStone.getColour() == Colour.GREEN){
p1_num_runestone_green++;
}
}
if(p1_num_helms > 0){
p1_pic_helm.setVisibility(View.VISIBLE);
p1_helm.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_helms; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_helm.setAdapter(adapterDrop);
}
if(p1_num_telescopes > 0){
p1_pic_telescope.setVisibility(View.VISIBLE);
p1_telescope.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_telescopes; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_telescope.setAdapter(adapterDrop);
}
if(p1_num_wineskins > 0){
p1_pic_wineskin.setVisibility(View.VISIBLE);
p1_wineskin.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_wineskins; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_wineskin.setAdapter(adapterDrop);
}
if(p1_num_medicinal_herbs > 0){
p1_pic_medicinal_herb.setVisibility(View.VISIBLE);
p1_medicinal_herb.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_medicinal_herbs; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_medicinal_herb.setAdapter(adapterDrop);
}
if(p1_num_witch_brew > 0){
p1_pic_witch_brew.setVisibility(View.VISIBLE);
p1_witch_brew.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_witch_brew; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_witch_brew.setAdapter(adapterDrop);
}
if(p1_num_gold > 0){
p1_pic_gold.setVisibility(View.VISIBLE);
p1_gold.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_gold; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_gold.setAdapter(adapterDrop);
}
if(p1_num_runestone_blue > 0){
p1_pic_runestone_blue.setVisibility(View.VISIBLE);
p1_runestone_blue.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_blue; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_blue.setAdapter(adapterDrop);
}
if(p1_num_runestone_yellow > 0){
p1_pic_runestone_yellow.setVisibility(View.VISIBLE);
p1_runestone_yellow.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_yellow; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_yellow.setAdapter(adapterDrop);
}
if(p1_num_runestone_green > 0){
p1_pic_runestone_green.setVisibility(View.VISIBLE);
p1_runestone_green.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_green; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_green.setAdapter(adapterDrop);
}
}
}
if(p2_hero_class != null){
Hero p2_hero = null;
for(int i = 0; i < myPlayer.getGame().getCurrentNumPlayers(); i++){
if(myPlayer.getGame().getPlayers()[i].getHero().getHeroClass() == p2_hero_class){
p2_hero = myPlayer.getGame().getPlayers()[i].getHero();
break;
}
}
if(p2_hero != null){
int p2_num_helms = getNumItems(p2_hero, ItemType.HELM);
int p2_num_telescopes = getNumItems(p2_hero, ItemType.TELESCOPE);
int p2_num_wineskins = getNumItems(p2_hero, ItemType.WINESKIN);
int p2_num_medicinal_herbs = getNumItems(p2_hero, ItemType.MEDICINAL_HERB);
int p2_num_witch_brew = getNumItems(p2_hero, ItemType.WITCH_BREW);
int p2_num_gold = p2_hero.getGold();
int p2_num_runestone_yellow = 0;
int p2_num_runestone_blue = 0;
int p2_num_runestone_green = 0;
for(RuneStone runeStone : p2_hero.getRuneStones()){
if(runeStone.getColour() == Colour.YELLOW){
p2_num_runestone_yellow++;
}
if(runeStone.getColour() == Colour.BLUE){
p2_num_runestone_blue++;
}
if(runeStone.getColour() == Colour.GREEN){
p2_num_runestone_green++;
}
}
if(p2_num_helms > 0){
p2_pic_helm.setVisibility(View.VISIBLE);
p2_helm.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_helms; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_helm.setAdapter(adapterDrop);
}
if(p2_num_telescopes > 0){
p2_pic_telescope.setVisibility(View.VISIBLE);
p2_telescope.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_telescopes; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_telescope.setAdapter(adapterDrop);
}
if(p2_num_wineskins > 0){
p2_pic_wineskin.setVisibility(View.VISIBLE);
p2_wineskin.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_wineskins; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_wineskin.setAdapter(adapterDrop);
}
if(p2_num_medicinal_herbs > 0){
p2_pic_medicinal_herb.setVisibility(View.VISIBLE);
p2_medicinal_herb.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_medicinal_herbs; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_medicinal_herb.setAdapter(adapterDrop);
}
if(p2_num_witch_brew > 0){
p2_pic_witch_brew.setVisibility(View.VISIBLE);
p2_witch_brew.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_witch_brew; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_witch_brew.setAdapter(adapterDrop);
}
if(p2_num_gold > 0){
p2_pic_gold.setVisibility(View.VISIBLE);
p2_gold.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_gold; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_gold.setAdapter(adapterDrop);
}
if(p2_num_runestone_blue > 0){
p2_pic_runestone_blue.setVisibility(View.VISIBLE);
p2_runestone_blue.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_blue; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_blue.setAdapter(adapterDrop);
}
if(p2_num_runestone_yellow > 0){
p2_pic_runestone_yellow.setVisibility(View.VISIBLE);
p2_runestone_yellow.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_yellow; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_yellow.setAdapter(adapterDrop);
}
if(p2_num_runestone_green > 0){
p2_pic_runestone_green.setVisibility(View.VISIBLE);
p2_runestone_green.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_green; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_green.setAdapter(adapterDrop);
}
}
}
t = new Thread(new Runnable() {
@Override
public void run() {
myPlayer = MyPlayer.getInstance();
while(!threadTerminated){
try{
final HttpResponse<String> httpResponse = Unirest.get("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getPlayer().getUsername() + "/getGameUpdate")
.asString();
if(httpResponse.getCode() == 200){
final Game game = new Gson().fromJson(httpResponse.getBody(), Game.class);
MyPlayer.getInstance().setGame(game);
for(int i = 0; i < game.getCurrentNumPlayers(); i++){
if(game.getPlayers()[i].getUsername().equals(myPlayer.getPlayer().getUsername())){
myPlayer.setPlayer(game.getPlayers()[i]);
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < game.getCurrentNumPlayers(); i++){
if(game.getPlayers()[i].getHero().getHeroClass() == p1_hero_class){
FalconTradeObject currentTrade = game.getPlayers()[i].getHero().getCurrentFalconTrade();
if(currentTrade == null){
Toast.makeText(FalconTrade.this, "Falcon Trade Processed", Toast.LENGTH_LONG).show();
threadTerminated = true;
startActivity(new Intent(FalconTrade.this, UseArticle.class));
finish();
}else{
p1_gold.setSelection(getIndex(p1_gold, currentTrade.getP1_gold()));
p1_wineskin.setSelection(getIndex(p1_wineskin, currentTrade.getP1_wineskin()));
p1_runestone_blue.setSelection(getIndex(p1_runestone_blue, currentTrade.getP1_runestone_blue()));
p1_runestone_green.setSelection(getIndex(p1_runestone_green, currentTrade.getP1_runestone_green()));
p1_runestone_yellow.setSelection(getIndex(p1_runestone_yellow,currentTrade.getP1_runestone_yellow()));
p1_telescope.setSelection(getIndex(p1_telescope, currentTrade.getP1_telescope()));
p1_helm.setSelection(getIndex(p1_helm, currentTrade.getP1_helm()));
p1_medicinal_herb.setSelection(getIndex(p1_medicinal_herb, currentTrade.getP1_medicinal_herb()));
p1_witch_brew.setSelection(getIndex(p1_witch_brew,currentTrade.getP1_witch_brew()));
p2_gold.setSelection(getIndex(p2_gold, currentTrade.getP2_gold()));
p2_wineskin.setSelection(getIndex(p2_wineskin, currentTrade.getP2_wineskin()));
p2_runestone_blue.setSelection(getIndex(p2_runestone_blue, currentTrade.getP2_runestone_blue()));
p2_runestone_green.setSelection(getIndex(p2_runestone_green, currentTrade.getP2_runestone_green()));
p2_runestone_yellow.setSelection(getIndex(p2_runestone_yellow,currentTrade.getP2_runestone_yellow()));
p2_telescope.setSelection(getIndex(p2_telescope, currentTrade.getP2_telescope()));
p2_helm.setSelection(getIndex(p2_helm, currentTrade.getP2_helm()));
p2_medicinal_herb.setSelection(getIndex(p2_medicinal_herb, currentTrade.getP2_medicinal_herb()));
p2_witch_brew.setSelection(getIndex(p2_witch_brew,currentTrade.getP2_witch_brew()));
if(!currentTrade.isDontUpdate()){
if(currentTrade.isP1_hasConfirmed()){
p1_hasConfirmed.setBackgroundColor(Color.GREEN);
}else{
p1_hasConfirmed.setBackgroundColor(Color.RED);
}
}
if(currentTrade.isP2_hasConfirmed()){
p2_hasConfirmed.setBackgroundColor(Color.GREEN);
}else{
p2_hasConfirmed.setBackgroundColor(Color.RED);
}
currentTrade.setDontUpdate(false);
}
}
}
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
}
});
t.start();
if(!isPlayer1){
p1_gold.setEnabled(false);
p1_runestone_yellow.setEnabled(false);
p1_runestone_blue.setEnabled(false);
p1_runestone_green.setEnabled(false);
p1_helm.setEnabled(false);
p1_medicinal_herb.setEnabled(false);
p1_wineskin.setEnabled(false);
p1_telescope.setEnabled(false);
p1_witch_brew.setEnabled(false);
p2_gold.setEnabled(false);
p2_runestone_yellow.setEnabled(false);
p2_runestone_blue.setEnabled(false);
p2_runestone_green.setEnabled(false);
p2_helm.setEnabled(false);
p2_medicinal_herb.setEnabled(false);
p2_wineskin.setEnabled(false);
p2_telescope.setEnabled(false);
p2_witch_brew.setEnabled(false);
p1_hasConfirmed.setEnabled(false);
p1_confirm.setEnabled(false);
p1_confirm.setVisibility(View.INVISIBLE);
trade.setVisibility(View.INVISIBLE);
}else{
p2_hasConfirmed.setEnabled(false);
p2_confirm.setEnabled(false);
p2_confirm.setVisibility(View.INVISIBLE);
}
p1_gold.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_gold((Integer) p1_gold.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_wineskin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_wineskin((Integer) p1_wineskin.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_telescope.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_telescope((Integer) p1_telescope.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_helm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_helm((Integer) p1_helm.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_medicinal_herb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_medicinal_herb((Integer) p1_medicinal_herb.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_witch_brew.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_witch_brew((Integer) p1_witch_brew.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_blue.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_blue((Integer) p1_runestone_blue.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_yellow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_yellow((Integer) p1_runestone_yellow.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_green.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_green((Integer) p1_runestone_green.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_gold.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_gold((Integer) p2_gold.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_wineskin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_wineskin((Integer) p2_wineskin.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_telescope.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_telescope((Integer) p2_telescope.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_helm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_helm((Integer) p2_helm.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_medicinal_herb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_medicinal_herb((Integer) p2_medicinal_herb.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_witch_brew.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_witch_brew((Integer) p2_witch_brew.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_blue.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_blue((Integer) p2_runestone_blue.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_yellow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_yellow((Integer) p2_runestone_yellow.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_green.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_green((Integer) p2_runestone_green.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clientTrade.setP1_hasConfirmed(true);
sendUpdatedTradeObject(clientTrade);
}
});
p2_confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clientTrade.setP2_hasConfirmed(true);
clientTrade.setDontUpdate(true);
sendUpdatedTradeObject(clientTrade);
}
});
trade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(clientTrade.toString());
ColorDrawable p1_color = (ColorDrawable) p1_hasConfirmed.getBackground();
ColorDrawable p2_color = (ColorDrawable) p2_hasConfirmed.getBackground();
if(p1_color.getColor() == Color.GREEN && p2_color.getColor() == Color.GREEN){
AsyncTask<String,Void,ProcessFalconTradeResponses> asyncTask;
ProcessFalconTradeResponses processFalconTradeResponses = null;
ProcessFalconTrade processFalconTrade = new ProcessFalconTrade();
try{
asyncTask = processFalconTrade.execute(new Gson().toJson(clientTrade));
processFalconTradeResponses = asyncTask.get();
}catch(Exception e){
e.printStackTrace();
}
if (processFalconTradeResponses == ProcessFalconTradeResponses.CANNOT_ACCEPT_ITEMS) {
Toast.makeText(FalconTrade.this,"One or more of the heroes cannot accept the items requested" , Toast.LENGTH_LONG).show();
clientTrade.clearValues();
sendUpdatedTradeObject(clientTrade);
}else if (processFalconTradeResponses == ProcessFalconTradeResponses.TRADE_FAILED){
Toast.makeText(FalconTrade.this,"Falcon trade failed for unknown reasons, please try again" , Toast.LENGTH_LONG).show();
clientTrade.clearValues();
sendUpdatedTradeObject(clientTrade);
}else if(processFalconTradeResponses == ProcessFalconTradeResponses.TRADE_PROCESSED){
}
}else{
Toast.makeText(FalconTrade.this,"Not ready to trade. Please wait until both players confirm" , Toast.LENGTH_LONG).show();
}
}
});
}
private static class GetGame extends AsyncTask<String, Void, Game > {
@Override
protected Game doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.get("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getPlayer().getUsername() + "/getGameByUsername")
.asString();
String resultAsJsonString = response.getBody();
System.out.println("RESPONSE BODY " + response.getBody());
return new Gson().fromJson(resultAsJsonString, Game.class);
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
public static int getNumItems(Hero hero, ItemType type){
int count = 0;
for(Item item : hero.getItems()){
if(item.getItemType() == type){
count++;
}
}
return count;
}
public static HeroClass getHeroClass(String heroString){
if(heroString.equals("wizard")){
return HeroClass.WIZARD;
}else if(heroString.equals("warrior")){
return HeroClass.WARRIOR;
}else if (heroString.equals("archer")){
return HeroClass.ARCHER;
}else if(heroString.equals("dwarf")){
return HeroClass.DWARF;
}
return null;
}
private int getIndex(Spinner spinner, Integer num){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i) == num){
return i;
}
}
return -1;
}
private static class SendFalconTradeObject extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.post("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getGame().getGameName() + "/" + myPlayer.getPlayer().getUsername() + "/updateFalconTradeObject")
.header("Content-Type", "application/json")
.body(strings[0])
.asString();
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
private static class ProcessFalconTrade extends AsyncTask<String, Void, ProcessFalconTradeResponses> {
@Override
protected ProcessFalconTradeResponses doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.post("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getGame().getGameName() + "/processFalconTrade")
.header("Content-Type", "application/json")
.body(strings[0])
.asString();
String resultAsJsonString = response.getBody();
return new Gson().fromJson(resultAsJsonString, ProcessFalconTradeResponses.class);
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
private void sendUpdatedTradeObject(FalconTradeObject falconTradeObject){
AsyncTask<String,Void,Void> asyncTask;
SendFalconTradeObject sendFalconTradeObject = new SendFalconTradeObject();
asyncTask = sendFalconTradeObject.execute(new Gson().toJson(falconTradeObject));
}
}
| UTF-8 | Java | 53,504 | java | FalconTrade.java | Java | [] | null | [] | package com.example.LegendsOfAndor;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.util.ArrayList;
enum ProcessFalconTradeResponses{
TRADE_PROCESSED,TRADE_FAILED, CANNOT_ACCEPT_ITEMS
}
public class FalconTrade extends AppCompatActivity {
Spinner p1_gold;
Spinner p1_runestone_blue;
Spinner p1_wineskin;
Spinner p1_runestone_green;
Spinner p1_telescope;
Spinner p1_helm;
Spinner p1_medicinal_herb;
Spinner p1_witch_brew;
Spinner p1_runestone_yellow;
ImageButton p1_pic_gold;
ImageButton p1_pic_runestone_blue;
ImageButton p1_pic_wineskin;
ImageButton p1_pic_runestone_green;
ImageButton p1_pic_telescope;
ImageButton p1_pic_helm;
ImageButton p1_pic_medicinal_herb;
ImageButton p1_pic_witch_brew;
ImageButton p1_pic_runestone_yellow;
Spinner p2_gold;
Spinner p2_runestone_blue;
Spinner p2_wineskin;
Spinner p2_runestone_green;
Spinner p2_telescope;
Spinner p2_helm;
Spinner p2_medicinal_herb;
Spinner p2_witch_brew;
Spinner p2_runestone_yellow;
ImageButton p2_pic_gold;
ImageButton p2_pic_runestone_blue;
ImageButton p2_pic_wineskin;
ImageButton p2_pic_runestone_green;
ImageButton p2_pic_telescope;
ImageButton p2_pic_helm;
ImageButton p2_pic_medicinal_herb;
ImageButton p2_pic_witch_brew;
ImageButton p2_pic_runestone_yellow;
MyPlayer myPlayer;
TextView p1_heroclass;
TextView p2_heroclass;
HeroClass p2_hero_class;
HeroClass p1_hero_class;
private Thread t;
private boolean threadTerminated = false;
FalconTradeObject clientTrade;
Boolean isPlayer1;
Button p1_confirm;
Button p2_confirm;
TextView p1_hasConfirmed;
TextView p2_hasConfirmed;
Button trade;
@Override
public void onBackPressed(){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.falcon_trade);
p1_gold = findViewById(R.id.p1_gold);
p1_runestone_yellow = findViewById(R.id.p1_runestone_yellow);
p1_runestone_blue = findViewById(R.id.p1_runestone_blue);
p1_runestone_green = findViewById(R.id.p1_runestone_green);
p1_helm = findViewById(R.id.p1_helm);
p1_medicinal_herb = findViewById(R.id.p1_medicinal_herb);
p1_wineskin = findViewById(R.id.p1_wineskin);
p1_telescope = findViewById(R.id.p1_telescope);
p1_witch_brew = findViewById(R.id.p1_witch_brew);
p1_gold.setVisibility(View.INVISIBLE);
p1_runestone_yellow.setVisibility(View.INVISIBLE);
p1_runestone_blue.setVisibility(View.INVISIBLE);
p1_runestone_green.setVisibility(View.INVISIBLE);
p1_helm.setVisibility(View.INVISIBLE);
p1_medicinal_herb.setVisibility(View.INVISIBLE);
p1_wineskin.setVisibility(View.INVISIBLE);
p1_telescope.setVisibility(View.INVISIBLE);
p1_witch_brew.setVisibility(View.INVISIBLE);
p1_pic_gold = findViewById(R.id.p1_gold_pic);
p1_pic_runestone_yellow = findViewById(R.id.p1_runestone_yellow_pic);
p1_pic_runestone_blue = findViewById(R.id.p1_runestone_blue_pic);
p1_pic_runestone_green = findViewById(R.id.p1_runestone_green_pic);
p1_pic_helm = findViewById(R.id.p1_helm_pic);
p1_pic_medicinal_herb = findViewById(R.id.p1_medicinal_herb_pic);
p1_pic_wineskin = findViewById(R.id.p1_wineskin_pic);
p1_pic_telescope = findViewById(R.id.p1_telescope_pic);
p1_pic_witch_brew = findViewById(R.id.p1_witch_brew_pic);
p1_pic_gold.setVisibility(View.INVISIBLE);
p1_pic_runestone_yellow.setVisibility(View.INVISIBLE);
p1_pic_runestone_blue.setVisibility(View.INVISIBLE);
p1_pic_runestone_green.setVisibility(View.INVISIBLE);
p1_pic_helm.setVisibility(View.INVISIBLE);
p1_pic_medicinal_herb.setVisibility(View.INVISIBLE);
p1_pic_wineskin.setVisibility(View.INVISIBLE);
p1_pic_telescope.setVisibility(View.INVISIBLE);
p1_pic_witch_brew.setVisibility(View.INVISIBLE);
p2_gold = findViewById(R.id.p2_gold);
p2_runestone_yellow = findViewById(R.id.p2_runestone_yellow);
p2_runestone_blue = findViewById(R.id.p2_runestone_blue);
p2_runestone_green = findViewById(R.id.p2_runestone_green);
p2_helm = findViewById(R.id.p2_helm);
p2_medicinal_herb = findViewById(R.id.p2_medicinal_herb);
p2_wineskin = findViewById(R.id.p2_wineskin);
p2_telescope = findViewById(R.id.p2_telescope);
p2_witch_brew = findViewById(R.id.p2_witch_brew);
p2_gold.setVisibility(View.INVISIBLE);
p2_runestone_yellow.setVisibility(View.INVISIBLE);
p2_runestone_blue.setVisibility(View.INVISIBLE);
p2_runestone_green.setVisibility(View.INVISIBLE);
p2_helm.setVisibility(View.INVISIBLE);
p2_medicinal_herb.setVisibility(View.INVISIBLE);
p2_wineskin.setVisibility(View.INVISIBLE);
p2_telescope.setVisibility(View.INVISIBLE);
p2_witch_brew.setVisibility(View.INVISIBLE);
p2_pic_gold = findViewById(R.id.p2_gold_pic);
p2_pic_runestone_yellow = findViewById(R.id.p2_runestone_yellow_pic);
p2_pic_runestone_blue = findViewById(R.id.p2_runestone_blue_pic);
p2_pic_runestone_green = findViewById(R.id.p2_runestone_green_pic);
p2_pic_helm = findViewById(R.id.p2_helm_pic);
p2_pic_medicinal_herb = findViewById(R.id.p2_medicinal_herb_pic);
p2_pic_wineskin = findViewById(R.id.p2_wineskin_pic);
p2_pic_telescope = findViewById(R.id.p2_telescope_pic);
p2_pic_witch_brew = findViewById(R.id.p2_witch_brew_pic);
p2_pic_gold.setVisibility(View.INVISIBLE);
p2_pic_runestone_yellow.setVisibility(View.INVISIBLE);
p2_pic_runestone_blue.setVisibility(View.INVISIBLE);
p2_pic_runestone_green.setVisibility(View.INVISIBLE);
p2_pic_helm.setVisibility(View.INVISIBLE);
p2_pic_medicinal_herb.setVisibility(View.INVISIBLE);
p2_pic_wineskin.setVisibility(View.INVISIBLE);
p2_pic_telescope.setVisibility(View.INVISIBLE);
p2_pic_witch_brew.setVisibility(View.INVISIBLE);
myPlayer = MyPlayer.getInstance();
p1_heroclass = findViewById(R.id.p1_heroclass);
p2_heroclass = findViewById(R.id.p2_heroclass);
p2_hero_class = null;
p1_hero_class = null;
p1_confirm = findViewById(R.id.p1_confirm);
p2_confirm = findViewById(R.id.p2_confirm);
p1_hasConfirmed = findViewById(R.id.p1_has_confirmed);
p2_hasConfirmed = findViewById(R.id.p2_has_confirmed);
trade = findViewById(R.id.trade_items_falcon);
try{
AsyncTask<String, Void, Game> asyncTaskGame;
Game gameToSet;
GetGame getGame = new GetGame();
asyncTaskGame = getGame.execute();
gameToSet = asyncTaskGame.get();
System.out.println(gameToSet);
myPlayer.setGame(gameToSet);
for(int i = 0; i < gameToSet.getCurrentNumPlayers(); i++){
if(gameToSet.getPlayers()[i].getUsername().equals(myPlayer.getPlayer().getUsername())){
myPlayer.setPlayer(gameToSet.getPlayers()[i]);
}
}
}catch (Exception e){
e.printStackTrace();
}
String p1_hero_string = getIntent().getExtras().getString("p1");
if(p1_hero_string != null){
p1_hero_class = getHeroClass(p1_hero_string);
p1_heroclass.setText(p1_hero_string);
}
String p2_hero_string = getIntent().getExtras().getString("p2");
if(p2_hero_string != null){
p2_hero_class = getHeroClass(p2_hero_string);
p2_heroclass.setText(p2_hero_string);
}
if(p1_hero_class != null){
if(p1_hero_class == myPlayer.getPlayer().getHero().getHeroClass()){
isPlayer1 = true;
}else{
isPlayer1 = false;
}
Hero p1_hero = null;
for(int i = 0; i < myPlayer.getGame().getCurrentNumPlayers(); i++){
if(myPlayer.getGame().getPlayers()[i].getHero().getHeroClass() == p1_hero_class){
p1_hero = myPlayer.getGame().getPlayers()[i].getHero();
clientTrade = myPlayer.getGame().getPlayers()[i].getHero().getCurrentFalconTrade();
break;
}
}
if(p1_hero != null){
int p1_num_helms = getNumItems(p1_hero, ItemType.HELM);
int p1_num_telescopes = getNumItems(p1_hero, ItemType.TELESCOPE);
int p1_num_wineskins = getNumItems(p1_hero, ItemType.WINESKIN);
int p1_num_medicinal_herbs = getNumItems(p1_hero, ItemType.MEDICINAL_HERB);
int p1_num_witch_brew = getNumItems(p1_hero, ItemType.WITCH_BREW);
int p1_num_gold = p1_hero.getGold();
int p1_num_runestone_yellow = 0;
int p1_num_runestone_blue = 0;
int p1_num_runestone_green = 0;
for(RuneStone runeStone : p1_hero.getRuneStones()){
if(runeStone.getColour() == Colour.YELLOW){
p1_num_runestone_yellow++;
}
if(runeStone.getColour() == Colour.BLUE){
p1_num_runestone_blue++;
}
if(runeStone.getColour() == Colour.GREEN){
p1_num_runestone_green++;
}
}
if(p1_num_helms > 0){
p1_pic_helm.setVisibility(View.VISIBLE);
p1_helm.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_helms; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_helm.setAdapter(adapterDrop);
}
if(p1_num_telescopes > 0){
p1_pic_telescope.setVisibility(View.VISIBLE);
p1_telescope.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_telescopes; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_telescope.setAdapter(adapterDrop);
}
if(p1_num_wineskins > 0){
p1_pic_wineskin.setVisibility(View.VISIBLE);
p1_wineskin.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_wineskins; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_wineskin.setAdapter(adapterDrop);
}
if(p1_num_medicinal_herbs > 0){
p1_pic_medicinal_herb.setVisibility(View.VISIBLE);
p1_medicinal_herb.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_medicinal_herbs; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_medicinal_herb.setAdapter(adapterDrop);
}
if(p1_num_witch_brew > 0){
p1_pic_witch_brew.setVisibility(View.VISIBLE);
p1_witch_brew.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_witch_brew; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_witch_brew.setAdapter(adapterDrop);
}
if(p1_num_gold > 0){
p1_pic_gold.setVisibility(View.VISIBLE);
p1_gold.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_gold; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_gold.setAdapter(adapterDrop);
}
if(p1_num_runestone_blue > 0){
p1_pic_runestone_blue.setVisibility(View.VISIBLE);
p1_runestone_blue.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_blue; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_blue.setAdapter(adapterDrop);
}
if(p1_num_runestone_yellow > 0){
p1_pic_runestone_yellow.setVisibility(View.VISIBLE);
p1_runestone_yellow.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_yellow; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_yellow.setAdapter(adapterDrop);
}
if(p1_num_runestone_green > 0){
p1_pic_runestone_green.setVisibility(View.VISIBLE);
p1_runestone_green.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p1_num_runestone_green; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p1_runestone_green.setAdapter(adapterDrop);
}
}
}
if(p2_hero_class != null){
Hero p2_hero = null;
for(int i = 0; i < myPlayer.getGame().getCurrentNumPlayers(); i++){
if(myPlayer.getGame().getPlayers()[i].getHero().getHeroClass() == p2_hero_class){
p2_hero = myPlayer.getGame().getPlayers()[i].getHero();
break;
}
}
if(p2_hero != null){
int p2_num_helms = getNumItems(p2_hero, ItemType.HELM);
int p2_num_telescopes = getNumItems(p2_hero, ItemType.TELESCOPE);
int p2_num_wineskins = getNumItems(p2_hero, ItemType.WINESKIN);
int p2_num_medicinal_herbs = getNumItems(p2_hero, ItemType.MEDICINAL_HERB);
int p2_num_witch_brew = getNumItems(p2_hero, ItemType.WITCH_BREW);
int p2_num_gold = p2_hero.getGold();
int p2_num_runestone_yellow = 0;
int p2_num_runestone_blue = 0;
int p2_num_runestone_green = 0;
for(RuneStone runeStone : p2_hero.getRuneStones()){
if(runeStone.getColour() == Colour.YELLOW){
p2_num_runestone_yellow++;
}
if(runeStone.getColour() == Colour.BLUE){
p2_num_runestone_blue++;
}
if(runeStone.getColour() == Colour.GREEN){
p2_num_runestone_green++;
}
}
if(p2_num_helms > 0){
p2_pic_helm.setVisibility(View.VISIBLE);
p2_helm.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_helms; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_helm.setAdapter(adapterDrop);
}
if(p2_num_telescopes > 0){
p2_pic_telescope.setVisibility(View.VISIBLE);
p2_telescope.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_telescopes; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_telescope.setAdapter(adapterDrop);
}
if(p2_num_wineskins > 0){
p2_pic_wineskin.setVisibility(View.VISIBLE);
p2_wineskin.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_wineskins; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_wineskin.setAdapter(adapterDrop);
}
if(p2_num_medicinal_herbs > 0){
p2_pic_medicinal_herb.setVisibility(View.VISIBLE);
p2_medicinal_herb.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_medicinal_herbs; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_medicinal_herb.setAdapter(adapterDrop);
}
if(p2_num_witch_brew > 0){
p2_pic_witch_brew.setVisibility(View.VISIBLE);
p2_witch_brew.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_witch_brew; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_witch_brew.setAdapter(adapterDrop);
}
if(p2_num_gold > 0){
p2_pic_gold.setVisibility(View.VISIBLE);
p2_gold.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_gold; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_gold.setAdapter(adapterDrop);
}
if(p2_num_runestone_blue > 0){
p2_pic_runestone_blue.setVisibility(View.VISIBLE);
p2_runestone_blue.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_blue; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_blue.setAdapter(adapterDrop);
}
if(p2_num_runestone_yellow > 0){
p2_pic_runestone_yellow.setVisibility(View.VISIBLE);
p2_runestone_yellow.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_yellow; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_yellow.setAdapter(adapterDrop);
}
if(p2_num_runestone_green > 0){
p2_pic_runestone_green.setVisibility(View.VISIBLE);
p2_runestone_green.setVisibility(View.VISIBLE);
ArrayList<Integer> values = new ArrayList<>();
values.add(0);
for(int i = 0; i < p2_num_runestone_green; i++){
values.add(i+1);
}
ArrayAdapter<Integer> adapterDrop = new ArrayAdapter<Integer>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, values);
adapterDrop.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
p2_runestone_green.setAdapter(adapterDrop);
}
}
}
t = new Thread(new Runnable() {
@Override
public void run() {
myPlayer = MyPlayer.getInstance();
while(!threadTerminated){
try{
final HttpResponse<String> httpResponse = Unirest.get("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getPlayer().getUsername() + "/getGameUpdate")
.asString();
if(httpResponse.getCode() == 200){
final Game game = new Gson().fromJson(httpResponse.getBody(), Game.class);
MyPlayer.getInstance().setGame(game);
for(int i = 0; i < game.getCurrentNumPlayers(); i++){
if(game.getPlayers()[i].getUsername().equals(myPlayer.getPlayer().getUsername())){
myPlayer.setPlayer(game.getPlayers()[i]);
}
}
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < game.getCurrentNumPlayers(); i++){
if(game.getPlayers()[i].getHero().getHeroClass() == p1_hero_class){
FalconTradeObject currentTrade = game.getPlayers()[i].getHero().getCurrentFalconTrade();
if(currentTrade == null){
Toast.makeText(FalconTrade.this, "Falcon Trade Processed", Toast.LENGTH_LONG).show();
threadTerminated = true;
startActivity(new Intent(FalconTrade.this, UseArticle.class));
finish();
}else{
p1_gold.setSelection(getIndex(p1_gold, currentTrade.getP1_gold()));
p1_wineskin.setSelection(getIndex(p1_wineskin, currentTrade.getP1_wineskin()));
p1_runestone_blue.setSelection(getIndex(p1_runestone_blue, currentTrade.getP1_runestone_blue()));
p1_runestone_green.setSelection(getIndex(p1_runestone_green, currentTrade.getP1_runestone_green()));
p1_runestone_yellow.setSelection(getIndex(p1_runestone_yellow,currentTrade.getP1_runestone_yellow()));
p1_telescope.setSelection(getIndex(p1_telescope, currentTrade.getP1_telescope()));
p1_helm.setSelection(getIndex(p1_helm, currentTrade.getP1_helm()));
p1_medicinal_herb.setSelection(getIndex(p1_medicinal_herb, currentTrade.getP1_medicinal_herb()));
p1_witch_brew.setSelection(getIndex(p1_witch_brew,currentTrade.getP1_witch_brew()));
p2_gold.setSelection(getIndex(p2_gold, currentTrade.getP2_gold()));
p2_wineskin.setSelection(getIndex(p2_wineskin, currentTrade.getP2_wineskin()));
p2_runestone_blue.setSelection(getIndex(p2_runestone_blue, currentTrade.getP2_runestone_blue()));
p2_runestone_green.setSelection(getIndex(p2_runestone_green, currentTrade.getP2_runestone_green()));
p2_runestone_yellow.setSelection(getIndex(p2_runestone_yellow,currentTrade.getP2_runestone_yellow()));
p2_telescope.setSelection(getIndex(p2_telescope, currentTrade.getP2_telescope()));
p2_helm.setSelection(getIndex(p2_helm, currentTrade.getP2_helm()));
p2_medicinal_herb.setSelection(getIndex(p2_medicinal_herb, currentTrade.getP2_medicinal_herb()));
p2_witch_brew.setSelection(getIndex(p2_witch_brew,currentTrade.getP2_witch_brew()));
if(!currentTrade.isDontUpdate()){
if(currentTrade.isP1_hasConfirmed()){
p1_hasConfirmed.setBackgroundColor(Color.GREEN);
}else{
p1_hasConfirmed.setBackgroundColor(Color.RED);
}
}
if(currentTrade.isP2_hasConfirmed()){
p2_hasConfirmed.setBackgroundColor(Color.GREEN);
}else{
p2_hasConfirmed.setBackgroundColor(Color.RED);
}
currentTrade.setDontUpdate(false);
}
}
}
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
}
});
t.start();
if(!isPlayer1){
p1_gold.setEnabled(false);
p1_runestone_yellow.setEnabled(false);
p1_runestone_blue.setEnabled(false);
p1_runestone_green.setEnabled(false);
p1_helm.setEnabled(false);
p1_medicinal_herb.setEnabled(false);
p1_wineskin.setEnabled(false);
p1_telescope.setEnabled(false);
p1_witch_brew.setEnabled(false);
p2_gold.setEnabled(false);
p2_runestone_yellow.setEnabled(false);
p2_runestone_blue.setEnabled(false);
p2_runestone_green.setEnabled(false);
p2_helm.setEnabled(false);
p2_medicinal_herb.setEnabled(false);
p2_wineskin.setEnabled(false);
p2_telescope.setEnabled(false);
p2_witch_brew.setEnabled(false);
p1_hasConfirmed.setEnabled(false);
p1_confirm.setEnabled(false);
p1_confirm.setVisibility(View.INVISIBLE);
trade.setVisibility(View.INVISIBLE);
}else{
p2_hasConfirmed.setEnabled(false);
p2_confirm.setEnabled(false);
p2_confirm.setVisibility(View.INVISIBLE);
}
p1_gold.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_gold((Integer) p1_gold.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_wineskin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_wineskin((Integer) p1_wineskin.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_telescope.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_telescope((Integer) p1_telescope.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_helm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_helm((Integer) p1_helm.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_medicinal_herb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_medicinal_herb((Integer) p1_medicinal_herb.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_witch_brew.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_witch_brew((Integer) p1_witch_brew.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_blue.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_blue((Integer) p1_runestone_blue.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_yellow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_yellow((Integer) p1_runestone_yellow.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_runestone_green.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP1_runestone_green((Integer) p1_runestone_green.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_gold.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_gold((Integer) p2_gold.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_wineskin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_wineskin((Integer) p2_wineskin.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_telescope.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_telescope((Integer) p2_telescope.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_helm.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_helm((Integer) p2_helm.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_medicinal_herb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_medicinal_herb((Integer) p2_medicinal_herb.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_witch_brew.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_witch_brew((Integer) p2_witch_brew.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_blue.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_blue((Integer) p2_runestone_blue.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_yellow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_yellow((Integer) p2_runestone_yellow.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p2_runestone_green.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
clientTrade.setP2_runestone_green((Integer) p2_runestone_green.getSelectedItem());
if(!clientTrade.isDontUpdate()){
if(isPlayer1){
p1_hasConfirmed.setBackgroundColor(Color.RED);
p2_hasConfirmed.setBackgroundColor(Color.RED);
clientTrade.setP1_hasConfirmed(false);
}
clientTrade.setP2_hasConfirmed(false);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
p1_confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clientTrade.setP1_hasConfirmed(true);
sendUpdatedTradeObject(clientTrade);
}
});
p2_confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clientTrade.setP2_hasConfirmed(true);
clientTrade.setDontUpdate(true);
sendUpdatedTradeObject(clientTrade);
}
});
trade.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.out.println(clientTrade.toString());
ColorDrawable p1_color = (ColorDrawable) p1_hasConfirmed.getBackground();
ColorDrawable p2_color = (ColorDrawable) p2_hasConfirmed.getBackground();
if(p1_color.getColor() == Color.GREEN && p2_color.getColor() == Color.GREEN){
AsyncTask<String,Void,ProcessFalconTradeResponses> asyncTask;
ProcessFalconTradeResponses processFalconTradeResponses = null;
ProcessFalconTrade processFalconTrade = new ProcessFalconTrade();
try{
asyncTask = processFalconTrade.execute(new Gson().toJson(clientTrade));
processFalconTradeResponses = asyncTask.get();
}catch(Exception e){
e.printStackTrace();
}
if (processFalconTradeResponses == ProcessFalconTradeResponses.CANNOT_ACCEPT_ITEMS) {
Toast.makeText(FalconTrade.this,"One or more of the heroes cannot accept the items requested" , Toast.LENGTH_LONG).show();
clientTrade.clearValues();
sendUpdatedTradeObject(clientTrade);
}else if (processFalconTradeResponses == ProcessFalconTradeResponses.TRADE_FAILED){
Toast.makeText(FalconTrade.this,"Falcon trade failed for unknown reasons, please try again" , Toast.LENGTH_LONG).show();
clientTrade.clearValues();
sendUpdatedTradeObject(clientTrade);
}else if(processFalconTradeResponses == ProcessFalconTradeResponses.TRADE_PROCESSED){
}
}else{
Toast.makeText(FalconTrade.this,"Not ready to trade. Please wait until both players confirm" , Toast.LENGTH_LONG).show();
}
}
});
}
private static class GetGame extends AsyncTask<String, Void, Game > {
@Override
protected Game doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.get("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getPlayer().getUsername() + "/getGameByUsername")
.asString();
String resultAsJsonString = response.getBody();
System.out.println("RESPONSE BODY " + response.getBody());
return new Gson().fromJson(resultAsJsonString, Game.class);
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
public static int getNumItems(Hero hero, ItemType type){
int count = 0;
for(Item item : hero.getItems()){
if(item.getItemType() == type){
count++;
}
}
return count;
}
public static HeroClass getHeroClass(String heroString){
if(heroString.equals("wizard")){
return HeroClass.WIZARD;
}else if(heroString.equals("warrior")){
return HeroClass.WARRIOR;
}else if (heroString.equals("archer")){
return HeroClass.ARCHER;
}else if(heroString.equals("dwarf")){
return HeroClass.DWARF;
}
return null;
}
private int getIndex(Spinner spinner, Integer num){
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i) == num){
return i;
}
}
return -1;
}
private static class SendFalconTradeObject extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.post("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getGame().getGameName() + "/" + myPlayer.getPlayer().getUsername() + "/updateFalconTradeObject")
.header("Content-Type", "application/json")
.body(strings[0])
.asString();
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
private static class ProcessFalconTrade extends AsyncTask<String, Void, ProcessFalconTradeResponses> {
@Override
protected ProcessFalconTradeResponses doInBackground(String... strings) {
MyPlayer myPlayer = MyPlayer.getInstance();
HttpResponse<String> response;
try {
response = Unirest.post("http://" + myPlayer.getServerIP() + ":8080/" + myPlayer.getGame().getGameName() + "/processFalconTrade")
.header("Content-Type", "application/json")
.body(strings[0])
.asString();
String resultAsJsonString = response.getBody();
return new Gson().fromJson(resultAsJsonString, ProcessFalconTradeResponses.class);
} catch (UnirestException e) {
e.printStackTrace();
}
return null;
}
}
private void sendUpdatedTradeObject(FalconTradeObject falconTradeObject){
AsyncTask<String,Void,Void> asyncTask;
SendFalconTradeObject sendFalconTradeObject = new SendFalconTradeObject();
asyncTask = sendFalconTradeObject.execute(new Gson().toJson(falconTradeObject));
}
}
| 53,504 | 0.545735 | 0.533231 | 1,109 | 47.245266 | 34.57449 | 193 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694319 | false | false | 4 |
2f47f2a35d20fe65ff02dfb04c58f55d204df9ea | 2,834,678,438,901 | 56adea945b27ccaf880decadb7f7cb86de450a8d | /core/ep-core/src/test/java/com/elasticpath/service/pricing/dao/impl/BaseAmountDaoImplTest.java | 715314666db78cb31fa3775ba3f7388f797030c7 | [] | no_license | ryanlfoster/ep-commerce-engine-68 | https://github.com/ryanlfoster/ep-commerce-engine-68 | 89b56878806ca784eca453d58fb91836782a0987 | 7364bce45d25892e06df2e1c51da84dbdcebce5d | refs/heads/master | 2020-04-16T04:27:40.577000 | 2013-12-10T19:31:52 | 2013-12-10T20:01:08 | 40,164,760 | 1 | 1 | null | true | 2015-08-04T05:15:25 | 2015-08-04T05:15:25 | 2014-06-02T21:13:54 | 2013-12-10T21:24:38 | 86,120 | 0 | 0 | 0 | null | null | null | package com.elasticpath.service.pricing.dao.impl;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;
import com.elasticpath.common.pricing.service.BaseAmountFilter;
import com.elasticpath.common.pricing.service.impl.BaseAmountFilterImpl;
import com.elasticpath.domain.pricing.BaseAmount;
import com.elasticpath.persistence.api.EpPersistenceException;
import com.elasticpath.persistence.api.PersistenceEngine;
/**
* Test for BaseAmountDaoImpl.
*/
public class BaseAmountDaoImplTest {
@Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
/**
* Test the JPQL query builder.
* @throws Exception on error
*/
@Test
public void testQueryBuilder() throws Exception {
final BigDecimal quantityDbl = new BigDecimal("2.43");
final BigDecimal list = new BigDecimal("9.9");
final BigDecimal sale = new BigDecimal("3.14");
BaseAmountFilter filter = new BaseAmountFilterImpl();
filter.setObjectGuid("GUID");
BaseAmountDaoImpl.BaseAmountJPQLBuilder builder = new BaseAmountDaoImpl().new BaseAmountJPQLBuilder(filter);
assertEquals("SELECT baseAmount FROM BaseAmountImpl AS baseAmount WHERE baseAmount.objectGuid = 'GUID'", builder.toString());
BaseAmountFilter filter2 = new BaseAmountFilterImpl();
filter2.setObjectGuid("GUID2");
filter2.setObjectType("PROD");
filter2.setListValue(list);
filter2.setSaleValue(sale);
filter2.setPriceListDescriptorGuid("PRICELISTGUID");
filter2.setQuantity(quantityDbl);
BaseAmountDaoImpl.BaseAmountJPQLBuilder builder2 = new BaseAmountDaoImpl().new BaseAmountJPQLBuilder(filter2);
assertEquals("SELECT baseAmount FROM BaseAmountImpl AS baseAmount "
+ "WHERE baseAmount.objectGuid = 'GUID2' "
+ "AND baseAmount.objectType = 'PROD' "
+ "AND baseAmount.priceListDescriptorGuid = 'PRICELISTGUID' "
+ "AND baseAmount.listValueInternal = 9.9 "
+ "AND baseAmount.saleValueInternal = 3.14 "
+ "AND baseAmount.quantityInternal = 2.43", builder2.toString());
}
/**
* Test that guid/uidpk checking is done before updating a BaseAmount.
*/
@Test
public void testUpdateGuidChecking() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
final PersistenceEngine engine = context.mock(PersistenceEngine.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public PersistenceEngine getPersistenceEngine() {
return engine;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(true));
oneOf(baseAmount).getGuid(); will(returnValue("GUID"));
oneOf(engine).saveOrUpdate(baseAmount); will(returnValue(baseAmount));
} });
dao.update(baseAmount);
}
/**
* Test that if BaseAmount doesn't have a GUID, exception is thrown.
* Service won't be able to update a non existing guid.
*/
@Test(expected = EpPersistenceException.class)
public void testUpdateExceptionNoGuid() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public BaseAmount findBaseAmountByGuid(final String guid) {
return null;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(true));
oneOf(baseAmount).getGuid(); will(returnValue(null));
} });
dao.update(baseAmount);
}
/**
* Test that if BaseAmount doesn't have a UIDPK, exception is thrown.
* Service won't be able to update a non persisted object.
*/
@Test(expected = EpPersistenceException.class)
public void testUpdateExceptionNoUid() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public BaseAmount findBaseAmountByGuid(final String guid) {
return null;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(false));
} });
dao.update(baseAmount);
}
}
| UTF-8 | Java | 4,058 | java | BaseAmountDaoImplTest.java | Java | [] | null | [] | package com.elasticpath.service.pricing.dao.impl;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Rule;
import org.junit.Test;
import com.elasticpath.common.pricing.service.BaseAmountFilter;
import com.elasticpath.common.pricing.service.impl.BaseAmountFilterImpl;
import com.elasticpath.domain.pricing.BaseAmount;
import com.elasticpath.persistence.api.EpPersistenceException;
import com.elasticpath.persistence.api.PersistenceEngine;
/**
* Test for BaseAmountDaoImpl.
*/
public class BaseAmountDaoImplTest {
@Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
/**
* Test the JPQL query builder.
* @throws Exception on error
*/
@Test
public void testQueryBuilder() throws Exception {
final BigDecimal quantityDbl = new BigDecimal("2.43");
final BigDecimal list = new BigDecimal("9.9");
final BigDecimal sale = new BigDecimal("3.14");
BaseAmountFilter filter = new BaseAmountFilterImpl();
filter.setObjectGuid("GUID");
BaseAmountDaoImpl.BaseAmountJPQLBuilder builder = new BaseAmountDaoImpl().new BaseAmountJPQLBuilder(filter);
assertEquals("SELECT baseAmount FROM BaseAmountImpl AS baseAmount WHERE baseAmount.objectGuid = 'GUID'", builder.toString());
BaseAmountFilter filter2 = new BaseAmountFilterImpl();
filter2.setObjectGuid("GUID2");
filter2.setObjectType("PROD");
filter2.setListValue(list);
filter2.setSaleValue(sale);
filter2.setPriceListDescriptorGuid("PRICELISTGUID");
filter2.setQuantity(quantityDbl);
BaseAmountDaoImpl.BaseAmountJPQLBuilder builder2 = new BaseAmountDaoImpl().new BaseAmountJPQLBuilder(filter2);
assertEquals("SELECT baseAmount FROM BaseAmountImpl AS baseAmount "
+ "WHERE baseAmount.objectGuid = 'GUID2' "
+ "AND baseAmount.objectType = 'PROD' "
+ "AND baseAmount.priceListDescriptorGuid = 'PRICELISTGUID' "
+ "AND baseAmount.listValueInternal = 9.9 "
+ "AND baseAmount.saleValueInternal = 3.14 "
+ "AND baseAmount.quantityInternal = 2.43", builder2.toString());
}
/**
* Test that guid/uidpk checking is done before updating a BaseAmount.
*/
@Test
public void testUpdateGuidChecking() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
final PersistenceEngine engine = context.mock(PersistenceEngine.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public PersistenceEngine getPersistenceEngine() {
return engine;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(true));
oneOf(baseAmount).getGuid(); will(returnValue("GUID"));
oneOf(engine).saveOrUpdate(baseAmount); will(returnValue(baseAmount));
} });
dao.update(baseAmount);
}
/**
* Test that if BaseAmount doesn't have a GUID, exception is thrown.
* Service won't be able to update a non existing guid.
*/
@Test(expected = EpPersistenceException.class)
public void testUpdateExceptionNoGuid() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public BaseAmount findBaseAmountByGuid(final String guid) {
return null;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(true));
oneOf(baseAmount).getGuid(); will(returnValue(null));
} });
dao.update(baseAmount);
}
/**
* Test that if BaseAmount doesn't have a UIDPK, exception is thrown.
* Service won't be able to update a non persisted object.
*/
@Test(expected = EpPersistenceException.class)
public void testUpdateExceptionNoUid() {
final BaseAmount baseAmount = context.mock(BaseAmount.class);
BaseAmountDaoImpl dao = new BaseAmountDaoImpl() {
@Override
public BaseAmount findBaseAmountByGuid(final String guid) {
return null;
}
};
context.checking(new Expectations() { {
oneOf(baseAmount).isPersisted(); will(returnValue(false));
} });
dao.update(baseAmount);
}
}
| 4,058 | 0.748891 | 0.741745 | 118 | 33.389832 | 27.785509 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.127119 | false | false | 4 |
1a705d4dc13eac604a0b6342a4276fa16419be9c | 5,600,637,394,381 | 7bbc7513eff59a13406312177144d8f472065cf7 | /pense-analisador-semantico/src/test/java/br/com/pense/produto/controller/AbstractSemanticEngineTest.java | 0183a87e4f8e270a7c6d641c342cdd04f3a8accb | [
"BSD-3-Clause"
] | permissive | PenseClassi/pense-semantic-analiser | https://github.com/PenseClassi/pense-semantic-analiser | 38a8d2c7bdb3612b6a221f2219c5f2cd52ead0a8 | ea2e8f2e828ab68fde17f14d98a7f12f403f1a95 | refs/heads/master | 2021-01-10T22:08:54.619000 | 2014-01-22T13:20:57 | 2014-01-22T13:20:57 | 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 br.com.pense.produto.controller;
import junit.framework.TestCase;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author Felipe_Noguez
*/
public class AbstractSemanticEngineTest extends TestCase {
private static SemanticEngineImoveis engImoveis;
public AbstractSemanticEngineTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
if (engImoveis == null){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-semantic.xml");
engImoveis = (SemanticEngineImoveis)context.getBean("engineSemantica");
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testConsultaOntologiaBaseadaEmDadosPenseQuartos() {
System.out.println(">>>> testConsultaOntologiaBaseadaEmDadosPenseQuartos");
////SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("Apartamento 1 dormitorio Porto Alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("apartamento 1 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[1:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 3 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("apartamento 1, 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("casa de madeira 3 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Casa de madeira]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa de madeira 3d e 2d em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Casa de madeira]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 dormitórios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("apartamento 2 dormitorios porto alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("1 dormitorio em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[1:1]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 3 dormitórios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[3:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("Casas 1 e 2 dormitórios em Joinville");
engImoveis.executeQuery();
assertEquals("{cidade=[Joinville], Dormitórios=[1:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("2 dormitorios com garagem em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:2], Vagas de garagem=[1:]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento mobiliado em porto alegre 2 dormitorios rs");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], estado=[rio grande do sul], Características=[Mobiliado], Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa 3 quartos em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[3:3], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 quartos");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
// System.out.println("-*--------------------------------------------------------------------------");
// engImoveis.preparaConteudoBusca("apartamento de 01 dormitório em porto alegre");
// engImoveis.executeQuery();
// engImoveis.getResultsAsString();
}
public void testConsultaSaoFranciscoDePaulaComplexo() {
System.out.println(">>>> testConsultaSaoFranciscoDePaulaComplexo");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com lareira, churrasqueira e play");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Playground], Características=[Lareira, Churrasqueira], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com 2d, lareira, churrasqueira e play");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Playground], Características=[Lareira, Churrasqueira], Dormitórios=[2:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com dois quartos, lareira, churrasqueira e play piscina zelador");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Zelador, Playground, Piscina], Características=[Lareira, Churrasqueira], Dormitórios=[2:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
}
public void testConsultaQuarto() {
System.out.println(">>>> testConsultaQuarto");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 1 a 3 quartos");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[1:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
//
// engImoveis.preparaConteudoBusca("cobertura com um a três quartos");
// engImoveis.executeQuery();
// //assertEquals("{Dormitórios=[1:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
// engImoveis.getResultsAsString();
}
public void testBanheiroSuiteQuarto() {
System.out.println(">>>> testBanheiroSuiteQuarto");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 a 3 dormitorios, 2 a 3 suites, 1 banheiro");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Dormitórios=[2:3], Suítes=[2:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
}
public void testComplexo() {
System.out.println(">>>> testComplexo");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 a 3 dormitorios, 2 a 3 suites, banheiro com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[2:3], Suítes=[2:3], Vagas de garagem=[1:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura com dormitorios, suites, banheiros com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[1:5], Suítes=[1:5], Vagas de garagem=[1:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("2 a 3 dormitorios, 2 a 3 suites, banheiro com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[2:3], Suítes=[2:3], Vagas de garagem=[1:]}", engImoveis.getResultsAsString());
}
public void testMetragemExtenso() {
System.out.println(">>>> testMetragemExtenso");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados ou 3mil metros quadrados");
engImoveis.executeQuery();
assertEquals("{Área total=[2000:3000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 3mil com piscina");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Infraestrutura=[Piscina], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 3 mil com piscina");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Infraestrutura=[Piscina], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura entre 3 milhões e 4 milhões, com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura entre 3 milhões e 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 3 mil até 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 3 mil até R$ 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados");
engImoveis.executeQuery();
assertEquals("{Área total=[2000:2000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[2000:2000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura apartir de R$ 3mil até R$ 5mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:5000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento de R$300.000 a R$ 400.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:400000], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
String ret = "{Banheiros=[1:], cidade=[Porto Alegre], Preço=[:1000000], Infraestrutura=[Piscina], Características=[Churrasqueira], Vagas de garagem=[1:], Tipo de imóvel=[Casa]}";
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de R$1.000.000,00"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de R$ 1.000.000,00"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de 1.000.000,00"));
ret = "{estado=[rio grande do sul], Tipo de imóvel=[Casa]}";
assertEquals(ret, engImoveis.obtemParametrosAsString("casa no rio grande do sul"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa em rio grande do sul"));
}
public void testCidadeBairros(){
System.out.println(">>>> testCidadeBairros");
assertEquals("{cidade=[Porto Alegre], bairroCodigo=[3919], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa em porto alegre na azenha"));
assertEquals("{cidade=[Canoas], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa em canoas na azenha"));
}
public void testMaisDeMenosDe(){
System.out.println(">>>> testMaisDeMenosDe");
assertEquals("{Dormitórios=[2:5], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos"));
assertEquals("{Dormitórios=[1:4], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com menos de 4 quartos"));
assertEquals("{Dormitórios=[2:5], Suítes=[2:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, de 2 a 3 suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[1:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, com menos de 3 suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[2:5], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, 2 ou mais suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[1:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, 3 ou menos suites"));
}
public void testBairros(){
System.out.println(">>>> testBairros");
assertEquals("{Tipo de imóvel=[Casa]}",engImoveis.obtemParametrosAsString("casa na azenha"));
}
public void testInfra(){
System.out.println(">>>> testInfra");
assertEquals("{Infraestrutura=[Churrasqueira coletiva], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com churrasqueira coletiva"));
assertEquals("{Infraestrutura=[Área de serviço], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com area de serviço"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso deficientes"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso para deficientes"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso de deficientes"));
assertEquals("{Infraestrutura=[Academia / espaço fitness], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com espaço fitness"));
assertEquals("{Infraestrutura=[Quadra esportiva], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com quadra esportiva"));
assertEquals("{Infraestrutura=[Salão de festas], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com salão de festas"));
assertEquals("{Infraestrutura=[Salão de festas], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com salao de festas"));
}
public void testMetrosQuadrados() {
System.out.println(">>>> testMetrosQuadrados");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("apartamento com 25m2 a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25 m2 a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25 m² a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25m² a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.geraParametros("apartamento com 25m² a partir de R$ 3 mil");
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
}
public void testFree(){
System.out.println(">>>> testFree");
assertEquals("{Características=[Sacada], Vagas de garagem=[1:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("Casa com sacada grande e garagem"));
}
public void testIntervalosValores() {
System.out.println(">>>> testIntervalosValores");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 ou mais dormitorios");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[2:5], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura com 2 ou menos dormitorios");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[1:2], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura acima de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura acima de 300.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura abaixo de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura até R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200m2 e acima de R$ 1milhão");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200m2 e acima de R$ 1.000.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200 m2 e acima de R$ 1milhão");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
assertEquals("{Características=[Churrasqueira], Dormitórios=[1:2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com churrasqueira com até 2 quartos"));
}
public void testIntervalosValores_01() {
System.out.println(">>>> testIntervalosValores_01");
assertEquals("{Dormitórios=[1:2]}", engImoveis.obtemParametrosAsString("até 2 dormitórios"));
}
public void testIntervalosValores_02() {
System.out.println(">>>> testIntervalosValores_02");
assertEquals("{Dormitórios=[3:5]}", engImoveis.obtemParametrosAsString("com mais de 3 dormitórios"));
}
public void testIntervalosValores_03() {
System.out.println(">>>> testIntervalosValores_03");
assertEquals("{Dormitórios=[1:4]}", engImoveis.obtemParametrosAsString("com menos de 4 dormitórios"));
}
public void testIntervalosValores_04() {
System.out.println(">>>> testIntervalosValores_04");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("de 1 a 3 dormitórios"));
}
public void testIntervalosValores_05() {
System.out.println(">>>> testIntervalosValores_05");
assertEquals("{Dormitórios=[2:4]}", engImoveis.obtemParametrosAsString("de 2 até 4 dormitórios"));
}
public void testIntervalosValores_06() {
System.out.println(">>>> testIntervalosValores_06");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("com 1 e 3 dormitórios"));
}
public void testIntervalosValores_07() {
System.out.println(">>>> testIntervalosValores_07");
assertEquals("{Dormitórios=[2:4]}", engImoveis.obtemParametrosAsString("com 2 ou 4 dormitórios"));
}
public void testIntervalosValores_08() {
System.out.println(">>>> testIntervalosValores_08");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("com 3 ou menos quartos"));
}
public void testIntervalosValores_09() {
System.out.println(">>>> testIntervalosValores_09");
assertEquals("{Dormitórios=[2:5]}", engImoveis.obtemParametrosAsString("com 2 ou mais quartos"));
}
public void testIntervalosValores_10() {
System.out.println(">>>> testIntervalosValores_10");
assertEquals("{Área total=[13:1000M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa a partir de 13m²"));
}
public void testIntervalosValores_11() {
System.out.println(">>>> testIntervalosValores_11");
assertEquals("{Área total=[13:1000M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de 13m²"));
}
public void testIntervalosValores_12() {
System.out.println(">>>> testIntervalosValores_12");
assertEquals("{Área total=[10:30M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa abaixo de 30m²"));
}
public void testIntervalosValores_13() {
System.out.println(">>>> testIntervalosValores_13");
assertEquals("{Área total=[10:40M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa até 40m²"));
}
public void testIntervalosValores_14() {
System.out.println(">>>> testIntervalosValores_14");
assertEquals("{Área total=[50:50M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa de 50m²"));
}
public void testIntervalosValores_15() {
System.out.println(">>>> testIntervalosValores_15");
assertEquals("{Preço=[300000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa a partir de R$ 300mil"));
}
public void testIntervalosValores_16() {
System.out.println(">>>> testIntervalosValores_16");
assertEquals("{Preço=[1000000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de R$ 1milhão"));
}
public void testIntervalosValores_17() {
System.out.println(">>>> testIntervalosValores_17");
assertEquals("{Preço=[1000000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de R$ 1milhao"));
}
public void testIntervalosValores_18() {
System.out.println(">>>> testIntervalosValores_18");
assertEquals("{Preço=[:1000000], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa abaixo de R$ 1milhao"));
}
public void testIntervalosValores_19() {
System.out.println(">>>> testIntervalosValores_19");
assertEquals("{Preço=[:2000000], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa até R$ 2milhao"));
}
}
| UTF-8 | Java | 26,323 | java | AbstractSemanticEngineTest.java | Java | [
{
"context": "sPathXmlApplicationContext;\r\n\r\n/**\r\n *\r\n * @author Felipe_Noguez\r\n */\r\npublic class AbstractSemanticEngineTest exten",
"end": 379,
"score": 0.9741445183753967,
"start": 366,
"tag": "NAME",
"value": "Felipe_Noguez"
}
] | 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 br.com.pense.produto.controller;
import junit.framework.TestCase;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author Felipe_Noguez
*/
public class AbstractSemanticEngineTest extends TestCase {
private static SemanticEngineImoveis engImoveis;
public AbstractSemanticEngineTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
if (engImoveis == null){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-semantic.xml");
engImoveis = (SemanticEngineImoveis)context.getBean("engineSemantica");
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testConsultaOntologiaBaseadaEmDadosPenseQuartos() {
System.out.println(">>>> testConsultaOntologiaBaseadaEmDadosPenseQuartos");
////SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("Apartamento 1 dormitorio Porto Alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("apartamento 1 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[1:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 3 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("apartamento 1, 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("casa de madeira 3 e 2 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Casa de madeira]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa de madeira 3d e 2d em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Casa de madeira]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 dormitórios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
System.out.println("-*--------------------------------------------------------------------------");
engImoveis.preparaConteudoBusca("apartamento 2 dormitorios porto alegre");
engImoveis.executeQuery();
engImoveis.getResultsAsString();
engImoveis.preparaConteudoBusca("1 dormitorio em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[1:1]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 3 dormitórios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[3:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 e 3 dormitorios em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:3], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("Casas 1 e 2 dormitórios em Joinville");
engImoveis.executeQuery();
assertEquals("{cidade=[Joinville], Dormitórios=[1:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("2 dormitorios com garagem em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[2:2], Vagas de garagem=[1:]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento mobiliado em porto alegre 2 dormitorios rs");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], estado=[rio grande do sul], Características=[Mobiliado], Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa 3 quartos em porto alegre");
engImoveis.executeQuery();
assertEquals("{cidade=[Porto Alegre], Dormitórios=[3:3], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento 2 quartos");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[2:2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
// System.out.println("-*--------------------------------------------------------------------------");
// engImoveis.preparaConteudoBusca("apartamento de 01 dormitório em porto alegre");
// engImoveis.executeQuery();
// engImoveis.getResultsAsString();
}
public void testConsultaSaoFranciscoDePaulaComplexo() {
System.out.println(">>>> testConsultaSaoFranciscoDePaulaComplexo");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com lareira, churrasqueira e play");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Playground], Características=[Lareira, Churrasqueira], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com 2d, lareira, churrasqueira e play");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Playground], Características=[Lareira, Churrasqueira], Dormitórios=[2:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("casa em São Francisco de Paula com dois quartos, lareira, churrasqueira e play piscina zelador");
engImoveis.executeQuery();
assertEquals("{cidade=[São Francisco de Paula], Infraestrutura=[Zelador, Playground, Piscina], Características=[Lareira, Churrasqueira], Dormitórios=[2:2], Tipo de imóvel=[Casa]}", engImoveis.getResultsAsString());
}
public void testConsultaQuarto() {
System.out.println(">>>> testConsultaQuarto");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 1 a 3 quartos");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[1:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
//
// engImoveis.preparaConteudoBusca("cobertura com um a três quartos");
// engImoveis.executeQuery();
// //assertEquals("{Dormitórios=[1:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
// engImoveis.getResultsAsString();
}
public void testBanheiroSuiteQuarto() {
System.out.println(">>>> testBanheiroSuiteQuarto");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 a 3 dormitorios, 2 a 3 suites, 1 banheiro");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Dormitórios=[2:3], Suítes=[2:3], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
}
public void testComplexo() {
System.out.println(">>>> testComplexo");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 a 3 dormitorios, 2 a 3 suites, banheiro com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[2:3], Suítes=[2:3], Vagas de garagem=[1:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura com dormitorios, suites, banheiros com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[1:5], Suítes=[1:5], Vagas de garagem=[1:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("2 a 3 dormitorios, 2 a 3 suites, banheiro com garagem piscina churrasqueira");
engImoveis.executeQuery();
assertEquals("{Banheiros=[1:], Infraestrutura=[Piscina], Características=[Churrasqueira], Dormitórios=[2:3], Suítes=[2:3], Vagas de garagem=[1:]}", engImoveis.getResultsAsString());
}
public void testMetragemExtenso() {
System.out.println(">>>> testMetragemExtenso");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados ou 3mil metros quadrados");
engImoveis.executeQuery();
assertEquals("{Área total=[2000:3000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 3mil com piscina");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Infraestrutura=[Piscina], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 3 mil com piscina");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Infraestrutura=[Piscina], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura entre 3 milhões e 4 milhões, com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura entre 3 milhões e 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 3 mil até 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura de R$ 3 mil até R$ 4 milhões com sacada");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:4000000], Características=[Sacada], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados");
engImoveis.executeQuery();
assertEquals("{Área total=[2000:2000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 2mil metros quadrados a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[2000:2000M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura apartir de R$ 3mil até R$ 5mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:5000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento de R$300.000 a R$ 400.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:400000], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
String ret = "{Banheiros=[1:], cidade=[Porto Alegre], Preço=[:1000000], Infraestrutura=[Piscina], Características=[Churrasqueira], Vagas de garagem=[1:], Tipo de imóvel=[Casa]}";
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de R$1.000.000,00"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de R$ 1.000.000,00"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa com piscina, churrasqueira, banheiro e garagem em poa, abaixo de 1.000.000,00"));
ret = "{estado=[rio grande do sul], Tipo de imóvel=[Casa]}";
assertEquals(ret, engImoveis.obtemParametrosAsString("casa no rio grande do sul"));
assertEquals(ret, engImoveis.obtemParametrosAsString("casa em rio grande do sul"));
}
public void testCidadeBairros(){
System.out.println(">>>> testCidadeBairros");
assertEquals("{cidade=[Porto Alegre], bairroCodigo=[3919], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa em porto alegre na azenha"));
assertEquals("{cidade=[Canoas], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa em canoas na azenha"));
}
public void testMaisDeMenosDe(){
System.out.println(">>>> testMaisDeMenosDe");
assertEquals("{Dormitórios=[2:5], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos"));
assertEquals("{Dormitórios=[1:4], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com menos de 4 quartos"));
assertEquals("{Dormitórios=[2:5], Suítes=[2:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, de 2 a 3 suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[1:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, com menos de 3 suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[2:5], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, 2 ou mais suites"));
assertEquals("{Dormitórios=[2:5], Suítes=[1:3], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com mais de 2 quartos, 3 ou menos suites"));
}
public void testBairros(){
System.out.println(">>>> testBairros");
assertEquals("{Tipo de imóvel=[Casa]}",engImoveis.obtemParametrosAsString("casa na azenha"));
}
public void testInfra(){
System.out.println(">>>> testInfra");
assertEquals("{Infraestrutura=[Churrasqueira coletiva], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com churrasqueira coletiva"));
assertEquals("{Infraestrutura=[Área de serviço], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com area de serviço"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso deficientes"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso para deficientes"));
assertEquals("{Infraestrutura=[Acesso para deficientes], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com acesso de deficientes"));
assertEquals("{Infraestrutura=[Academia / espaço fitness], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com espaço fitness"));
assertEquals("{Infraestrutura=[Quadra esportiva], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com quadra esportiva"));
assertEquals("{Infraestrutura=[Salão de festas], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com salão de festas"));
assertEquals("{Infraestrutura=[Salão de festas], Tipo de imóvel=[Apartamento]}", engImoveis.obtemParametrosAsString("apartamento com salao de festas"));
}
public void testMetrosQuadrados() {
System.out.println(">>>> testMetrosQuadrados");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("apartamento com 25m2 a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25 m2 a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25 m² a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento com 25m² a partir de R$ 3 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.geraParametros("apartamento com 25m² a partir de R$ 3 mil");
assertEquals("{Preço=[3000:], Área total=[25:25M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
}
public void testFree(){
System.out.println(">>>> testFree");
assertEquals("{Características=[Sacada], Vagas de garagem=[1:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("Casa com sacada grande e garagem"));
}
public void testIntervalosValores() {
System.out.println(">>>> testIntervalosValores");
//SemanticEngineImoveis engImoveis = new SemanticEngineImoveis();
engImoveis.preparaConteudoBusca("cobertura com 2 ou mais dormitorios");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[2:5], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura com 2 ou menos dormitorios");
engImoveis.executeQuery();
assertEquals("{Dormitórios=[1:2], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura a partir de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura acima de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura acima de 300.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[300000:], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura abaixo de R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("cobertura até R$ 300 mil");
engImoveis.executeQuery();
assertEquals("{Preço=[:300000], Tipo de imóvel=[Cobertura]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200m2 e acima de R$ 1milhão");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200m2 e acima de R$ 1.000.000,00");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
engImoveis.preparaConteudoBusca("apartamento até 200 m2 e acima de R$ 1milhão");
engImoveis.executeQuery();
assertEquals("{Preço=[1000000:], Área total=[10:200M2], Tipo de imóvel=[Apartamento]}", engImoveis.getResultsAsString());
assertEquals("{Características=[Churrasqueira], Dormitórios=[1:2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa com churrasqueira com até 2 quartos"));
}
public void testIntervalosValores_01() {
System.out.println(">>>> testIntervalosValores_01");
assertEquals("{Dormitórios=[1:2]}", engImoveis.obtemParametrosAsString("até 2 dormitórios"));
}
public void testIntervalosValores_02() {
System.out.println(">>>> testIntervalosValores_02");
assertEquals("{Dormitórios=[3:5]}", engImoveis.obtemParametrosAsString("com mais de 3 dormitórios"));
}
public void testIntervalosValores_03() {
System.out.println(">>>> testIntervalosValores_03");
assertEquals("{Dormitórios=[1:4]}", engImoveis.obtemParametrosAsString("com menos de 4 dormitórios"));
}
public void testIntervalosValores_04() {
System.out.println(">>>> testIntervalosValores_04");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("de 1 a 3 dormitórios"));
}
public void testIntervalosValores_05() {
System.out.println(">>>> testIntervalosValores_05");
assertEquals("{Dormitórios=[2:4]}", engImoveis.obtemParametrosAsString("de 2 até 4 dormitórios"));
}
public void testIntervalosValores_06() {
System.out.println(">>>> testIntervalosValores_06");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("com 1 e 3 dormitórios"));
}
public void testIntervalosValores_07() {
System.out.println(">>>> testIntervalosValores_07");
assertEquals("{Dormitórios=[2:4]}", engImoveis.obtemParametrosAsString("com 2 ou 4 dormitórios"));
}
public void testIntervalosValores_08() {
System.out.println(">>>> testIntervalosValores_08");
assertEquals("{Dormitórios=[1:3]}", engImoveis.obtemParametrosAsString("com 3 ou menos quartos"));
}
public void testIntervalosValores_09() {
System.out.println(">>>> testIntervalosValores_09");
assertEquals("{Dormitórios=[2:5]}", engImoveis.obtemParametrosAsString("com 2 ou mais quartos"));
}
public void testIntervalosValores_10() {
System.out.println(">>>> testIntervalosValores_10");
assertEquals("{Área total=[13:1000M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa a partir de 13m²"));
}
public void testIntervalosValores_11() {
System.out.println(">>>> testIntervalosValores_11");
assertEquals("{Área total=[13:1000M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de 13m²"));
}
public void testIntervalosValores_12() {
System.out.println(">>>> testIntervalosValores_12");
assertEquals("{Área total=[10:30M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa abaixo de 30m²"));
}
public void testIntervalosValores_13() {
System.out.println(">>>> testIntervalosValores_13");
assertEquals("{Área total=[10:40M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa até 40m²"));
}
public void testIntervalosValores_14() {
System.out.println(">>>> testIntervalosValores_14");
assertEquals("{Área total=[50:50M2], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa de 50m²"));
}
public void testIntervalosValores_15() {
System.out.println(">>>> testIntervalosValores_15");
assertEquals("{Preço=[300000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa a partir de R$ 300mil"));
}
public void testIntervalosValores_16() {
System.out.println(">>>> testIntervalosValores_16");
assertEquals("{Preço=[1000000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de R$ 1milhão"));
}
public void testIntervalosValores_17() {
System.out.println(">>>> testIntervalosValores_17");
assertEquals("{Preço=[1000000:], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa acima de R$ 1milhao"));
}
public void testIntervalosValores_18() {
System.out.println(">>>> testIntervalosValores_18");
assertEquals("{Preço=[:1000000], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa abaixo de R$ 1milhao"));
}
public void testIntervalosValores_19() {
System.out.println(">>>> testIntervalosValores_19");
assertEquals("{Preço=[:2000000], Tipo de imóvel=[Casa]}", engImoveis.obtemParametrosAsString("casa até R$ 2milhao"));
}
}
| 26,323 | 0.677555 | 0.650372 | 452 | 55.703541 | 52.539036 | 222 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.201327 | false | false | 4 |
bba3b87c046b2f4887b87076cd91e55fc17c6ed4 | 8,598,524,572,659 | f31aa472d5dd7fc28580d9e902eda8dcfd19b80d | /src/main/java/com/BoostingWebsite/message/Message.java | 4a1a25fa6e6f02ddb33bedbbd45075b32de93f83 | [] | no_license | KacperSzuba/Boosting-website-Spring-MVC-Data-Security-Hibernate-SQL- | https://github.com/KacperSzuba/Boosting-website-Spring-MVC-Data-Security-Hibernate-SQL- | da8b2dfeb7bbe4718f1e3f624f8060558b6b4ef4 | 1bce61534bf2da373961ddf9df07990655f63bd7 | refs/heads/master | 2020-07-10T04:34:41.999000 | 2020-06-09T17:25:28 | 2020-06-09T17:25:28 | 204,168,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.BoostingWebsite.message;
import com.BoostingWebsite.account.user.User;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@DynamicUpdate
@Table(name = "messages")
public class Message implements Comparable<Message>{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String message;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="message_sender")
private User author;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="recipient_of_the_message")
private User recipient;
private LocalDateTime date;
public Message(){
this.date = LocalDateTime.now();
}
public Message(String message, User author, User recipient) {
this.message = message;
this.author = author;
this.recipient = recipient;
this.date = LocalDateTime.now();
}
public Message(Message copyMessage) {
this.id = copyMessage.id;
this.message = copyMessage.message;
this.author = copyMessage.author;
this.recipient = copyMessage.recipient;
this.date = LocalDateTime.now();
}
public Long getId() {
return id;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public User getRecipient() {
return recipient;
}
public void setRecipient(User recipient) {
this.recipient = recipient;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
LocalDateTime getDate() {
return date;
}
@Override
public int compareTo(Message o) {
return getDate().compareTo(o.getDate());
}
@Override
public String toString() {
return "Message{" +
"id =" + id +
", sendMessage ='" + message + '\'' +
", date =" + date +
'}';
}
}
| UTF-8 | Java | 2,087 | java | Message.java | Java | [] | null | [] | package com.BoostingWebsite.message;
import com.BoostingWebsite.account.user.User;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@DynamicUpdate
@Table(name = "messages")
public class Message implements Comparable<Message>{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String message;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="message_sender")
private User author;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="recipient_of_the_message")
private User recipient;
private LocalDateTime date;
public Message(){
this.date = LocalDateTime.now();
}
public Message(String message, User author, User recipient) {
this.message = message;
this.author = author;
this.recipient = recipient;
this.date = LocalDateTime.now();
}
public Message(Message copyMessage) {
this.id = copyMessage.id;
this.message = copyMessage.message;
this.author = copyMessage.author;
this.recipient = copyMessage.recipient;
this.date = LocalDateTime.now();
}
public Long getId() {
return id;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public User getRecipient() {
return recipient;
}
public void setRecipient(User recipient) {
this.recipient = recipient;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
LocalDateTime getDate() {
return date;
}
@Override
public int compareTo(Message o) {
return getDate().compareTo(o.getDate());
}
@Override
public String toString() {
return "Message{" +
"id =" + id +
", sendMessage ='" + message + '\'' +
", date =" + date +
'}';
}
}
| 2,087 | 0.609487 | 0.609487 | 93 | 21.440861 | 17.593048 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365591 | false | false | 4 |
4b7464f573c09bd43ed7848afe1bf7afbfeae0fe | 8,598,524,570,585 | d2df1a5b28ead7ea2d69ab94025395dee121ed8b | /msm-web-ui/src/main/java/net/paslavsky/msm/client/event/CurrentSongChangedEvent.java | 16eb26ba31777ac5dd3aa028ce78dd96d9b18327 | [
"Apache-2.0"
] | permissive | paslavsky/music-sync-manager | https://github.com/paslavsky/music-sync-manager | 83706cd4aff29f859d684063ab44cbb45e84c916 | 593d83723f1ca9315675114b246b89d7cb65f5dd | refs/heads/master | 2019-04-23T09:29:33.847000 | 2015-06-04T02:23:48 | 2015-06-04T02:23:48 | 17,972,687 | 0 | 1 | null | false | 2015-06-04T02:23:48 | 2014-03-21T08:15:04 | 2015-02-20T14:06:01 | 2015-06-04T02:23:48 | 6,801 | 0 | 0 | 0 | Java | null | null | package net.paslavsky.msm.client.event;
import com.google.web.bindery.event.shared.Event;
import net.paslavsky.msm.client.domain.AudioFile;
/**
* This event notifies that the position has been changed in the playlist
*
* @author Andrey Paslavsky
* @version 1.0
*/
public class CurrentSongChangedEvent extends Event<CurrentSongChangedHandler> {
public static Type<CurrentSongChangedHandler> TYPE = new Type<CurrentSongChangedHandler>();
private final AudioFile current;
public CurrentSongChangedEvent(AudioFile current) {
this.current = current;
}
public AudioFile getCurrent() {
return current;
}
public Type<CurrentSongChangedHandler> getAssociatedType() {
return TYPE;
}
protected void dispatch(CurrentSongChangedHandler handler) {
handler.onCurrentSongChanged(this);
}
}
| UTF-8 | Java | 857 | java | CurrentSongChangedEvent.java | Java | [
{
"context": "ion has been changed in the playlist\n *\n * @author Andrey Paslavsky\n * @version 1.0\n */\npublic class CurrentSongChang",
"end": 250,
"score": 0.9998356699943542,
"start": 234,
"tag": "NAME",
"value": "Andrey Paslavsky"
}
] | null | [] | package net.paslavsky.msm.client.event;
import com.google.web.bindery.event.shared.Event;
import net.paslavsky.msm.client.domain.AudioFile;
/**
* This event notifies that the position has been changed in the playlist
*
* @author <NAME>
* @version 1.0
*/
public class CurrentSongChangedEvent extends Event<CurrentSongChangedHandler> {
public static Type<CurrentSongChangedHandler> TYPE = new Type<CurrentSongChangedHandler>();
private final AudioFile current;
public CurrentSongChangedEvent(AudioFile current) {
this.current = current;
}
public AudioFile getCurrent() {
return current;
}
public Type<CurrentSongChangedHandler> getAssociatedType() {
return TYPE;
}
protected void dispatch(CurrentSongChangedHandler handler) {
handler.onCurrentSongChanged(this);
}
}
| 847 | 0.732789 | 0.730455 | 31 | 26.645161 | 27.511345 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.290323 | false | false | 4 |
d0a7a945eabe105f7fdad579ecdf69373347d497 | 12,704,513,314,882 | 96f8d42c474f8dd42ecc6811b6e555363f168d3e | /zuiyou/sources/cn/xiaochuankeji/aop/permission/PermissionItem.java | fd4638601583b1ed41bbb188c4d5264b91dd8290 | [] | no_license | aheadlcx/analyzeApk | https://github.com/aheadlcx/analyzeApk | 050b261595cecc85790558a02d79739a789ae3a3 | 25cecc394dde4ed7d4971baf0e9504dcb7fabaca | refs/heads/master | 2020-03-10T10:24:49.773000 | 2018-04-13T09:44:45 | 2018-04-13T09:44:45 | 129,332,351 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.xiaochuankeji.aop.permission;
import java.io.Serializable;
public class PermissionItem implements Serializable {
public String deniedButton;
public String deniedMessage;
public boolean needGotoSetting;
public String[] permissions;
public String rationalButton;
public String rationalMessage;
public boolean runIgnorePermission;
public String settingText;
public PermissionItem(String... strArr) {
if (strArr == null || strArr.length <= 0) {
throw new IllegalArgumentException("permissions must have one content at least");
}
this.permissions = strArr;
}
public PermissionItem rationalMessage(String str) {
this.rationalMessage = str;
return this;
}
public PermissionItem rationalButton(String str) {
this.rationalButton = str;
return this;
}
public PermissionItem deniedMessage(String str) {
this.deniedMessage = str;
return this;
}
public PermissionItem deniedButton(String str) {
this.deniedButton = str;
return this;
}
public PermissionItem needGotoSetting(boolean z) {
this.needGotoSetting = z;
return this;
}
public PermissionItem runIgnorePermission(boolean z) {
this.runIgnorePermission = z;
return this;
}
public PermissionItem settingText(String str) {
this.settingText = str;
return this;
}
}
| UTF-8 | Java | 1,468 | java | PermissionItem.java | Java | [] | null | [] | package cn.xiaochuankeji.aop.permission;
import java.io.Serializable;
public class PermissionItem implements Serializable {
public String deniedButton;
public String deniedMessage;
public boolean needGotoSetting;
public String[] permissions;
public String rationalButton;
public String rationalMessage;
public boolean runIgnorePermission;
public String settingText;
public PermissionItem(String... strArr) {
if (strArr == null || strArr.length <= 0) {
throw new IllegalArgumentException("permissions must have one content at least");
}
this.permissions = strArr;
}
public PermissionItem rationalMessage(String str) {
this.rationalMessage = str;
return this;
}
public PermissionItem rationalButton(String str) {
this.rationalButton = str;
return this;
}
public PermissionItem deniedMessage(String str) {
this.deniedMessage = str;
return this;
}
public PermissionItem deniedButton(String str) {
this.deniedButton = str;
return this;
}
public PermissionItem needGotoSetting(boolean z) {
this.needGotoSetting = z;
return this;
}
public PermissionItem runIgnorePermission(boolean z) {
this.runIgnorePermission = z;
return this;
}
public PermissionItem settingText(String str) {
this.settingText = str;
return this;
}
}
| 1,468 | 0.663488 | 0.662807 | 56 | 25.214285 | 20.810123 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
1606b48d092a23ef51fccd03779d3288be6bc73c | 29,901,562,339,254 | c267ea78d09a052d2d7ba78c99f42761d2c8b6ba | /src/main/java/hemoptysisheart/github/com/tutorial/spring/web/controller/RootController.java | d5164bdc9883d6c769f5dc811b37f25dec80248f | [
"Apache-2.0"
] | permissive | hemoptysisheart/tutorial-spring-web | https://github.com/hemoptysisheart/tutorial-spring-web | 6be4f0bd6bf985286affa5671d5cbfb5e8f9e6cb | 84ad1ddb01aabce2a96d20c188a22b75c7c2ef4d | refs/heads/master | 2020-03-18T04:17:06.498000 | 2018-10-31T16:01:34 | 2018-10-31T16:01:34 | 134,279,984 | 1 | 3 | Apache-2.0 | false | 2018-06-12T05:06:06 | 2018-05-21T14:25:07 | 2018-06-08T08:25:27 | 2018-06-12T05:06:05 | 4,576 | 1 | 2 | 0 | Java | false | null | package hemoptysisheart.github.com.tutorial.spring.web.controller;
import hemoptysisheart.github.com.tutorial.spring.web.controller.req.SignUpReq;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
/**
* 루트 페이지를 모아 제공하는 컨트롤러.
* 컨트롤러 인터페이스/클래스는 어떤 URL 그룹에 해당한다.
*
* @author hemoptysisheart
* @since 2018. 5. 31.
*/
@RequestMapping
public interface RootController {
/**
* 브라우저에 {@code /} 도메인만 입력했을 경우의 리퀘스트를 처리하는 컨트롤러 메서드.
*
* @param model HTTP 리퀘스트가 컨트롤러 전달하는 정보. 컨트롤러 로직 실행을 끝내고 뷰 템플릿 엔진에 데이터를 전달할 때도 사용한다.
* @return 루트 페이지의 템플릿 이름.
*/
@GetMapping
String index(Model model);
/**
* 회원 가입 폼을 출력한다.
*
* @param model
* @return 회원가입 폼 템플릿 이름.
*/
@GetMapping("/signup")
String signUpForm(Model model);
/**
* 회원 가입 요청을 처리한 후, 루트 페이지로 리다이렉트한다.
*
* @param signUpReq 회원가입 폼 입력.
* @param binding {@code signUpReq}의 검증 결과.
* @param model
* @return 루트 페이지 리다이렉트 정보.
*/
@PostMapping("/signup")
String signUp(@ModelAttribute("signUpReq") @Valid SignUpReq signUpReq, BindingResult binding, Model model);
} | UTF-8 | Java | 1,830 | java | RootController.java | Java | [
{
"context": "\n * 컨트롤러 인터페이스/클래스는 어떤 URL 그룹에 해당한다.\n *\n * @author hemoptysisheart\n * @since 2018. 5. 31.\n */\n@RequestMapping\npublic",
"end": 610,
"score": 0.9997062683105469,
"start": 595,
"tag": "USERNAME",
"value": "hemoptysisheart"
}
] | null | [] | package hemoptysisheart.github.com.tutorial.spring.web.controller;
import hemoptysisheart.github.com.tutorial.spring.web.controller.req.SignUpReq;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
/**
* 루트 페이지를 모아 제공하는 컨트롤러.
* 컨트롤러 인터페이스/클래스는 어떤 URL 그룹에 해당한다.
*
* @author hemoptysisheart
* @since 2018. 5. 31.
*/
@RequestMapping
public interface RootController {
/**
* 브라우저에 {@code /} 도메인만 입력했을 경우의 리퀘스트를 처리하는 컨트롤러 메서드.
*
* @param model HTTP 리퀘스트가 컨트롤러 전달하는 정보. 컨트롤러 로직 실행을 끝내고 뷰 템플릿 엔진에 데이터를 전달할 때도 사용한다.
* @return 루트 페이지의 템플릿 이름.
*/
@GetMapping
String index(Model model);
/**
* 회원 가입 폼을 출력한다.
*
* @param model
* @return 회원가입 폼 템플릿 이름.
*/
@GetMapping("/signup")
String signUpForm(Model model);
/**
* 회원 가입 요청을 처리한 후, 루트 페이지로 리다이렉트한다.
*
* @param signUpReq 회원가입 폼 입력.
* @param binding {@code signUpReq}의 검증 결과.
* @param model
* @return 루트 페이지 리다이렉트 정보.
*/
@PostMapping("/signup")
String signUp(@ModelAttribute("signUpReq") @Valid SignUpReq signUpReq, BindingResult binding, Model model);
} | 1,830 | 0.689847 | 0.684979 | 50 | 27.780001 | 25.390778 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 4 |
6851fa18c2fe9033140338336d19b0bf840070ba | 12,489,764,921,785 | d5f0b3f726f4c82701b115f5a751bfb83d19288c | /main/java/com/hello/Solution28.java | 793488332395c7498f4f0974bf60e34d4382734c | [] | no_license | NeeWe/Leetcode | https://github.com/NeeWe/Leetcode | 3addedf4d3b427519341afde775ceabaec00635a | 1674810a1e13d3e09a11645827c061e1a19d33b0 | refs/heads/master | 2021-06-29T15:13:13.034000 | 2020-08-10T16:06:20 | 2020-08-10T16:06:20 | 155,074,163 | 0 | 0 | null | false | 2020-10-13T14:33:50 | 2018-10-28T13:29:33 | 2020-08-10T16:06:32 | 2020-10-13T14:33:49 | 17 | 0 | 0 | 1 | Java | false | false | package com.hello;
/**
* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/implement-strstr
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @author Administrator
*/
public class Solution28 {
public static int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0) {
return 0;
}
int hashCode = needle.hashCode();
for(int i = 0; i <= haystack.length() - needle.length(); i ++) {
String s = haystack.substring(i, i + needle.length());
if(s.hashCode() == hashCode) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(strStr("abcd", "abcd"));
}
}
| UTF-8 | Java | 1,027 | java | Solution28.java | Java | [
{
"context": "r\n * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n * @author Administrator\n */\npublic class Solution28 {\n\n public static ",
"end": 258,
"score": 0.5843376517295837,
"start": 245,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package com.hello;
/**
* 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/implement-strstr
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @author Administrator
*/
public class Solution28 {
public static int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0) {
return 0;
}
int hashCode = needle.hashCode();
for(int i = 0; i <= haystack.length() - needle.length(); i ++) {
String s = haystack.substring(i, i + needle.length());
if(s.hashCode() == hashCode) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(strStr("abcd", "abcd"));
}
}
| 1,027 | 0.572781 | 0.563314 | 31 | 26.258064 | 25.004475 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.451613 | false | false | 4 |
8c65df3e0289365268a684c94fd25eec054a0bb5 | 17,927,193,496,086 | a87018d0f086fc4c15f75983912c7504b4ab2546 | /tao-core/src/main/java/soya/framework/tao/KnowledgeBase.java | 3596ef198c3259f95a2089d0e62c190b0c9bce05 | [] | no_license | soyastudio/Nezha | https://github.com/soyastudio/Nezha | 945e73d4a687acd3f4961d1f8ed89e5557c9eed0 | cb1531676c0b009033f0235ef9debda114b083d4 | refs/heads/master | 2022-04-06T02:32:23.835000 | 2021-03-17T21:14:15 | 2021-03-17T21:14:15 | 216,121,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package soya.framework.tao;
/**
* <p>
* 道可道也,非恒道也。名可名也,非恒名也。
* 无名,万物之始也;有名,万物之母也。
* 故恒无欲也,以观其眇;恒有欲也,以观其所徼。两者同出,异名同谓。玄之又玄,众眇之门。
* </p>
* <p>
* T: 宇宙的本原和实质,或事物的客观存在,即无名。
* K: 对宇宙或事物的认知,即有名;认知是可以深化和改变的。
* </p>
*
* @author Wen Qun
*/
public interface KnowledgeBase<T, K extends Annotatable> {
T tao();
K knowledge();
}
| UTF-8 | Java | 593 | java | KnowledgeBase.java | Java | [
{
"context": ": 对宇宙或事物的认知,即有名;认知是可以深化和改变的。\n * </p>\n *\n * @author Wen Qun\n */\npublic interface KnowledgeBase<T, K extends A",
"end": 238,
"score": 0.999787449836731,
"start": 231,
"tag": "NAME",
"value": "Wen Qun"
}
] | null | [] | package soya.framework.tao;
/**
* <p>
* 道可道也,非恒道也。名可名也,非恒名也。
* 无名,万物之始也;有名,万物之母也。
* 故恒无欲也,以观其眇;恒有欲也,以观其所徼。两者同出,异名同谓。玄之又玄,众眇之门。
* </p>
* <p>
* T: 宇宙的本原和实质,或事物的客观存在,即无名。
* K: 对宇宙或事物的认知,即有名;认知是可以深化和改变的。
* </p>
*
* @author <NAME>
*/
public interface KnowledgeBase<T, K extends Annotatable> {
T tao();
K knowledge();
}
| 592 | 0.620178 | 0.620178 | 20 | 15.85 | 15.582923 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 4 |
1b9ad6099e4ac12b862009923de45b84e3d4c98e | 16,956,530,952,100 | 3b09171ccdb2ab8657e96a77179a4df27e92b0c5 | /app/src/main/java/com/kys/knowyourshop/Callbacks/Adscallback.java | 6fdb078e783379b3140763f38c51d23bc3dc655b | [] | no_license | tayorh27/KnowYourShop | https://github.com/tayorh27/KnowYourShop | c8d1838e9d3bb2eb5cb15ea28032b86f0f0d2417 | 333f246bf7653cb427352a985ada782b4e08de9e | refs/heads/master | 2021-01-23T04:14:04.778000 | 2017-06-29T16:41:42 | 2017-06-29T16:41:42 | 86,176,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kys.knowyourshop.Callbacks;
import com.kys.knowyourshop.Information.Ads;
import java.util.ArrayList;
/**
* Created by sanniAdewale on 26/03/2017.
*/
public interface Adscallback {
void onAdsLoaded(ArrayList<Ads> adsArrayList);
}
| UTF-8 | Java | 252 | java | Adscallback.java | Java | [
{
"context": "s;\n\nimport java.util.ArrayList;\n\n/**\n * Created by sanniAdewale on 26/03/2017.\n */\n\npublic interface Adscallback ",
"end": 146,
"score": 0.994750440120697,
"start": 134,
"tag": "USERNAME",
"value": "sanniAdewale"
}
] | null | [] | package com.kys.knowyourshop.Callbacks;
import com.kys.knowyourshop.Information.Ads;
import java.util.ArrayList;
/**
* Created by sanniAdewale on 26/03/2017.
*/
public interface Adscallback {
void onAdsLoaded(ArrayList<Ads> adsArrayList);
}
| 252 | 0.757937 | 0.72619 | 14 | 17 | 19.346466 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 4 |
1a35655d423f58a85318c561e22684f686b9eef3 | 18,004,502,943,282 | c31e8742cf182ade82673a34397d64c57c5f0e9a | /类的练习/HuoChe.java | 7c965498346a0900ffe5adfbcbd239e8d6b4a953 | [] | no_license | 2650973415/Java | https://github.com/2650973415/Java | 81cccd1f407c1ff41c4d6b06a598206f580b9106 | 1de2780db8d36ed0d4a82c595bba208a40565103 | refs/heads/master | 2021-01-20T02:33:45.996000 | 2017-05-25T06:50:26 | 2017-05-25T06:50:26 | 89,425,032 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Student{
String name;//火车名字
int age;//试用年限
int shiSu;
String shiZhongDian;
//构造器
public Student(){
}
//构造器
public Student(String name,int age,char sex){
this.name=name;
this.age=age;
this.sex=sex;
}
//自我介绍
public void shuchu(){
System.out.println("我叫"+name+",性别"+sex+",今年"+age+"岁!");
}
//状态
public void chi(){
System.out.println(name+"在吃饭!");
}
public void wan(){
System.out.println(name+"在玩游戏!");
}
public void yundong(){
System.out.println(name+"在运动!");
}
} | GB18030 | Java | 623 | java | HuoChe.java | Java | [
{
"context": "e;//火车名字\r\n\tint age;//试用年限\r\n\tint shiSu;\r\n\tString shiZhongDian;\r\n\t//构造器\r\n\tpublic Student(){\r\n\t\r\n\t}\r\n\t//",
"end": 85,
"score": 0.5453435182571411,
"start": 84,
"tag": "NAME",
"value": "i"
},
{
"context": "名字\r\n\tint age;//试用年限\r\n\tint shiSu;\r\n\tString shiZhongDian;\r\n\t//构造器\r\n\tpublic Student(){\r\n\t\r\n\t}\r\n\t//构造器\r\n\tpub",
"end": 94,
"score": 0.5476285219192505,
"start": 90,
"tag": "NAME",
"value": "Dian"
}
] | null | [] | public class Student{
String name;//火车名字
int age;//试用年限
int shiSu;
String shiZhongDian;
//构造器
public Student(){
}
//构造器
public Student(String name,int age,char sex){
this.name=name;
this.age=age;
this.sex=sex;
}
//自我介绍
public void shuchu(){
System.out.println("我叫"+name+",性别"+sex+",今年"+age+"岁!");
}
//状态
public void chi(){
System.out.println(name+"在吃饭!");
}
public void wan(){
System.out.println(name+"在玩游戏!");
}
public void yundong(){
System.out.println(name+"在运动!");
}
} | 623 | 0.60149 | 0.60149 | 30 | 15.966666 | 13.91997 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false | 4 |
001a3966e2944d08ef365e0571cf8b0a3c0495dd | 25,786,983,694,983 | 38f28be99132ee8f02307935ef40600562084174 | /JavaPractice/src/ortiz/perez/albin/abstractclass/Common.java | b667519678b559f0dd3ef21cdc1ab6e1bf2c1eba | [] | no_license | apobits/java | https://github.com/apobits/java | 2fe99ee6394a5261900f03bd214d4e28694ddcec | e77e1e91438b5f01b399e25dc293c3aa49408887 | refs/heads/master | 2022-07-23T09:17:02.823000 | 2020-09-08T23:15:12 | 2020-09-08T23:15:12 | 74,909,264 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package ortiz.perez.albin.abstractclass;
/**
* @author Administrador
*
*/
public class Common extends Person {
/*
* (non-Javadoc)
*
* @see ortiz.perez.albin.abstractclass.Person#run()
*/
@Override
public void run() {
System.out.println("Running at 5 km/h");
}
}
| UTF-8 | Java | 296 | java | Common.java | Java | [
{
"context": "e ortiz.perez.albin.abstractclass;\n\n/**\n * @author Administrador\n *\n */\npublic class Common extends Person {\n\n\t/*\n",
"end": 82,
"score": 0.9414056539535522,
"start": 69,
"tag": "NAME",
"value": "Administrador"
}
] | null | [] | /**
*
*/
package ortiz.perez.albin.abstractclass;
/**
* @author Administrador
*
*/
public class Common extends Person {
/*
* (non-Javadoc)
*
* @see ortiz.perez.albin.abstractclass.Person#run()
*/
@Override
public void run() {
System.out.println("Running at 5 km/h");
}
}
| 296 | 0.621622 | 0.618243 | 23 | 11.869565 | 15.726755 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 4 |
afe39948c5d06f3dd288ed5481afb7b922b005ef | 22,840,636,128,117 | 39276429f3a5aac2914a9ab0772c72dde8b404cc | /renren-admin/src/main/java/io/renren/modules/gather/controller/GatherController.java | 7c5451ed09b965a433b2ffcf15e21df3aefe3a73 | [
"Apache-2.0"
] | permissive | liuyuchi1990/renren-security | https://github.com/liuyuchi1990/renren-security | 7a30ea909cc3ee65cad036589bd9c68919ae0c71 | 5af922eec3cd101f4a746f5bc603ad70925d16e3 | refs/heads/master | 2022-07-15T10:13:27.685000 | 2019-10-15T07:10:09 | 2019-10-15T07:10:09 | 154,243,505 | 1 | 0 | Apache-2.0 | false | 2022-07-06T20:29:46 | 2018-10-23T01:42:13 | 2020-06-04T02:21:53 | 2022-07-06T20:29:42 | 8,693 | 1 | 0 | 15 | JavaScript | false | false | package io.renren.modules.gather.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import io.renren.common.utils.QRCodeUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.distribution.entity.Distribution;
import io.renren.modules.distribution.service.DistributionService;
import io.renren.modules.gather.entity.GatherEntity;
import io.renren.modules.gather.entity.PrizeEntity;
import io.renren.modules.gather.service.GatherService;
import io.renren.modules.sys.entity.ReturnCodeEnum;
import io.renren.modules.sys.entity.ReturnResult;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
/**
* @author chenshun
* @email sunlightcs@gmail.com
* @date 2019-06-11 10:39:02
*/
@RestController
@RequestMapping("/gather")
public class GatherController {
@Autowired
private GatherService gatherService;
@Autowired
SysUserService sysUserService;
@Autowired
DistributionService distributionService;
@Value("${qr.gather}")
String qrGatherUrl;
@Value("${qr.gatherImgPath}")
String qrGatherImgUrl;
@Value("${qr.httpgatherurl}")
String httpgatherurl;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = gatherService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") String id) {
GatherEntity gather = gatherService.selectById(id);
return R.ok().put("gather", gather);
}
/**
* 列表
*/
@RequestMapping("/queryAll")
//@RequiresPermissions("sys:distribution:list")
public ReturnResult queryAll(@RequestBody Map<String, Object> params) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
List<Map<String, Object>> activityLst = gatherService.queryList(params);
Map<String, Object> map = new HashedMap();
map.put("data", activityLst);
result.setResult(map);
return result;
}
/**
* 保存
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public R save(@RequestBody GatherEntity gather) throws Exception {
if ("".equals(gather.getId()) || gather.getId() == null) {
gather.setId(UUID.randomUUID().toString().replaceAll("-", ""));
gather.setQrImg(httpgatherurl + gather.getId() + ".jpg");
gather.setCreateTime(new Date());
gather.setPrizeLeft(gather.getPriceNum());
gatherService.insertAllColumn(gather);
distributionService.insertActivity(gather);
String text = qrGatherUrl.replace("id=", "id=" + gather.getId());
QRCodeUtils.encode(text, null, qrGatherImgUrl, gather.getId(), true);
} else {
gather.setUpdateTime(new Date());
gatherService.updateById(gather);//全部更新
distributionService.updateActivity(gather);
}
return R.ok().put("gather", gather);
}
/**
* 保存
*/
@RequestMapping(value = "/copy", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:save")
@ResponseBody
public R copy(@RequestBody GatherEntity gather) throws Exception {
GatherEntity ga = gatherService.selectById(gather.getId());
ga.setId(UUID.randomUUID().toString().replaceAll("-", ""));
ga.setQrImg(httpgatherurl + ga.getId() + ".jpg");
ga.setCreateTime(new Date());
gatherService.insertAllColumn(ga);
distributionService.insertActivity(ga);
String text = qrGatherUrl.replace("id=", "id=" + ga.getId());
QRCodeUtils.encode(text, null, qrGatherImgUrl, ga.getId(), true);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody GatherEntity gather) {
ValidatorUtils.validateEntity(gather);
gatherService.updateById(gather);//全部更新
return R.ok();
}
@RequestMapping(value = "/like", method = RequestMethod.POST)
@Transactional
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult like(@RequestBody PrizeEntity pz) throws ParseException {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
Map<String, Object> pList = gatherService.queryLikeTime(pz);
GatherEntity gz = gatherService.selectById(pz.getActivityId());
long hours = 0;
Long prize_time = Long.parseLong(pList.get("prize_time").toString());
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime toDate = LocalDateTime.now();
String create_time = pList.get("create_time") == null ? null : pList.get("create_time").toString().replace(".0", "");
if (pList.get("create_time") != null) {
LocalDateTime ldt = LocalDateTime.parse(create_time, df);
hours = ChronoUnit.HOURS.between(ldt, toDate);
}
if (create_time == null || gz.getRestrictTime() < hours) {
pz.setUpdateTime(new Date());
gatherService.insertLikeLog(pz);
Map<String, Object> p = gatherService.queryPrizeLog(pz.getId());
int arr = p.get("likes") == null ? 0 : p.get("likes").toString().split(",").length;
if (arr == (gz.getTargetNum()-1)) {
pz.setCompleteTime(new Date());
gatherService.releasePrize(pz.getActivityId());
}
int mp = gatherService.updatePrizeLog(pz);
map.put("data", mp);
} else {
result.setCode(ReturnCodeEnum.INVOKE_VENDOR_DF_ERROR.getCode());
result.setMsg("请超过" + prize_time + "小时后再点赞,谢谢");
}
map.put("status", "success");
map.put("msg", "send ok");
result.setResult(map);
return result;
}
@RequestMapping(value = "/makeLike", method = RequestMethod.POST)
@Transactional
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult makeLike(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
SysUserEntity user = new SysUserEntity();
Map<String, Object> map = new HashedMap();
pz.setId(UUID.randomUUID().toString().replaceAll("-", ""));
int mp = gatherService.insertPrizeLog(pz);
user.setUsername(pz.getUserName());
user.setUserId(pz.getUserId());
user.setMobile(pz.getMobile());
sysUserService.updateUser(user);
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", pz);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryLike", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryLike(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
List<Map<String, Object>> mp = gatherService.queryLike(pz.getActivityId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryLikeLog", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryLikeLog(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
List<Map<String, Object>> mp = gatherService.queryLikeLog(pz.getId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryPrizeLog", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryPrizeLog(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
Map<String, Object> mp = gatherService.queryPrizeLog(pz.getId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
/**
* 删除
*/
@RequestMapping("/delete")
@Transactional
public R delete(@RequestBody String[] ids) {
gatherService.deleteBatchIds(Arrays.asList(ids));
distributionService.deleteActivity(Arrays.asList(ids));
return R.ok();
}
}
| UTF-8 | Java | 9,739 | java | GatherController.java | Java | [
{
"context": "\nimport io.renren.common.utils.R;\n\n\n/**\n * @author chenshun\n * @email sunlightcs@gmail.com\n * @date 2019-06-1",
"end": 1313,
"score": 0.9987771511077881,
"start": 1305,
"tag": "USERNAME",
"value": "chenshun"
},
{
"context": "ommon.utils.R;\n\n\n/**\n * @author chenshun\n * @email sunlightcs@gmail.com\n * @date 2019-06-11 10:39:02\n */\n@RestController\n",
"end": 1344,
"score": 0.9999317526817322,
"start": 1324,
"tag": "EMAIL",
"value": "sunlightcs@gmail.com"
},
{
"context": "vice.insertPrizeLog(pz);\n user.setUsername(pz.getUserName());\n user.setUserId(pz.getUserId());\n ",
"end": 7283,
"score": 0.9926165342330933,
"start": 7269,
"tag": "USERNAME",
"value": "pz.getUserName"
}
] | null | [] | package io.renren.modules.gather.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import io.renren.common.utils.QRCodeUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.distribution.entity.Distribution;
import io.renren.modules.distribution.service.DistributionService;
import io.renren.modules.gather.entity.GatherEntity;
import io.renren.modules.gather.entity.PrizeEntity;
import io.renren.modules.gather.service.GatherService;
import io.renren.modules.sys.entity.ReturnCodeEnum;
import io.renren.modules.sys.entity.ReturnResult;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
/**
* @author chenshun
* @email <EMAIL>
* @date 2019-06-11 10:39:02
*/
@RestController
@RequestMapping("/gather")
public class GatherController {
@Autowired
private GatherService gatherService;
@Autowired
SysUserService sysUserService;
@Autowired
DistributionService distributionService;
@Value("${qr.gather}")
String qrGatherUrl;
@Value("${qr.gatherImgPath}")
String qrGatherImgUrl;
@Value("${qr.httpgatherurl}")
String httpgatherurl;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = gatherService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") String id) {
GatherEntity gather = gatherService.selectById(id);
return R.ok().put("gather", gather);
}
/**
* 列表
*/
@RequestMapping("/queryAll")
//@RequiresPermissions("sys:distribution:list")
public ReturnResult queryAll(@RequestBody Map<String, Object> params) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
List<Map<String, Object>> activityLst = gatherService.queryList(params);
Map<String, Object> map = new HashedMap();
map.put("data", activityLst);
result.setResult(map);
return result;
}
/**
* 保存
*/
@RequestMapping(value = "/save", method = RequestMethod.POST)
public R save(@RequestBody GatherEntity gather) throws Exception {
if ("".equals(gather.getId()) || gather.getId() == null) {
gather.setId(UUID.randomUUID().toString().replaceAll("-", ""));
gather.setQrImg(httpgatherurl + gather.getId() + ".jpg");
gather.setCreateTime(new Date());
gather.setPrizeLeft(gather.getPriceNum());
gatherService.insertAllColumn(gather);
distributionService.insertActivity(gather);
String text = qrGatherUrl.replace("id=", "id=" + gather.getId());
QRCodeUtils.encode(text, null, qrGatherImgUrl, gather.getId(), true);
} else {
gather.setUpdateTime(new Date());
gatherService.updateById(gather);//全部更新
distributionService.updateActivity(gather);
}
return R.ok().put("gather", gather);
}
/**
* 保存
*/
@RequestMapping(value = "/copy", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:save")
@ResponseBody
public R copy(@RequestBody GatherEntity gather) throws Exception {
GatherEntity ga = gatherService.selectById(gather.getId());
ga.setId(UUID.randomUUID().toString().replaceAll("-", ""));
ga.setQrImg(httpgatherurl + ga.getId() + ".jpg");
ga.setCreateTime(new Date());
gatherService.insertAllColumn(ga);
distributionService.insertActivity(ga);
String text = qrGatherUrl.replace("id=", "id=" + ga.getId());
QRCodeUtils.encode(text, null, qrGatherImgUrl, ga.getId(), true);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody GatherEntity gather) {
ValidatorUtils.validateEntity(gather);
gatherService.updateById(gather);//全部更新
return R.ok();
}
@RequestMapping(value = "/like", method = RequestMethod.POST)
@Transactional
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult like(@RequestBody PrizeEntity pz) throws ParseException {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
Map<String, Object> pList = gatherService.queryLikeTime(pz);
GatherEntity gz = gatherService.selectById(pz.getActivityId());
long hours = 0;
Long prize_time = Long.parseLong(pList.get("prize_time").toString());
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime toDate = LocalDateTime.now();
String create_time = pList.get("create_time") == null ? null : pList.get("create_time").toString().replace(".0", "");
if (pList.get("create_time") != null) {
LocalDateTime ldt = LocalDateTime.parse(create_time, df);
hours = ChronoUnit.HOURS.between(ldt, toDate);
}
if (create_time == null || gz.getRestrictTime() < hours) {
pz.setUpdateTime(new Date());
gatherService.insertLikeLog(pz);
Map<String, Object> p = gatherService.queryPrizeLog(pz.getId());
int arr = p.get("likes") == null ? 0 : p.get("likes").toString().split(",").length;
if (arr == (gz.getTargetNum()-1)) {
pz.setCompleteTime(new Date());
gatherService.releasePrize(pz.getActivityId());
}
int mp = gatherService.updatePrizeLog(pz);
map.put("data", mp);
} else {
result.setCode(ReturnCodeEnum.INVOKE_VENDOR_DF_ERROR.getCode());
result.setMsg("请超过" + prize_time + "小时后再点赞,谢谢");
}
map.put("status", "success");
map.put("msg", "send ok");
result.setResult(map);
return result;
}
@RequestMapping(value = "/makeLike", method = RequestMethod.POST)
@Transactional
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult makeLike(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
SysUserEntity user = new SysUserEntity();
Map<String, Object> map = new HashedMap();
pz.setId(UUID.randomUUID().toString().replaceAll("-", ""));
int mp = gatherService.insertPrizeLog(pz);
user.setUsername(pz.getUserName());
user.setUserId(pz.getUserId());
user.setMobile(pz.getMobile());
sysUserService.updateUser(user);
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", pz);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryLike", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryLike(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
List<Map<String, Object>> mp = gatherService.queryLike(pz.getActivityId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryLikeLog", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryLikeLog(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
List<Map<String, Object>> mp = gatherService.queryLikeLog(pz.getId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
@RequestMapping(value = "/queryPrizeLog", method = RequestMethod.POST)
//@RequiresPermissions("sys:distribution:delete")
public ReturnResult queryPrizeLog(@RequestBody PrizeEntity pz) {
ReturnResult result = new ReturnResult(ReturnCodeEnum.SUCCESS.getCode(), ReturnCodeEnum.SUCCESS.getMessage());
Map<String, Object> map = new HashedMap();
Map<String, Object> mp = gatherService.queryPrizeLog(pz.getId());
map.put("status", "success");
map.put("msg", "send ok");
map.put("data", mp);
result.setResult(map);
return result;
}
/**
* 删除
*/
@RequestMapping("/delete")
@Transactional
public R delete(@RequestBody String[] ids) {
gatherService.deleteBatchIds(Arrays.asList(ids));
distributionService.deleteActivity(Arrays.asList(ids));
return R.ok();
}
}
| 9,726 | 0.654741 | 0.65288 | 252 | 37.376984 | 27.77383 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.793651 | false | false | 4 |
6802a27cdfb296c307ba17c9fe16204f5ca0d625 | 23,965,917,560,531 | 4e3f315acf996c85757ccfe4bf223e29eef1295b | /study-micro-services-eureka/src/main/java/com/bage/study/micro/services/eureka/EurekaClientController.java | 057e96d73f4175f41b1b5be8e34d5f49eaa81a74 | [] | no_license | bage2014/study-micro-services | https://github.com/bage2014/study-micro-services | 4cd83acaee5fb201df823b815e110965bbc5ab7e | a5e07266ed164383d3ba93306090f07078f05793 | refs/heads/master | 2022-12-21T23:02:08.808000 | 2022-05-29T05:55:30 | 2022-05-29T05:55:30 | 157,491,000 | 6 | 4 | null | false | 2022-12-16T04:23:32 | 2018-11-14T04:32:18 | 2022-05-17T19:35:55 | 2022-12-16T04:23:29 | 313 | 6 | 4 | 14 | Java | false | false | package com.bage.study.micro.services.eureka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("eurekaClient")
public class EurekaClientController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/clients")
public String client() {
List<String> list = discoveryClient.getServices();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
stringBuilder.append(list.get(i) + ",");
}
System.out.println(stringBuilder.toString());
return stringBuilder.toString();
}
}
| UTF-8 | Java | 894 | java | EurekaClientController.java | Java | [] | null | [] | package com.bage.study.micro.services.eureka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("eurekaClient")
public class EurekaClientController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/clients")
public String client() {
List<String> list = discoveryClient.getServices();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
stringBuilder.append(list.get(i) + ",");
}
System.out.println(stringBuilder.toString());
return stringBuilder.toString();
}
}
| 894 | 0.756152 | 0.755034 | 29 | 28.827587 | 23.145819 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.241379 | false | false | 4 |
2c935a4eea30c3751f84029bf782afc3cfd5090b | 2,241,972,995,371 | dbff764783159dbc747e7a8d7bdadc61a7015b38 | /src/main/java/com/virtusa/travelline/models/Feedback.java | 7503dbdfec1455287113cda1bbc665f18707bcb6 | [] | no_license | Vvarun0/Virtusa_Bus_booking_App | https://github.com/Vvarun0/Virtusa_Bus_booking_App | bc984bcac9d82cc7ab8f4712f8e4c6d0d00cea98 | f832abaf3a988e29cc3aa57b5b6503a7b59d5c5f | refs/heads/master | 2020-08-14T06:25:51.360000 | 2019-10-14T18:58:37 | 2019-10-14T18:58:37 | 215,114,079 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.virtusa.travelline.models;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "Feedback_tbl")
public class Feedback {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Feedback_Id")
private int feedbackId;
@Column(name= "Description", nullable=false)
private String description;
@OneToOne(cascade = CascadeType.MERGE,fetch = FetchType.LAZY)
@JoinColumn(name = "Booking_Id",nullable=false)
private Booking booking;
public int getFeedbackId() {
return feedbackId;
}
public void setFeedbackId(int feedbackId) {
this.feedbackId = feedbackId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Booking getBooking() {
return booking;
}
public void setBooking(Booking booking) {
this.booking = booking;
}
} | UTF-8 | Java | 1,256 | java | Feedback.java | Java | [] | null | [] | package com.virtusa.travelline.models;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "Feedback_tbl")
public class Feedback {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Feedback_Id")
private int feedbackId;
@Column(name= "Description", nullable=false)
private String description;
@OneToOne(cascade = CascadeType.MERGE,fetch = FetchType.LAZY)
@JoinColumn(name = "Booking_Id",nullable=false)
private Booking booking;
public int getFeedbackId() {
return feedbackId;
}
public void setFeedbackId(int feedbackId) {
this.feedbackId = feedbackId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Booking getBooking() {
return booking;
}
public void setBooking(Booking booking) {
this.booking = booking;
}
} | 1,256 | 0.736465 | 0.736465 | 55 | 20.872726 | 17.627514 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 4 |
5ac3f695874586dfb3e9546cd8e8a8bcb72ea52c | 5,523,328,005,635 | 5b7b8dfb71ebc9a82d34793bd84bf9b5d8add1c5 | /meta/src/main/java/org/arend/lib/meta/equation/RingSolver.java | 634290eba1c0f71dfbc95dbf82555d0aeef3e882 | [] | no_license | JetBrains/arend-lib | https://github.com/JetBrains/arend-lib | a9b968d87c7d9e89c9012c6c773a0e7f01175c4f | 145baa4faa58e57ecc34f3d4559d0c4f51e8df8e | refs/heads/master | 2023-08-13T22:44:53.179000 | 2023-07-26T11:35:24 | 2023-07-26T11:35:24 | 35,632,282 | 70 | 21 | null | false | 2023-06-23T10:34:23 | 2015-05-14T19:30:54 | 2023-03-12T18:39:02 | 2023-06-23T10:34:22 | 3,024 | 69 | 23 | 22 | Java | false | false | package org.arend.lib.meta.equation;
import org.arend.ext.concrete.ConcreteFactory;
import org.arend.ext.concrete.expr.ConcreteExpression;
import org.arend.ext.concrete.expr.ConcreteReferenceExpression;
import org.arend.ext.core.context.CoreBinding;
import org.arend.ext.core.definition.CoreClassDefinition;
import org.arend.ext.core.expr.CoreClassCallExpression;
import org.arend.ext.core.expr.CoreFunCallExpression;
import org.arend.ext.core.ops.CMP;
import org.arend.ext.error.ErrorReporter;
import org.arend.ext.typechecking.ExpressionTypechecker;
import org.arend.ext.typechecking.TypedExpression;
import org.arend.lib.context.ContextHelper;
import org.arend.lib.meta.closure.CongruenceClosure;
import org.arend.lib.meta.cong.CongruenceMeta;
import org.arend.lib.meta.equation.datafactory.RingDataFactory;
import org.arend.lib.ring.Monomial;
import org.arend.lib.util.CountingSort;
import org.arend.lib.util.Utils;
import org.arend.lib.util.algorithms.ComMonoidWP;
import org.arend.lib.util.algorithms.groebner.Buchberger;
import org.arend.lib.util.algorithms.idealmem.GroebnerIM;
import org.arend.lib.util.algorithms.polynomials.Poly;
import org.arend.lib.util.algorithms.polynomials.Ring;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
public class RingSolver extends BaseEqualitySolver {
private final boolean isCommutative;
private final TermCompiler termCompiler;
private TermCompiler.CompiledTerm lastCompiled;
private TypedExpression lastTerm;
protected RingSolver(EquationMeta meta, ExpressionTypechecker typechecker, ConcreteFactory factory, ConcreteReferenceExpression refExpr, CoreFunCallExpression equality, TypedExpression instance, CoreClassCallExpression classCall, CoreClassDefinition forcedClass, boolean useHypotheses) {
super(meta, typechecker, factory, refExpr, instance, useHypotheses);
this.equality = equality;
termCompiler = new TermCompiler(classCall, instance, meta.ext, typechecker, refExpr, values, forcedClass);
isCommutative = termCompiler.isLattice || classCall.getDefinition().isSubClassOf(meta.CMonoid) && (forcedClass == null || forcedClass.isSubClassOf(meta.CMonoid));
}
@Override
public TypedExpression finalize(ConcreteExpression result) {
RingDataFactory dataFactory = new RingDataFactory(meta, dataRef, values, factory, instance, termCompiler.isLattice, termCompiler.isRing, isCommutative);
return typechecker.typecheck(dataFactory.wrapWithData(result), null);
}
private void typeToRule(CoreBinding binding, List<Equality> rules) {
if (binding == null) return;
CoreFunCallExpression eq = Utils.toEquality(binding.getTypeExpr(), null, null);
if (eq == null || !typechecker.compare(eq.getDefCallArguments().get(0), getValuesType(), CMP.EQ, refExpr, false, true, false)) return;
TermCompiler.CompiledTerm lhsTerm = termCompiler.compileTerm(eq.getDefCallArguments().get(1));
TermCompiler.CompiledTerm rhsTerm = termCompiler.compileTerm(eq.getDefCallArguments().get(2));
if (isCommutative) {
toCommutativeNF(lhsTerm.nf);
toCommutativeNF(rhsTerm.nf);
}
rules.add(new Equality(factory.ref(binding), lhsTerm, rhsTerm));
}
private void toCommutativeNF(List<Monomial> nf) {
nf.replaceAll(monomial -> new Monomial(monomial.coefficient, CountingSort.sort(monomial.elements)));
}
private ConcreteExpression nfToRingTerm(List<Monomial> nf) {
if (nf.isEmpty()) return factory.ref(meta.zroTerm.getRef());
var monomialTerms = new ArrayList<ConcreteExpression>();
for (Monomial m : nf) {
var isNegative = m.coefficient.signum() == -1;
var mTerm = factory.app(factory.ref(meta.coefTerm.getRef()), true, Collections.singletonList(factory.number(m.coefficient.abs())));
if(isNegative) {
mTerm = factory.app(factory.ref(meta.negativeTerm.getRef()), true, Collections.singletonList(mTerm));
}
for (Integer v : m.elements) {
var varTerm = factory.app(factory.ref(meta.varTerm.getRef()), true, singletonList(factory.number(v)));
mTerm = factory.app(factory.ref(meta.mulTerm.getRef()), true, Arrays.asList(mTerm, varTerm));
}
monomialTerms.add(mTerm);
}
var resTerm = monomialTerms.get(0);
for (int i = 1; i < nf.size(); ++i) {
resTerm = factory.app(factory.ref(meta.addTerm.getRef()), true, Arrays.asList(resTerm, monomialTerms.get(i)));
}
return resTerm;
}
@Override
public ConcreteExpression solve(@Nullable ConcreteExpression hint, @NotNull TypedExpression leftExpr, @NotNull TypedExpression rightExpr, @NotNull ErrorReporter errorReporter) {
TermCompiler.CompiledTerm term1 = lastTerm == leftExpr ? lastCompiled : termCompiler.compileTerm(leftExpr.getExpression());
TermCompiler.CompiledTerm term2 = termCompiler.compileTerm(rightExpr.getExpression());
lastTerm = rightExpr;
lastCompiled = term2;
if (isCommutative) {
toCommutativeNF(term1.nf);
toCommutativeNF(term2.nf);
}
List<Monomial> nf1 = term1.nf;
List<Monomial> nf2 = term2.nf;
if (termCompiler.isLattice) {
removeDuplicates(nf1);
removeDuplicates(nf2);
nf1 = latticeCollapse(nf1);
nf2 = latticeCollapse(nf2);
}
Collections.sort(nf1);
Collections.sort(nf2);
if (isCommutative && useHypotheses) {
var rules = new ArrayList<Equality>();
ContextHelper helper = new ContextHelper(hint);
for (CoreBinding binding : helper.getAllBindings(typechecker)) {
typeToRule(binding, rules);
}
if(!rules.isEmpty()) {
ComRingSolver comSolver = new ComRingSolver();
return comSolver.solve(term1, term2, rules);
}
}
if (!termCompiler.isLattice) {
nf1 = Monomial.collapse(nf1);
nf2 = Monomial.collapse(nf2);
}
if (!nf1.equals(nf2)) {
return null;
}
return factory.appBuilder(factory.ref((termCompiler.isLattice ? meta.latticeTermsEq : (termCompiler.isRing ? (isCommutative ? meta.commRingTermsEq : meta.ringTermsEq) : (isCommutative ? meta.commSemiringTermsEq : meta.ringTermsEq))).getRef()))
.app(factory.ref(dataRef), false)
.app(term1.concrete)
.app(term2.concrete)
.app(factory.ref(meta.ext.prelude.getIdp().getRef()))
.build();
}
private static void removeDuplicates(List<Monomial> list) {
list.replaceAll(monomial -> new Monomial(monomial.coefficient, MonoidSolver.removeDuplicates(monomial.elements)));
}
private static List<Monomial> latticeCollapse(List<Monomial> list) {
List<Monomial> result = new ArrayList<>(list.size());
for (Monomial m : list) {
insert(m, result);
}
return result;
}
private static void insert(Monomial m, List<Monomial> list) {
for (int i = 0; i < list.size(); i++) {
Monomial.ComparisonResult result = m.compare(list.get(i));
if (result != Monomial.ComparisonResult.UNCOMPARABLE) {
if (result == Monomial.ComparisonResult.LESS) {
list.set(i, m);
}
return;
}
}
list.add(m);
}
private static class Equality {
public final ConcreteExpression binding;
public TermCompiler.CompiledTerm lhsTerm;
public TermCompiler.CompiledTerm rhsTerm;
private Equality(ConcreteExpression binding, TermCompiler.CompiledTerm lhsTerm, TermCompiler.CompiledTerm rhsTerm) {
this.binding = binding;
this.lhsTerm = lhsTerm;
this.rhsTerm = rhsTerm;
}
}
private class ComRingSolver {
private Poly<BigInteger> termToPoly(TermCompiler.CompiledTerm term, int numVars) {
var poly = Poly.constant(BigInteger.ZERO, numVars, Ring.Z);
for (Monomial m : term.nf) {
poly = poly.add(new org.arend.lib.util.algorithms.polynomials.Monomial<>(m.coefficient, ComMonoidWP.elemsSeqToPowersSeq(m.elements, numVars), Ring.Z));
}
return poly;
}
private List<Monomial> polyToNF(Poly<BigInteger> poly) {
var nf = poly.monomials.stream().map(m -> new Monomial(m.coefficient, ComMonoidWP.powersSeqToElemsSeq(m.degreeVector))).collect(Collectors.toList());
if (nf.size() > 1 && nf.get(0).elements.isEmpty() && nf.get(0).coefficient.equals(BigInteger.ZERO)) {
nf.remove(0);
}
return nf;
}
private ConcreteExpression idealGenDecompRingTerm(List<Poly<BigInteger>> coeffs, List<ConcreteExpression> axiomsRT) {
var summands = new ArrayList<ConcreteExpression>();
for (int i = 0; i < coeffs.size(); ++i) {
var coeffTerm = nfToRingTerm(polyToNF(coeffs.get(i)));
coeffTerm = factory.app(factory.ref(meta.mulTerm.getRef()), true, Arrays.asList(coeffTerm, axiomsRT.get(i)));
summands.add(coeffTerm);
}
ConcreteExpression resTerm = factory.ref(meta.zroTerm.getRef());
for (int i = summands.size() - 1; i >= 0; --i) {
resTerm = factory.app(factory.ref(meta.addTerm.getRef()), true, Arrays.asList(summands.get(i), resTerm));
}
return resTerm;
}
private ConcreteExpression argIsZeroToProdIsZero(ConcreteExpression a, ConcreteExpression bEqZeroPrf) {
var prodCongProof = CongruenceMeta.applyCongruence(typechecker,
Arrays.asList(new CongruenceClosure.EqProofOrElement(factory.ref(meta.mul.getRef()), true),
new CongruenceClosure.EqProofOrElement(a, true),
new CongruenceClosure.EqProofOrElement(bEqZeroPrf, false)), factory, meta.ext.prelude);
var aMulZeroIsZeroProof = factory.appBuilder(factory.ref(meta.zeroMulRight.getRef()))
.app(factory.core(instance), false)
.app(a, false)
.build();
return factory.app(factory.ref(meta.ext.concat.getRef()), true, Arrays.asList(prodCongProof, aMulZeroIsZeroProof));
}
private ConcreteExpression argsAreZeroToSumIsZero(ConcreteExpression aEqZeroPrf, ConcreteExpression bEqZeroPrf) {
var sumCongProof = CongruenceMeta.applyCongruence(typechecker,
Arrays.asList(new CongruenceClosure.EqProofOrElement(factory.ref(meta.plus.getRef()), true),
new CongruenceClosure.EqProofOrElement(aEqZeroPrf, false),
new CongruenceClosure.EqProofOrElement(bEqZeroPrf, false)), factory, meta.ext.prelude);
var zeroPlusZeroIsZeroProof = factory.appBuilder(factory.ref(meta.addMonZroRight.getRef()))
.app(factory.core(instance), false)
.app(factory.ref(meta.ext.zro.getRef()), false)
.build();
return factory.app(factory.ref(meta.ext.concat.getRef()), true, Arrays.asList(sumCongProof, zeroPlusZeroIsZeroProof));
}
// todo: implement as lemma in Arend
private ConcreteExpression idealGenDecompEqZero(List<Poly<BigInteger>> coeffs, List<ConcreteExpression> axEqZeroProofs) {
var summandProofs = new ArrayList<ConcreteExpression>();
for (int i = 0; i < coeffs.size(); ++i) {
var coeffTerm = nfToRingTerm(polyToNF(coeffs.get(i)));
coeffTerm = factory.appBuilder(factory.ref(meta.ringInterpret.getRef()))
.app(factory.ref(dataRef), false)
.app(coeffTerm).build();
summandProofs.add(argIsZeroToProdIsZero(coeffTerm, axEqZeroProofs.get(i)));
}
var resProof = summandProofs.get(0);
for (int i = 1; i < summandProofs.size(); ++i) {
resProof = argsAreZeroToSumIsZero(resProof, summandProofs.get(i));
}
return resProof;
}
private int numVarsInNF(List<Monomial> nf) {
if (nf.isEmpty()) return 0;
return Collections.max(nf.stream().map(m -> m.elements.isEmpty() ? 0 : Collections.max(m.elements)).toList()) + 1;
}
private ConcreteExpression minusRingTerm(ConcreteExpression a, ConcreteExpression b) {
return factory.appBuilder(factory.ref(meta.addTerm.getRef()))
.app(a, true)
.app(factory.app(factory.ref(meta.negativeTerm.getRef()), true, Collections.singletonList(b)), true)
.build();
}
private ConcreteExpression minusRingElement(ConcreteExpression a, ConcreteExpression b) {
return factory.appBuilder(factory.ref(meta.plus.getRef()))
.app(a, true)
.app(factory.app(factory.ref(meta.negative.getRef()), true, Collections.singletonList(b)), true)
.build();
}
public ConcreteExpression solve(TermCompiler.CompiledTerm term1, TermCompiler.CompiledTerm term2, List<Equality> axioms) {
int numVariables = Integer.max(numVarsInNF(term1.nf), numVarsInNF(term2.nf));
for (Equality axiom : axioms) {
numVariables = Integer.max(numVarsInNF(axiom.lhsTerm.nf), numVariables);
numVariables = Integer.max(numVarsInNF(axiom.rhsTerm.nf), numVariables);
}
var p = termToPoly(term1, numVariables).subtr(termToPoly(term2, numVariables));
var idealGen = new ArrayList<Poly<BigInteger>>();
for (Equality axiom : axioms) {
idealGen.add(termToPoly(axiom.lhsTerm, numVariables).subtr(termToPoly(axiom.rhsTerm, numVariables)));
}
var idealCoeffs = new GroebnerIM(new Buchberger()).computeGenDecomposition(p, idealGen);
if (idealCoeffs == null) {
return null;
}
var genCoeffs = new ArrayList<ConcreteExpression>();
var axiomDiffs = new ArrayList<ConcreteExpression>();
for (int i = 0;i < axioms.size(); ++i) {
var axiom = axioms.get(i);
var axiomDiff = minusRingElement(axiom.lhsTerm.originalExpr, axiom.rhsTerm.originalExpr);
var axDiffIsZero = factory.appBuilder(factory.ref(meta.toZero.getRef()))
.app(factory.core(instance), false)
.app(axiom.lhsTerm.originalExpr, false)
.app(axiom.rhsTerm.originalExpr, false)
.app(axiom.binding)
.build();
var coeffTerm = nfToRingTerm(polyToNF(idealCoeffs.get(i)));
coeffTerm = factory.appBuilder(factory.ref(meta.ringInterpret.getRef()))
.app(factory.ref(dataRef), false)
.app(coeffTerm).build();
axiomDiffs.add(minusRingTerm(axiom.lhsTerm.concrete, axiom.rhsTerm.concrete));
genCoeffs.add(factory.tuple(coeffTerm, axiomDiff, axDiffIsZero));
}
/*
var axDiffIsZeroPrf = new ArrayList<ConcreteExpression>();
for (Equality axiom : axioms) {
axiomDiffs.add(minusRingTerm(axiom.lhsTerm.concrete, axiom.rhsTerm.concrete));
axDiffIsZeroPrf.add(factory.appBuilder(factory.ref(meta.toZero.getRef()))
.app(factory.core(instance), false)
.app(axiom.lhsTerm.originalExpr)
.app(axiom.rhsTerm.originalExpr)
.app(axiom.binding)
.build());
}
*/
// term1 - term2 = sum_i idealCoeffs(i) * (axiom(i).L - axiom(i).R)
var decompositionProof = factory.appBuilder(factory.ref(meta.commRingTermsEq.getRef()))
.app(factory.ref(dataRef), false)
.app(minusRingTerm(term1.concrete, term2.concrete))
.app(idealGenDecompRingTerm(idealCoeffs, axiomDiffs))
.app(factory.ref(meta.ext.prelude.getIdp().getRef()))
.build();
/*
// term1 - term2 = 0
var isZeroProof = factory.appBuilder(factory.ref(meta.ext.concat.getRef()))
.app(decompositionProof)
.app(idealGenDecompEqZero(idealCoeffs, axDiffIsZeroPrf))
.build();
*/
// sum_i idealCoeffs(i) * (axiom(i).L - axiom(i).R) = 0
var idealGenDecompEqZero = factory.appBuilder(factory.ref(meta.gensZeroToIdealZero.getRef()))
.app(MonoidSolver.formList(genCoeffs, factory, meta.ext.nil, meta.ext.cons))
.build();
// term1 - term2 = 0
var isZeroProof = factory.appBuilder(factory.ref(meta.ext.concat.getRef()))
.app(decompositionProof)
.app(idealGenDecompEqZero)
.build();
return factory.appBuilder(factory.ref(meta.fromZero.getRef()))
.app(factory.core(instance), false)
.app(term1.originalExpr, false)
.app(term2.originalExpr, false)
.app(isZeroProof)
.build();
}
}
}
| UTF-8 | Java | 16,063 | java | RingSolver.java | Java | [] | null | [] | package org.arend.lib.meta.equation;
import org.arend.ext.concrete.ConcreteFactory;
import org.arend.ext.concrete.expr.ConcreteExpression;
import org.arend.ext.concrete.expr.ConcreteReferenceExpression;
import org.arend.ext.core.context.CoreBinding;
import org.arend.ext.core.definition.CoreClassDefinition;
import org.arend.ext.core.expr.CoreClassCallExpression;
import org.arend.ext.core.expr.CoreFunCallExpression;
import org.arend.ext.core.ops.CMP;
import org.arend.ext.error.ErrorReporter;
import org.arend.ext.typechecking.ExpressionTypechecker;
import org.arend.ext.typechecking.TypedExpression;
import org.arend.lib.context.ContextHelper;
import org.arend.lib.meta.closure.CongruenceClosure;
import org.arend.lib.meta.cong.CongruenceMeta;
import org.arend.lib.meta.equation.datafactory.RingDataFactory;
import org.arend.lib.ring.Monomial;
import org.arend.lib.util.CountingSort;
import org.arend.lib.util.Utils;
import org.arend.lib.util.algorithms.ComMonoidWP;
import org.arend.lib.util.algorithms.groebner.Buchberger;
import org.arend.lib.util.algorithms.idealmem.GroebnerIM;
import org.arend.lib.util.algorithms.polynomials.Poly;
import org.arend.lib.util.algorithms.polynomials.Ring;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
public class RingSolver extends BaseEqualitySolver {
private final boolean isCommutative;
private final TermCompiler termCompiler;
private TermCompiler.CompiledTerm lastCompiled;
private TypedExpression lastTerm;
protected RingSolver(EquationMeta meta, ExpressionTypechecker typechecker, ConcreteFactory factory, ConcreteReferenceExpression refExpr, CoreFunCallExpression equality, TypedExpression instance, CoreClassCallExpression classCall, CoreClassDefinition forcedClass, boolean useHypotheses) {
super(meta, typechecker, factory, refExpr, instance, useHypotheses);
this.equality = equality;
termCompiler = new TermCompiler(classCall, instance, meta.ext, typechecker, refExpr, values, forcedClass);
isCommutative = termCompiler.isLattice || classCall.getDefinition().isSubClassOf(meta.CMonoid) && (forcedClass == null || forcedClass.isSubClassOf(meta.CMonoid));
}
@Override
public TypedExpression finalize(ConcreteExpression result) {
RingDataFactory dataFactory = new RingDataFactory(meta, dataRef, values, factory, instance, termCompiler.isLattice, termCompiler.isRing, isCommutative);
return typechecker.typecheck(dataFactory.wrapWithData(result), null);
}
private void typeToRule(CoreBinding binding, List<Equality> rules) {
if (binding == null) return;
CoreFunCallExpression eq = Utils.toEquality(binding.getTypeExpr(), null, null);
if (eq == null || !typechecker.compare(eq.getDefCallArguments().get(0), getValuesType(), CMP.EQ, refExpr, false, true, false)) return;
TermCompiler.CompiledTerm lhsTerm = termCompiler.compileTerm(eq.getDefCallArguments().get(1));
TermCompiler.CompiledTerm rhsTerm = termCompiler.compileTerm(eq.getDefCallArguments().get(2));
if (isCommutative) {
toCommutativeNF(lhsTerm.nf);
toCommutativeNF(rhsTerm.nf);
}
rules.add(new Equality(factory.ref(binding), lhsTerm, rhsTerm));
}
private void toCommutativeNF(List<Monomial> nf) {
nf.replaceAll(monomial -> new Monomial(monomial.coefficient, CountingSort.sort(monomial.elements)));
}
private ConcreteExpression nfToRingTerm(List<Monomial> nf) {
if (nf.isEmpty()) return factory.ref(meta.zroTerm.getRef());
var monomialTerms = new ArrayList<ConcreteExpression>();
for (Monomial m : nf) {
var isNegative = m.coefficient.signum() == -1;
var mTerm = factory.app(factory.ref(meta.coefTerm.getRef()), true, Collections.singletonList(factory.number(m.coefficient.abs())));
if(isNegative) {
mTerm = factory.app(factory.ref(meta.negativeTerm.getRef()), true, Collections.singletonList(mTerm));
}
for (Integer v : m.elements) {
var varTerm = factory.app(factory.ref(meta.varTerm.getRef()), true, singletonList(factory.number(v)));
mTerm = factory.app(factory.ref(meta.mulTerm.getRef()), true, Arrays.asList(mTerm, varTerm));
}
monomialTerms.add(mTerm);
}
var resTerm = monomialTerms.get(0);
for (int i = 1; i < nf.size(); ++i) {
resTerm = factory.app(factory.ref(meta.addTerm.getRef()), true, Arrays.asList(resTerm, monomialTerms.get(i)));
}
return resTerm;
}
@Override
public ConcreteExpression solve(@Nullable ConcreteExpression hint, @NotNull TypedExpression leftExpr, @NotNull TypedExpression rightExpr, @NotNull ErrorReporter errorReporter) {
TermCompiler.CompiledTerm term1 = lastTerm == leftExpr ? lastCompiled : termCompiler.compileTerm(leftExpr.getExpression());
TermCompiler.CompiledTerm term2 = termCompiler.compileTerm(rightExpr.getExpression());
lastTerm = rightExpr;
lastCompiled = term2;
if (isCommutative) {
toCommutativeNF(term1.nf);
toCommutativeNF(term2.nf);
}
List<Monomial> nf1 = term1.nf;
List<Monomial> nf2 = term2.nf;
if (termCompiler.isLattice) {
removeDuplicates(nf1);
removeDuplicates(nf2);
nf1 = latticeCollapse(nf1);
nf2 = latticeCollapse(nf2);
}
Collections.sort(nf1);
Collections.sort(nf2);
if (isCommutative && useHypotheses) {
var rules = new ArrayList<Equality>();
ContextHelper helper = new ContextHelper(hint);
for (CoreBinding binding : helper.getAllBindings(typechecker)) {
typeToRule(binding, rules);
}
if(!rules.isEmpty()) {
ComRingSolver comSolver = new ComRingSolver();
return comSolver.solve(term1, term2, rules);
}
}
if (!termCompiler.isLattice) {
nf1 = Monomial.collapse(nf1);
nf2 = Monomial.collapse(nf2);
}
if (!nf1.equals(nf2)) {
return null;
}
return factory.appBuilder(factory.ref((termCompiler.isLattice ? meta.latticeTermsEq : (termCompiler.isRing ? (isCommutative ? meta.commRingTermsEq : meta.ringTermsEq) : (isCommutative ? meta.commSemiringTermsEq : meta.ringTermsEq))).getRef()))
.app(factory.ref(dataRef), false)
.app(term1.concrete)
.app(term2.concrete)
.app(factory.ref(meta.ext.prelude.getIdp().getRef()))
.build();
}
private static void removeDuplicates(List<Monomial> list) {
list.replaceAll(monomial -> new Monomial(monomial.coefficient, MonoidSolver.removeDuplicates(monomial.elements)));
}
private static List<Monomial> latticeCollapse(List<Monomial> list) {
List<Monomial> result = new ArrayList<>(list.size());
for (Monomial m : list) {
insert(m, result);
}
return result;
}
private static void insert(Monomial m, List<Monomial> list) {
for (int i = 0; i < list.size(); i++) {
Monomial.ComparisonResult result = m.compare(list.get(i));
if (result != Monomial.ComparisonResult.UNCOMPARABLE) {
if (result == Monomial.ComparisonResult.LESS) {
list.set(i, m);
}
return;
}
}
list.add(m);
}
private static class Equality {
public final ConcreteExpression binding;
public TermCompiler.CompiledTerm lhsTerm;
public TermCompiler.CompiledTerm rhsTerm;
private Equality(ConcreteExpression binding, TermCompiler.CompiledTerm lhsTerm, TermCompiler.CompiledTerm rhsTerm) {
this.binding = binding;
this.lhsTerm = lhsTerm;
this.rhsTerm = rhsTerm;
}
}
private class ComRingSolver {
private Poly<BigInteger> termToPoly(TermCompiler.CompiledTerm term, int numVars) {
var poly = Poly.constant(BigInteger.ZERO, numVars, Ring.Z);
for (Monomial m : term.nf) {
poly = poly.add(new org.arend.lib.util.algorithms.polynomials.Monomial<>(m.coefficient, ComMonoidWP.elemsSeqToPowersSeq(m.elements, numVars), Ring.Z));
}
return poly;
}
private List<Monomial> polyToNF(Poly<BigInteger> poly) {
var nf = poly.monomials.stream().map(m -> new Monomial(m.coefficient, ComMonoidWP.powersSeqToElemsSeq(m.degreeVector))).collect(Collectors.toList());
if (nf.size() > 1 && nf.get(0).elements.isEmpty() && nf.get(0).coefficient.equals(BigInteger.ZERO)) {
nf.remove(0);
}
return nf;
}
private ConcreteExpression idealGenDecompRingTerm(List<Poly<BigInteger>> coeffs, List<ConcreteExpression> axiomsRT) {
var summands = new ArrayList<ConcreteExpression>();
for (int i = 0; i < coeffs.size(); ++i) {
var coeffTerm = nfToRingTerm(polyToNF(coeffs.get(i)));
coeffTerm = factory.app(factory.ref(meta.mulTerm.getRef()), true, Arrays.asList(coeffTerm, axiomsRT.get(i)));
summands.add(coeffTerm);
}
ConcreteExpression resTerm = factory.ref(meta.zroTerm.getRef());
for (int i = summands.size() - 1; i >= 0; --i) {
resTerm = factory.app(factory.ref(meta.addTerm.getRef()), true, Arrays.asList(summands.get(i), resTerm));
}
return resTerm;
}
private ConcreteExpression argIsZeroToProdIsZero(ConcreteExpression a, ConcreteExpression bEqZeroPrf) {
var prodCongProof = CongruenceMeta.applyCongruence(typechecker,
Arrays.asList(new CongruenceClosure.EqProofOrElement(factory.ref(meta.mul.getRef()), true),
new CongruenceClosure.EqProofOrElement(a, true),
new CongruenceClosure.EqProofOrElement(bEqZeroPrf, false)), factory, meta.ext.prelude);
var aMulZeroIsZeroProof = factory.appBuilder(factory.ref(meta.zeroMulRight.getRef()))
.app(factory.core(instance), false)
.app(a, false)
.build();
return factory.app(factory.ref(meta.ext.concat.getRef()), true, Arrays.asList(prodCongProof, aMulZeroIsZeroProof));
}
private ConcreteExpression argsAreZeroToSumIsZero(ConcreteExpression aEqZeroPrf, ConcreteExpression bEqZeroPrf) {
var sumCongProof = CongruenceMeta.applyCongruence(typechecker,
Arrays.asList(new CongruenceClosure.EqProofOrElement(factory.ref(meta.plus.getRef()), true),
new CongruenceClosure.EqProofOrElement(aEqZeroPrf, false),
new CongruenceClosure.EqProofOrElement(bEqZeroPrf, false)), factory, meta.ext.prelude);
var zeroPlusZeroIsZeroProof = factory.appBuilder(factory.ref(meta.addMonZroRight.getRef()))
.app(factory.core(instance), false)
.app(factory.ref(meta.ext.zro.getRef()), false)
.build();
return factory.app(factory.ref(meta.ext.concat.getRef()), true, Arrays.asList(sumCongProof, zeroPlusZeroIsZeroProof));
}
// todo: implement as lemma in Arend
private ConcreteExpression idealGenDecompEqZero(List<Poly<BigInteger>> coeffs, List<ConcreteExpression> axEqZeroProofs) {
var summandProofs = new ArrayList<ConcreteExpression>();
for (int i = 0; i < coeffs.size(); ++i) {
var coeffTerm = nfToRingTerm(polyToNF(coeffs.get(i)));
coeffTerm = factory.appBuilder(factory.ref(meta.ringInterpret.getRef()))
.app(factory.ref(dataRef), false)
.app(coeffTerm).build();
summandProofs.add(argIsZeroToProdIsZero(coeffTerm, axEqZeroProofs.get(i)));
}
var resProof = summandProofs.get(0);
for (int i = 1; i < summandProofs.size(); ++i) {
resProof = argsAreZeroToSumIsZero(resProof, summandProofs.get(i));
}
return resProof;
}
private int numVarsInNF(List<Monomial> nf) {
if (nf.isEmpty()) return 0;
return Collections.max(nf.stream().map(m -> m.elements.isEmpty() ? 0 : Collections.max(m.elements)).toList()) + 1;
}
private ConcreteExpression minusRingTerm(ConcreteExpression a, ConcreteExpression b) {
return factory.appBuilder(factory.ref(meta.addTerm.getRef()))
.app(a, true)
.app(factory.app(factory.ref(meta.negativeTerm.getRef()), true, Collections.singletonList(b)), true)
.build();
}
private ConcreteExpression minusRingElement(ConcreteExpression a, ConcreteExpression b) {
return factory.appBuilder(factory.ref(meta.plus.getRef()))
.app(a, true)
.app(factory.app(factory.ref(meta.negative.getRef()), true, Collections.singletonList(b)), true)
.build();
}
public ConcreteExpression solve(TermCompiler.CompiledTerm term1, TermCompiler.CompiledTerm term2, List<Equality> axioms) {
int numVariables = Integer.max(numVarsInNF(term1.nf), numVarsInNF(term2.nf));
for (Equality axiom : axioms) {
numVariables = Integer.max(numVarsInNF(axiom.lhsTerm.nf), numVariables);
numVariables = Integer.max(numVarsInNF(axiom.rhsTerm.nf), numVariables);
}
var p = termToPoly(term1, numVariables).subtr(termToPoly(term2, numVariables));
var idealGen = new ArrayList<Poly<BigInteger>>();
for (Equality axiom : axioms) {
idealGen.add(termToPoly(axiom.lhsTerm, numVariables).subtr(termToPoly(axiom.rhsTerm, numVariables)));
}
var idealCoeffs = new GroebnerIM(new Buchberger()).computeGenDecomposition(p, idealGen);
if (idealCoeffs == null) {
return null;
}
var genCoeffs = new ArrayList<ConcreteExpression>();
var axiomDiffs = new ArrayList<ConcreteExpression>();
for (int i = 0;i < axioms.size(); ++i) {
var axiom = axioms.get(i);
var axiomDiff = minusRingElement(axiom.lhsTerm.originalExpr, axiom.rhsTerm.originalExpr);
var axDiffIsZero = factory.appBuilder(factory.ref(meta.toZero.getRef()))
.app(factory.core(instance), false)
.app(axiom.lhsTerm.originalExpr, false)
.app(axiom.rhsTerm.originalExpr, false)
.app(axiom.binding)
.build();
var coeffTerm = nfToRingTerm(polyToNF(idealCoeffs.get(i)));
coeffTerm = factory.appBuilder(factory.ref(meta.ringInterpret.getRef()))
.app(factory.ref(dataRef), false)
.app(coeffTerm).build();
axiomDiffs.add(minusRingTerm(axiom.lhsTerm.concrete, axiom.rhsTerm.concrete));
genCoeffs.add(factory.tuple(coeffTerm, axiomDiff, axDiffIsZero));
}
/*
var axDiffIsZeroPrf = new ArrayList<ConcreteExpression>();
for (Equality axiom : axioms) {
axiomDiffs.add(minusRingTerm(axiom.lhsTerm.concrete, axiom.rhsTerm.concrete));
axDiffIsZeroPrf.add(factory.appBuilder(factory.ref(meta.toZero.getRef()))
.app(factory.core(instance), false)
.app(axiom.lhsTerm.originalExpr)
.app(axiom.rhsTerm.originalExpr)
.app(axiom.binding)
.build());
}
*/
// term1 - term2 = sum_i idealCoeffs(i) * (axiom(i).L - axiom(i).R)
var decompositionProof = factory.appBuilder(factory.ref(meta.commRingTermsEq.getRef()))
.app(factory.ref(dataRef), false)
.app(minusRingTerm(term1.concrete, term2.concrete))
.app(idealGenDecompRingTerm(idealCoeffs, axiomDiffs))
.app(factory.ref(meta.ext.prelude.getIdp().getRef()))
.build();
/*
// term1 - term2 = 0
var isZeroProof = factory.appBuilder(factory.ref(meta.ext.concat.getRef()))
.app(decompositionProof)
.app(idealGenDecompEqZero(idealCoeffs, axDiffIsZeroPrf))
.build();
*/
// sum_i idealCoeffs(i) * (axiom(i).L - axiom(i).R) = 0
var idealGenDecompEqZero = factory.appBuilder(factory.ref(meta.gensZeroToIdealZero.getRef()))
.app(MonoidSolver.formList(genCoeffs, factory, meta.ext.nil, meta.ext.cons))
.build();
// term1 - term2 = 0
var isZeroProof = factory.appBuilder(factory.ref(meta.ext.concat.getRef()))
.app(decompositionProof)
.app(idealGenDecompEqZero)
.build();
return factory.appBuilder(factory.ref(meta.fromZero.getRef()))
.app(factory.core(instance), false)
.app(term1.originalExpr, false)
.app(term2.originalExpr, false)
.app(isZeroProof)
.build();
}
}
}
| 16,063 | 0.696819 | 0.692648 | 370 | 42.413513 | 40.401558 | 289 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.87027 | false | false | 4 |
a30ddda2b1d30e2ab0c03ed39008e8ea6aa9e4e3 | 21,303,037,852,274 | 02405c6e15951f148bf7907bf03b2f5e92371c80 | /FINsim/src/com/sim/iso8583/mastercard/MastercardProcessor.java | 247d02a336799d3c8d4ccc79ebefc77834400aed | [] | no_license | gml81/finsim2 | https://github.com/gml81/finsim2 | 300e1adb28fe2855f3e2f2c147fd9d9b8a1ac7a8 | 8433c080c33de1493ef4cff396bb41b364bf764e | refs/heads/master | 2020-05-09T16:27:39.198000 | 2019-04-16T13:10:18 | 2019-04-16T13:10:18 | 181,271,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sim.iso8583.mastercard;
import com.sim.device.DeviceConfigInterface;
import com.sim.iso8583.IsoProcessor;
import com.sim.transactions.TransactionInterface;
public class MastercardProcessor extends IsoProcessor
{
public MastercardProcessor(DeviceConfigInterface d)
{
// TODO Auto-generated constructor stub
}
@Override
public TransactionInterface newMessage()
{
return new MastercardMessage();
}
}
| UTF-8 | Java | 447 | java | MastercardProcessor.java | Java | [] | null | [] | package com.sim.iso8583.mastercard;
import com.sim.device.DeviceConfigInterface;
import com.sim.iso8583.IsoProcessor;
import com.sim.transactions.TransactionInterface;
public class MastercardProcessor extends IsoProcessor
{
public MastercardProcessor(DeviceConfigInterface d)
{
// TODO Auto-generated constructor stub
}
@Override
public TransactionInterface newMessage()
{
return new MastercardMessage();
}
}
| 447 | 0.765101 | 0.747204 | 21 | 19.285715 | 20.851271 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 4 |
dd7087ab065db7e527191f1d634fa04536cf6885 | 2,714,419,339,199 | 8095e6f0d20907b212d2e19b6d6dd6b8d1cedab5 | /app/src/main/java/com/example/oskar/yatzy_oskar_sammalisto/Human_Player.java | 58d0b5eda2d2fe7038318d602cbc94a8d7e0349f | [] | no_license | OskarSammalisto/Yatzy_Oskar_Sammalisto | https://github.com/OskarSammalisto/Yatzy_Oskar_Sammalisto | 391a7a2aac4d2debb2597481f47b87bf6db654d6 | 94bc4a0bc0665541f1de037ad9917c84210faa41 | refs/heads/master | 2020-04-17T04:37:36.854000 | 2019-01-24T12:39:05 | 2019-01-24T12:39:05 | 166,237,855 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.oskar.yatzy_oskar_sammalisto;
public class Human_Player {
private String name;
private int score;
private int avatar;
private int[] scoreArray = new int[16]; //maybe better to make the array in the Human_Player method?
Human_Player(String name, int avatar){
this.name = name;
this.avatar = avatar;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public int getAvatar() {
return avatar;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
}
| UTF-8 | Java | 762 | java | Human_Player.java | Java | [] | null | [] | package com.example.oskar.yatzy_oskar_sammalisto;
public class Human_Player {
private String name;
private int score;
private int avatar;
private int[] scoreArray = new int[16]; //maybe better to make the array in the Human_Player method?
Human_Player(String name, int avatar){
this.name = name;
this.avatar = avatar;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public int getAvatar() {
return avatar;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void setAvatar(int avatar) {
this.avatar = avatar;
}
}
| 762 | 0.597113 | 0.594488 | 39 | 18.538462 | 20.093176 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false | 4 |
3da39763cab7f0eda530db56992dcaff7f1634c2 | 13,829,794,755,751 | 7bdaa6fdaa1dfa062b88ec93f821b9d4869e49bd | /src/main/java/ir/apk/dm/ui/user/NavigationBean.java | 6554a72b8c1ecd62f8469cc03529091cdb54bf4b | [] | no_license | shahinebadi/newdigimarket | https://github.com/shahinebadi/newdigimarket | 9ea6e467363d2cd5e5b3c580e043117c6a83c76a | ffbced92994f90a99983b0b96d45befb5a5b265b | refs/heads/master | 2021-01-20T18:44:51.255000 | 2016-06-19T06:08:09 | 2016-06-19T06:08:09 | 61,466,972 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ir.apk.dm.ui.user;
import ir.apk.dm.ui.BaseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.io.IOException;
/**
* Created by shahin on 4/29/2016 AD.
*/
@ManagedBean(name = "navigationBean")
@SessionScoped
public class NavigationBean extends BaseBean{
private Logger logger = LoggerFactory.getLogger(NavigationBean.class);
@Override
protected void init(){
}
public void moveToContactUs(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/contactUs.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to contactUs page : {}", ex.getMessage());
}
}
public void moveToHome(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/index.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to home page : {}", ex.getMessage());
}
}
public void moveToLaptop(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/laptops.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to laptop page : {}", ex.getMessage());
}
}
public void moveToTablet(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/tablets.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to tablet page : {}", ex.getMessage());
}
}
public void moveToMacBookPro(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/macBookPro.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to macBookPro page : {}", ex.getMessage());
}
}
public void moveToIPadPro(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/iPadPro.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to iPadPro page : {}", ex.getMessage());
}
}
public void moveToBlackBerryQ10(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/blackBerryQ10.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to blackBerryQ10 page : {}", ex.getMessage());
}
}
public void moveToAppleLaptops(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/appleLaptops.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to appleLaptops page : {}", ex.getMessage());
}
}
public void moveToAppleTablets(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/appleTablets.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to appleTablets page : {}", ex.getMessage());
}
}
public void moveToBlackBerry(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/blackBerry.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to blackBerry page : {}", ex.getMessage());
}
}
public void moveToCellphone(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/cellphones.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to cellphone page : {}", ex.getMessage());
}
}
public void onIdle() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"No activity.", "What are you doing over there?"));
}
public void onActive() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Welcome Back", "Well, that's a long coffee break!"));
}
public void moveToSignUpPage(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/signUpPage.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to signUp page : {}", ex.getMessage());
}
}
public void moveToAdmin(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/admin.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to admin page : {}", ex.getMessage());
}
}
}
| UTF-8 | Java | 5,721 | java | NavigationBean.java | Java | [
{
"context": "xt;\nimport java.io.IOException;\n\n/**\n * Created by shahin on 4/29/2016 AD.\n */\n@ManagedBean(name = \"navigat",
"end": 375,
"score": 0.9972796440124512,
"start": 369,
"tag": "USERNAME",
"value": "shahin"
}
] | null | [] | package ir.apk.dm.ui.user;
import ir.apk.dm.ui.BaseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import java.io.IOException;
/**
* Created by shahin on 4/29/2016 AD.
*/
@ManagedBean(name = "navigationBean")
@SessionScoped
public class NavigationBean extends BaseBean{
private Logger logger = LoggerFactory.getLogger(NavigationBean.class);
@Override
protected void init(){
}
public void moveToContactUs(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/contactUs.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to contactUs page : {}", ex.getMessage());
}
}
public void moveToHome(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/index.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to home page : {}", ex.getMessage());
}
}
public void moveToLaptop(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/laptops.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to laptop page : {}", ex.getMessage());
}
}
public void moveToTablet(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/tablets.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to tablet page : {}", ex.getMessage());
}
}
public void moveToMacBookPro(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/macBookPro.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to macBookPro page : {}", ex.getMessage());
}
}
public void moveToIPadPro(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/iPadPro.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to iPadPro page : {}", ex.getMessage());
}
}
public void moveToBlackBerryQ10(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/blackBerryQ10.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to blackBerryQ10 page : {}", ex.getMessage());
}
}
public void moveToAppleLaptops(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/appleLaptops.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to appleLaptops page : {}", ex.getMessage());
}
}
public void moveToAppleTablets(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/appleTablets.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to appleTablets page : {}", ex.getMessage());
}
}
public void moveToBlackBerry(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/blackBerry.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to blackBerry page : {}", ex.getMessage());
}
}
public void moveToCellphone(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/cellphones.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to cellphone page : {}", ex.getMessage());
}
}
public void onIdle() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"No activity.", "What are you doing over there?"));
}
public void onActive() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Welcome Back", "Well, that's a long coffee break!"));
}
public void moveToSignUpPage(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/signUpPage.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to signUp page : {}", ex.getMessage());
}
}
public void moveToAdmin(){
try {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
FacesContext.getCurrentInstance().getExternalContext().redirect(ec.getRequestContextPath() + "/user/admin.jsf");
} catch (IOException ex) {
logger.error("User could not be redirected to admin page : {}", ex.getMessage());
}
}
}
| 5,721 | 0.737633 | 0.735011 | 154 | 36.149349 | 39.029091 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.032468 | false | false | 4 |
683d403fd856940a23bf3d183011ab59c291b5c6 | 13,804,024,938,363 | 047b558be62d813a6101430a77516d88fd34e5dd | /src/com/fsj/service/ImgDAO.java | 87781dc9f7f9e1a42e361d3049ad12c8b5a558c4 | [] | no_license | liao1565553/FSJJJR | https://github.com/liao1565553/FSJJJR | 2db21413b2cfc45c33c54070c2d5bfef28861142 | 029e5e2311460ff2a68545626aed9a4bbb8a202d | refs/heads/master | 2021-01-23T07:44:36.954000 | 2017-03-28T09:19:39 | 2017-03-28T09:19:39 | 86,436,809 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fsj.service;
import java.util.List;
import java.util.Map;
import com.fsj.entity.Img;
//图片业务逻辑接口
public interface ImgDAO {
// 查询所有
public int queryAll(String hql, Map<String, Object> map);
public List<Img> querypage(int pageNumber, int pageSize, String hql,
Map<String, Object> map);
// 图片注册
public boolean addImg(Img img);
// 图片更新
public boolean updateImg(Img img);
// 删除图片
public boolean deleteImg(int iid);
}
| UTF-8 | Java | 490 | java | ImgDAO.java | Java | [] | null | [] | package com.fsj.service;
import java.util.List;
import java.util.Map;
import com.fsj.entity.Img;
//图片业务逻辑接口
public interface ImgDAO {
// 查询所有
public int queryAll(String hql, Map<String, Object> map);
public List<Img> querypage(int pageNumber, int pageSize, String hql,
Map<String, Object> map);
// 图片注册
public boolean addImg(Img img);
// 图片更新
public boolean updateImg(Img img);
// 删除图片
public boolean deleteImg(int iid);
}
| 490 | 0.721719 | 0.721719 | 24 | 17.416666 | 18.553787 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.125 | false | false | 4 |
74920a639b15f3cca3ae06829ac2a3a725ee0e1c | 17,987,323,094,276 | 479500879d6971737f206f71a4a3983b6cebe9e3 | /src/main/java/ru/exapmple/user/Client.java | 980fbc1ab8516904a7dad83c035a9e87a816c1ae | [] | no_license | YlaVP/payment | https://github.com/YlaVP/payment | e70e49fa136cdc52f55a6838d12ae0167ab218e9 | f951b1d3b62198022c722e023f20aeee378e2abb | refs/heads/master | 2023-01-22T17:53:19.655000 | 2020-10-07T15:19:26 | 2020-10-07T15:19:26 | 293,311,909 | 0 | 0 | null | false | 2020-10-26T13:09:54 | 2020-09-06T16:02:10 | 2020-10-07T15:19:29 | 2020-10-26T13:00:44 | 100 | 0 | 0 | 1 | Java | false | false | package ru.exapmple.user;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@AllArgsConstructor
@Getter
@ToString
public
class Client {
private String phoneNumber;
private String accountNumber;
public String getPhoneNumber() {
return phoneNumber;
}
public String getAccountNumber() {
return accountNumber;
}
@Override
public String toString() {
return "User{" + "phoneNumber='" + phoneNumber + '\'' + ", accountNumber='" + accountNumber + '\'' + '}';
}
}
| UTF-8 | Java | 551 | java | Client.java | Java | [] | null | [] | package ru.exapmple.user;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@AllArgsConstructor
@Getter
@ToString
public
class Client {
private String phoneNumber;
private String accountNumber;
public String getPhoneNumber() {
return phoneNumber;
}
public String getAccountNumber() {
return accountNumber;
}
@Override
public String toString() {
return "User{" + "phoneNumber='" + phoneNumber + '\'' + ", accountNumber='" + accountNumber + '\'' + '}';
}
}
| 551 | 0.660617 | 0.660617 | 27 | 19.370371 | 22.402294 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37037 | false | false | 4 |
abaa75b976c5976de7708911f3ca6d2ed1a2eacd | 32,813,550,200,953 | 2d34f9c370b0750d5d69f3c3146b5fe74f359223 | /src/main/java/org/ggp/base/player/gamer/statemachine/MinimaxPlayer.java | f4f155cca473b02ee4fbdde7b0e0aec8a9d3974b | [
"BSD-3-Clause"
] | permissive | andreyz4k/ggp-base | https://github.com/andreyz4k/ggp-base | f14784b8e8310758be06978daac67a45711643b3 | 35b301b3f5f18c29c1d3e11de18ee540361f9d10 | refs/heads/master | 2021-05-30T12:48:20.603000 | 2016-02-07T18:04:36 | 2016-02-07T18:04:36 | 37,729,619 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ggp.base.player.gamer.statemachine;
import org.ggp.base.apps.player.detail.DetailPanel;
import org.ggp.base.apps.player.detail.SimpleDetailPanel;
import org.ggp.base.player.gamer.exception.GamePreviewException;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Move;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException;
import org.ggp.base.util.statemachine.implementation.prover.ProverStateMachine;
import java.util.*;
import java.util.logging.Logger;
/**
* Created by andrey on 16.04.15.
*/
public class MinimaxPlayer extends StateMachineGamer{
@Override
public void stateMachineAbort() {
}
@Override
public void stateMachineStop() {
}
@Override
public void preview(Game g, long timeout) throws GamePreviewException {
}
private static Logger log = Logger.getLogger(MinimaxPlayer.class.getName());
private Role getOpponent(Role role) {
List<Role> roles = getStateMachine().getRoles();
for (Role r : roles) {
if (!r.equals(role)) {
return r;
}
}
return null;
}
private int heuristicScore(MachineState state, Role role) throws MoveDefinitionException, GoalDefinitionException {
Role opponent = getOpponent(role);
return getStateMachine().getGoal(state,role) - getStateMachine().getGoal(state, opponent);
}
private int depthCharge(MachineState state, Role role) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
if (getStateMachine().isTerminal(state)) {
return getStateMachine().getGoal(state, role);
}
List<Role> roles = getStateMachine().getRoles();
List<Move> actions = new LinkedList<>();
for (Role r:roles) {
List<Move> moves = getStateMachine().getLegalMoves(state, r);
actions.add((moves.get(new Random().nextInt(moves.size()))));
}
return depthCharge(getStateMachine().getNextState(state, actions), role);
}
private int monteCarloScore(MachineState state, Role role, int count) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += depthCharge(state, role);
}
return sum/count;
}
private int maxScore(Role role, MachineState state, int alpha, int beta, int level) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
if (getStateMachine().isTerminal(state)) {
return getStateMachine().getGoal(state, role);
}
if (level == 0) {
return monteCarloScore(state, role, 2);
}
List<Move> moves = getStateMachine().getLegalMoves(state, role);
for (Move move: moves) {
int res = minScore(role, move, state, alpha, beta, level);
alpha = Math.max(alpha, res);
if (alpha >= beta) {
return beta;
}
}
return alpha;
}
private int minScore(Role role, Move action, MachineState state, int alpha, int beta, int level) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
Role opponent = getOpponent(role);
if (opponent == null) {
beta = maxScore(getRole(), getStateMachine().getNextState(state, new ArrayList<>(Arrays.asList(action))), alpha, beta, level - 1);
} else {
List<Role> roles = getStateMachine().getRoles();
List<Move> moves = getStateMachine().getLegalMoves(state, opponent);
for (Move move : moves) {
List<Move> actions;
if (role.equals(roles.get(0))) {
actions = new ArrayList<>(Arrays.asList(action, move));
} else {
actions = new ArrayList<>(Arrays.asList(move, action));
}
int res = maxScore(role, getStateMachine().getNextState(state, actions), alpha, beta, level - 1);
// log.info(actions.toString() + Integer.toString(res));
beta = Math.min(beta, res);
if (beta <= alpha) {
return alpha;
}
}
}
return beta;
}
private Move bestMove(MachineState state, long timeout) throws MoveDefinitionException, TransitionDefinitionException, GoalDefinitionException{
List<Move> moves = getStateMachine().getLegalMoves(state,getRole());
Move resMove = (moves.get(new Random().nextInt(moves.size())));
if (moves.size() == 1) {
return resMove;
}
int alpha = 0;
int beta = 100;
log.info("hui");
log.info(state.toString());
int depth = 2;
long start = System.currentTimeMillis();
long time0 = start;
for (int i = 0; i < moves.size(); i++) {
Move move = moves.get(i);
int res = minScore(getRole(), move, state, alpha, beta, depth);
log.info(move.toString() + Integer.toString(res));
if (res > alpha) {
alpha = res;
resMove = move;
}
long time = System.currentTimeMillis();
// log.info(Long.toString(time - time0) + " " + Long.toString(timeout) + " " + Long.toString(timeout - time0));
// log.info(Long.toString((timeout - time0)/(moves.size() - i)));
// log.info(Long.toString( (timeout - time0)/(moves.size() - i)/moves.size()));
if (time - time0 > (timeout - time0)/(moves.size() - i)) {
depth--;
log.info("-");
} else if (time - time0 < (timeout - time0)/(moves.size() - i)/moves.size()) {
depth++;
log.info("+");
}
time0 = time;
}
return resMove;
}
@Override
public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
MachineState state = getCurrentState();
return bestMove(state, timeout);
}
@Override
public String getName() {
return "MinimaxPlayer";
}
@Override
public StateMachine getInitialStateMachine() {
return new ProverStateMachine();
}
@Override
public DetailPanel getDetailPanel() {
return new SimpleDetailPanel();
}
@Override
public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
}
}
| UTF-8 | Java | 6,980 | java | MinimaxPlayer.java | Java | [
{
"context": "mport java.util.logging.Logger;\n\n/**\n * Created by andrey on 16.04.15.\n */\npublic class MinimaxPlayer exten",
"end": 839,
"score": 0.8884270787239075,
"start": 833,
"tag": "NAME",
"value": "andrey"
}
] | null | [] | package org.ggp.base.player.gamer.statemachine;
import org.ggp.base.apps.player.detail.DetailPanel;
import org.ggp.base.apps.player.detail.SimpleDetailPanel;
import org.ggp.base.player.gamer.exception.GamePreviewException;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.statemachine.MachineState;
import org.ggp.base.util.statemachine.Move;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException;
import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException;
import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException;
import org.ggp.base.util.statemachine.implementation.prover.ProverStateMachine;
import java.util.*;
import java.util.logging.Logger;
/**
* Created by andrey on 16.04.15.
*/
public class MinimaxPlayer extends StateMachineGamer{
@Override
public void stateMachineAbort() {
}
@Override
public void stateMachineStop() {
}
@Override
public void preview(Game g, long timeout) throws GamePreviewException {
}
private static Logger log = Logger.getLogger(MinimaxPlayer.class.getName());
private Role getOpponent(Role role) {
List<Role> roles = getStateMachine().getRoles();
for (Role r : roles) {
if (!r.equals(role)) {
return r;
}
}
return null;
}
private int heuristicScore(MachineState state, Role role) throws MoveDefinitionException, GoalDefinitionException {
Role opponent = getOpponent(role);
return getStateMachine().getGoal(state,role) - getStateMachine().getGoal(state, opponent);
}
private int depthCharge(MachineState state, Role role) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
if (getStateMachine().isTerminal(state)) {
return getStateMachine().getGoal(state, role);
}
List<Role> roles = getStateMachine().getRoles();
List<Move> actions = new LinkedList<>();
for (Role r:roles) {
List<Move> moves = getStateMachine().getLegalMoves(state, r);
actions.add((moves.get(new Random().nextInt(moves.size()))));
}
return depthCharge(getStateMachine().getNextState(state, actions), role);
}
private int monteCarloScore(MachineState state, Role role, int count) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += depthCharge(state, role);
}
return sum/count;
}
private int maxScore(Role role, MachineState state, int alpha, int beta, int level) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
if (getStateMachine().isTerminal(state)) {
return getStateMachine().getGoal(state, role);
}
if (level == 0) {
return monteCarloScore(state, role, 2);
}
List<Move> moves = getStateMachine().getLegalMoves(state, role);
for (Move move: moves) {
int res = minScore(role, move, state, alpha, beta, level);
alpha = Math.max(alpha, res);
if (alpha >= beta) {
return beta;
}
}
return alpha;
}
private int minScore(Role role, Move action, MachineState state, int alpha, int beta, int level) throws GoalDefinitionException, MoveDefinitionException, TransitionDefinitionException {
Role opponent = getOpponent(role);
if (opponent == null) {
beta = maxScore(getRole(), getStateMachine().getNextState(state, new ArrayList<>(Arrays.asList(action))), alpha, beta, level - 1);
} else {
List<Role> roles = getStateMachine().getRoles();
List<Move> moves = getStateMachine().getLegalMoves(state, opponent);
for (Move move : moves) {
List<Move> actions;
if (role.equals(roles.get(0))) {
actions = new ArrayList<>(Arrays.asList(action, move));
} else {
actions = new ArrayList<>(Arrays.asList(move, action));
}
int res = maxScore(role, getStateMachine().getNextState(state, actions), alpha, beta, level - 1);
// log.info(actions.toString() + Integer.toString(res));
beta = Math.min(beta, res);
if (beta <= alpha) {
return alpha;
}
}
}
return beta;
}
private Move bestMove(MachineState state, long timeout) throws MoveDefinitionException, TransitionDefinitionException, GoalDefinitionException{
List<Move> moves = getStateMachine().getLegalMoves(state,getRole());
Move resMove = (moves.get(new Random().nextInt(moves.size())));
if (moves.size() == 1) {
return resMove;
}
int alpha = 0;
int beta = 100;
log.info("hui");
log.info(state.toString());
int depth = 2;
long start = System.currentTimeMillis();
long time0 = start;
for (int i = 0; i < moves.size(); i++) {
Move move = moves.get(i);
int res = minScore(getRole(), move, state, alpha, beta, depth);
log.info(move.toString() + Integer.toString(res));
if (res > alpha) {
alpha = res;
resMove = move;
}
long time = System.currentTimeMillis();
// log.info(Long.toString(time - time0) + " " + Long.toString(timeout) + " " + Long.toString(timeout - time0));
// log.info(Long.toString((timeout - time0)/(moves.size() - i)));
// log.info(Long.toString( (timeout - time0)/(moves.size() - i)/moves.size()));
if (time - time0 > (timeout - time0)/(moves.size() - i)) {
depth--;
log.info("-");
} else if (time - time0 < (timeout - time0)/(moves.size() - i)/moves.size()) {
depth++;
log.info("+");
}
time0 = time;
}
return resMove;
}
@Override
public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
MachineState state = getCurrentState();
return bestMove(state, timeout);
}
@Override
public String getName() {
return "MinimaxPlayer";
}
@Override
public StateMachine getInitialStateMachine() {
return new ProverStateMachine();
}
@Override
public DetailPanel getDetailPanel() {
return new SimpleDetailPanel();
}
@Override
public void stateMachineMetaGame(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
}
}
| 6,980 | 0.617908 | 0.61361 | 184 | 36.934784 | 37.085186 | 189 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.820652 | false | false | 4 |
44777a4518230da92b942214fbf2f9c8d85f341a | 12,317,966,272,213 | 80273f07a0ca15f3b7bfdb698a9a77b8d3daeba5 | /src/main/java/solutions/graphs/GraphNode.java | 40e2d1af37bb45bcb4d5e5bfab8fd2ade5480aa9 | [] | no_license | jasonboukheir/javainterview | https://github.com/jasonboukheir/javainterview | 6e96f36fa334693cd74bff2d3587325e6c2694a2 | ebd2656267f54ff8d1579c1e7c88f45dd5748127 | refs/heads/master | 2020-03-19T05:52:56.734000 | 2018-06-20T02:02:15 | 2018-06-20T02:02:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package solutions.graphs;
public class GraphNode {
Object data;
public GraphNode(Object data) {
this.data = data;
}
} | UTF-8 | Java | 139 | java | GraphNode.java | Java | [] | null | [] | package solutions.graphs;
public class GraphNode {
Object data;
public GraphNode(Object data) {
this.data = data;
}
} | 139 | 0.640288 | 0.640288 | 9 | 14.555555 | 12.588452 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
e02076f48b9aa424e28c88692285a2a5055fc663 | 1,872,605,806,637 | a15814f95a197d887f3f9b98c8f0b184b59dbda9 | /src/main/java/com/lonebytesoft/hamster/accounting/service/config/ConfigService.java | 65158e3f859fa596e7f3e43c4c8fc33a3f25097a | [] | no_license | hamsterxc/accounting | https://github.com/hamsterxc/accounting | fe7bf3f7b9d3fd9f7a7e3b0040fc180d9404eac1 | 919d923c9198d39e7a664676f497e8c2ab6d5be0 | refs/heads/master | 2023-07-22T05:42:31.845000 | 2019-08-25T15:55:40 | 2019-08-25T20:27:01 | 99,568,622 | 0 | 0 | null | false | 2023-07-16T03:15:47 | 2017-08-07T10:57:31 | 2019-08-25T20:27:22 | 2023-07-16T03:15:46 | 957 | 0 | 0 | 4 | Java | false | false | package com.lonebytesoft.hamster.accounting.service.config;
import com.lonebytesoft.hamster.accounting.model.Config;
public interface ConfigService {
Config get();
void save(Config config);
}
| UTF-8 | Java | 205 | java | ConfigService.java | Java | [] | null | [] | package com.lonebytesoft.hamster.accounting.service.config;
import com.lonebytesoft.hamster.accounting.model.Config;
public interface ConfigService {
Config get();
void save(Config config);
}
| 205 | 0.770732 | 0.770732 | 11 | 17.636364 | 22.054777 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 4 |
6289be4ac1734ed797c4eb8d5f461cf7b4970023 | 1,546,188,294,275 | b30a89a2fb8dd5d651e1eaed5ccd994e48a8d495 | /src/sketch/saladmaker/SaladMenu.java | f20156f8e1a270eded33eec33d91a8e696812d42 | [] | no_license | AndrianaY/salad | https://github.com/AndrianaY/salad | 185cb04e25f27271c2f42cc872ab61a67be24d4d | 03aed11d0c60aa60c3caa50c3fabd48e188e676b | refs/heads/master | 2021-05-04T04:02:03.662000 | 2016-10-20T21:15:58 | 2016-10-20T21:15:58 | 70,826,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mentor.salad.sketch.saladmaker;
/**
* Created by Andriana_Yarmoliuk on 10/6/2016.
*/
public class SaladMenu extends Menu{
private Salad salad;
private SaladMenu(Salad salad){
this.salad = salad;
currentMenu = this;
parentMenu = this;
nextMenu = this;
}
public static Menu getSaladMenuInstance(Salad salad){
return new SaladMenu(salad);
}
@Override
public void display() {
System.out.println("currently working with " + salad.getName() + " salad");
System.out.println("1- return to main menu, 2 - go to choosing ingredients, 3 - make salad, 4 - sort salad, 5 - calc calories.....");
}
@Override
public void performAction(String action) {
switch (action){
case "1": toMainMenu(); return;
case "2": goToIngredients(); return;
case "3": makeSalad(); return;
}
}
private void toMainMenu(){
moveNextMenu = parentMenu;
}
private void goToIngredients(){
moveNextMenu = nextMenu;
}
private void makeSalad(){
salad.makeSalad();
}
}
| UTF-8 | Java | 1,135 | java | SaladMenu.java | Java | [
{
"context": "mentor.salad.sketch.saladmaker;\n\n/**\n * Created by Andriana_Yarmoliuk on 10/6/2016.\n */\npublic class SaladMenu extends ",
"end": 77,
"score": 0.9997744560241699,
"start": 59,
"tag": "NAME",
"value": "Andriana_Yarmoliuk"
}
] | null | [] | package mentor.salad.sketch.saladmaker;
/**
* Created by Andriana_Yarmoliuk on 10/6/2016.
*/
public class SaladMenu extends Menu{
private Salad salad;
private SaladMenu(Salad salad){
this.salad = salad;
currentMenu = this;
parentMenu = this;
nextMenu = this;
}
public static Menu getSaladMenuInstance(Salad salad){
return new SaladMenu(salad);
}
@Override
public void display() {
System.out.println("currently working with " + salad.getName() + " salad");
System.out.println("1- return to main menu, 2 - go to choosing ingredients, 3 - make salad, 4 - sort salad, 5 - calc calories.....");
}
@Override
public void performAction(String action) {
switch (action){
case "1": toMainMenu(); return;
case "2": goToIngredients(); return;
case "3": makeSalad(); return;
}
}
private void toMainMenu(){
moveNextMenu = parentMenu;
}
private void goToIngredients(){
moveNextMenu = nextMenu;
}
private void makeSalad(){
salad.makeSalad();
}
}
| 1,135 | 0.599119 | 0.585903 | 41 | 26.682926 | 25.823452 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.536585 | false | false | 4 |
90054d6da2a41c49896b807cc0925a0df27525d7 | 36,421,322,681,405 | f248749a2ecd0f377ce4b3e280ebfa9a2d26c520 | /tydic_uc_service/uac_service/src/main/java/com/tydic/unicom/uac/service/vo/RedisDataVo.java | ce41f7a41960f2525a04599d99c6da186abc2002 | [] | no_license | bellmit/spring | https://github.com/bellmit/spring | e0206b40c7cae9ffc4bcdad2e41ce81f800270b5 | 81bff4d8eab01303c2d299a0075e452dc46cda9d | refs/heads/master | 2023-03-17T10:37:55.937000 | 2017-09-23T05:50:39 | 2017-09-23T05:50:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tydic.unicom.uac.service.vo;
import java.io.Serializable;
import java.util.Map;
import javax.persistence.Id;
public class RedisDataVo implements Serializable{
private static final long serialVersionUID = 1L;
private String id;
private Object obj;
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
| UTF-8 | Java | 467 | java | RedisDataVo.java | Java | [] | null | [] | package com.tydic.unicom.uac.service.vo;
import java.io.Serializable;
import java.util.Map;
import javax.persistence.Id;
public class RedisDataVo implements Serializable{
private static final long serialVersionUID = 1L;
private String id;
private Object obj;
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
}
| 467 | 0.713062 | 0.710921 | 28 | 15.678572 | 15.121068 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.178571 | false | false | 4 |
31f8fa3ddb4a13fb7f873228386b266d1a55cc11 | 18,227,841,264,252 | 5e459013ae685927475c802ef4fa9c7aa56cef8e | /sw-admin-infra/src/main/java/com/subway/infra/cassandra/spring/CassandraClientConfig.java | 42a363d56117a68b42464f75a5d9c8758a46de0f | [] | no_license | ZeuAlex/subway | https://github.com/ZeuAlex/subway | 826be2ad0ae01f2ed7f2a6ffaa6b05035bbab959 | 096628eddbcec04c34d31deee5e9c7bbf1b12b94 | refs/heads/master | 2021-06-10T19:12:25.358000 | 2016-05-21T15:08:21 | 2016-05-21T15:08:21 | 50,256,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.subway.infra.cassandra.spring;
import com.subway.infra.cassandra.CassandraClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CassandraClientConfig {
@Bean
public CassandraClient cassandraClient() {
// TODO : Cassandra config
// TODO : handle concurrent access on aggregate
return new CassandraClient();
}
}
| UTF-8 | Java | 460 | java | CassandraClientConfig.java | Java | [] | null | [] | package com.subway.infra.cassandra.spring;
import com.subway.infra.cassandra.CassandraClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CassandraClientConfig {
@Bean
public CassandraClient cassandraClient() {
// TODO : Cassandra config
// TODO : handle concurrent access on aggregate
return new CassandraClient();
}
}
| 460 | 0.747826 | 0.747826 | 20 | 22 | 22.416512 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
20aa1a72a4e9ad147661427c28f4595c1e21703b | 34,007,551,060,889 | 371353730cf46dd165d40e713bb67d0a1672d83c | /src/test/java/com/springboot/mvc/login/repository/TaskRepositoryTest.java | 10cdcdb5ec7351880f3eb0a734a118df4c18671b | [] | no_license | Abhisek-Das/ProjectManagementApp | https://github.com/Abhisek-Das/ProjectManagementApp | eeaef88b4c2b2a1f3d8a7c27ad68ce3803a68e11 | df263c850642ebfe711e2d8412ab1098b1d2214b | refs/heads/master | 2021-12-28T03:57:14.106000 | 2021-12-18T00:14:25 | 2021-12-18T00:14:25 | 179,908,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springboot.mvc.login.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.springboot.mvc.login.ProjectManagementAppApplicationTests;
import com.springboot.mvc.login.model.Task;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@DatabaseSetup("/taskData.xml")
public class TaskRepositoryTest extends ProjectManagementAppApplicationTests{
@Autowired
TaskRepository taskrepository;
@Test()
public void testfindByTaskname(){
List<Task> task = taskrepository.findByTaskname("Final Task1");
// assertEquals(task.get(0).getTaskname(), "Final Task1");
assertTrue(task != null);
}
}
| UTF-8 | Java | 1,641 | java | TaskRepositoryTest.java | Java | [] | null | [] | package com.springboot.mvc.login.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.springboot.mvc.login.ProjectManagementAppApplicationTests;
import com.springboot.mvc.login.model.Task;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@DatabaseSetup("/taskData.xml")
public class TaskRepositoryTest extends ProjectManagementAppApplicationTests{
@Autowired
TaskRepository taskrepository;
@Test()
public void testfindByTaskname(){
List<Task> task = taskrepository.findByTaskname("Final Task1");
// assertEquals(task.get(0).getTaskname(), "Final Task1");
assertTrue(task != null);
}
}
| 1,641 | 0.834247 | 0.83181 | 46 | 34.673912 | 28.025652 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.347826 | false | false | 4 |
4f0fbfe54d25feb814c7e838d2c941ffa7244459 | 28,303,834,522,032 | 71b7a62e4e9948a3d2f47aeddf870cb6a8934cbb | /src/main/java/com/inventario/persistencia/crud/BodegaCrudRepositorio.java | 9495d7645e155658915d296fbf69aa4028e8425d | [] | no_license | cesarlatorre2021/Inventario | https://github.com/cesarlatorre2021/Inventario | 4de15a6db3b8f4aa0ed761f84e63bc1d3e7732f3 | 058cc3e041eb38fa93ed94c2b8496afe57a05089 | refs/heads/master | 2023-04-03T19:23:44.644000 | 2021-03-24T19:08:36 | 2021-03-24T19:08:36 | 348,421,718 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inventario.persistencia.crud;
import java.util.Optional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import com.inventario.entity.Bodega;
public interface BodegaCrudRepositorio extends CrudRepository <Bodega, Integer>{
@Query(value = "SELECT * "
+ " FROM BODEGA"
+ " WHERE IDBODEGA = :idbodega", nativeQuery = true)
Optional<Bodega> listarBodegaID(@Param("idbodega") String idBodega);
@Modifying
@Transactional
@Query(value = "DELETE "
+ " FROM BODEGA "
+ " WHERE IDBODEGA = ?", nativeQuery = true)
void deleteForId(String idBodega);
@Modifying
@Query(value = "UPDATE BODEGA "
+ " SET NOMBREBODEGA = :nombrebodega"
+ " ,DIRECCION = :direccion"
+ " ,CIUDAD = :ciudad"
+ " ,DEPARTAMENTO = :departamento"
+ " ,PAIS = :pais"
+ " ,FECHAMODIFICACION = DATE"
+ " WHERE IDBODEGA = :idbodega", nativeQuery = true)
void modificarProducto(@Param("nombrebodega") String nombreBodega,
@Param("direccion") String direccion,
@Param("ciudad") String ciudad,
@Param("departamento") String departamento,
@Param("pais") String pais);
}
| UTF-8 | Java | 1,487 | java | BodegaCrudRepositorio.java | Java | [] | null | [] | package com.inventario.persistencia.crud;
import java.util.Optional;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import com.inventario.entity.Bodega;
public interface BodegaCrudRepositorio extends CrudRepository <Bodega, Integer>{
@Query(value = "SELECT * "
+ " FROM BODEGA"
+ " WHERE IDBODEGA = :idbodega", nativeQuery = true)
Optional<Bodega> listarBodegaID(@Param("idbodega") String idBodega);
@Modifying
@Transactional
@Query(value = "DELETE "
+ " FROM BODEGA "
+ " WHERE IDBODEGA = ?", nativeQuery = true)
void deleteForId(String idBodega);
@Modifying
@Query(value = "UPDATE BODEGA "
+ " SET NOMBREBODEGA = :nombrebodega"
+ " ,DIRECCION = :direccion"
+ " ,CIUDAD = :ciudad"
+ " ,DEPARTAMENTO = :departamento"
+ " ,PAIS = :pais"
+ " ,FECHAMODIFICACION = DATE"
+ " WHERE IDBODEGA = :idbodega", nativeQuery = true)
void modificarProducto(@Param("nombrebodega") String nombreBodega,
@Param("direccion") String direccion,
@Param("ciudad") String ciudad,
@Param("departamento") String departamento,
@Param("pais") String pais);
}
| 1,487 | 0.65501 | 0.65501 | 42 | 34.404762 | 23.339176 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.928571 | false | false | 4 |
28b13760d73510103aca3741815d61b75b44ccba | 35,244,501,631,662 | eb7e37bb31007391fbf36417dec6b97b23cdd66f | /Healthy_3/src/com/Healthy/dao/UserOperateDAO.java | 6309c05bba1daa5047b9b6002d9ae46ebff36b23 | [] | no_license | xyz0101/Healthy | https://github.com/xyz0101/Healthy | efb318177bf87d9ab49fc8463dda6f9f06eeefa5 | 5d5d0ee750cb62a9eab58e3c977742bbb7a527ee | refs/heads/master | 2021-01-19T16:10:09.578000 | 2017-05-19T05:25:51 | 2017-05-19T05:25:51 | 88,251,101 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.Healthy.dao;
import com.Healthy.model.UserOperate;
public interface UserOperateDAO {
public void add(UserOperate useroperate);
}
| UTF-8 | Java | 151 | java | UserOperateDAO.java | Java | [] | null | [] | package com.Healthy.dao;
import com.Healthy.model.UserOperate;
public interface UserOperateDAO {
public void add(UserOperate useroperate);
}
| 151 | 0.768212 | 0.768212 | 7 | 19.571428 | 17.393408 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
3bc07c678364cc0585c72737e2a369b6634b846d | 33,749,853,023,105 | 34b913be3fb4d2d03f017d92a1ac2ec32abb6445 | /Workspace/TowerDefense/src/data/TowerType.java | 7e83dec8eb60b9f87879f708e3b9a89060aef87d | [] | no_license | realalphaman/Simple-Tower-Defense | https://github.com/realalphaman/Simple-Tower-Defense | 7d6c7d64db1183e203fc92f467c6092b77c6b7d1 | 59693bd0249d03afc775dcb37896f09dbd6c8055 | refs/heads/master | 2023-07-08T13:36:14.933000 | 2021-08-23T09:13:34 | 2021-08-23T09:13:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package data;
import org.newdawn.slick.opengl.Texture;
import static helpers.Artist.*;
public enum TowerType {
CannonBlue(new Texture[] {QuickLoad("BlueCannonBase"), QuickLoad("BlueCannonGun")},BulletType.CannonBall,100,1,20),
CannonIce(new Texture[] {QuickLoad("iceCannon")},BulletType.IceBall,10000,2,30),
CannonKing(new Texture[] {QuickLoad("TowerKing")},BulletType.KingBall,300,2,55),
CannonQueen(new Texture[] {QuickLoad("TowerQueen")},BulletType.QueenBall,200,2,40);
Texture[] textures;
BulletType projectileType;
int damage, range, cost;
float firingSpeed;
TowerType(Texture[] textures, BulletType projectileType, int range, float firingSpeed, int cost){
this.textures=textures;
this.projectileType= projectileType;
this.range= range;
this.firingSpeed=firingSpeed;
this.cost=cost;
}
public int getCost(TowerType towerType) {
return towerType.cost;
}
}
| UTF-8 | Java | 895 | java | TowerType.java | Java | [] | null | [] | package data;
import org.newdawn.slick.opengl.Texture;
import static helpers.Artist.*;
public enum TowerType {
CannonBlue(new Texture[] {QuickLoad("BlueCannonBase"), QuickLoad("BlueCannonGun")},BulletType.CannonBall,100,1,20),
CannonIce(new Texture[] {QuickLoad("iceCannon")},BulletType.IceBall,10000,2,30),
CannonKing(new Texture[] {QuickLoad("TowerKing")},BulletType.KingBall,300,2,55),
CannonQueen(new Texture[] {QuickLoad("TowerQueen")},BulletType.QueenBall,200,2,40);
Texture[] textures;
BulletType projectileType;
int damage, range, cost;
float firingSpeed;
TowerType(Texture[] textures, BulletType projectileType, int range, float firingSpeed, int cost){
this.textures=textures;
this.projectileType= projectileType;
this.range= range;
this.firingSpeed=firingSpeed;
this.cost=cost;
}
public int getCost(TowerType towerType) {
return towerType.cost;
}
}
| 895 | 0.757542 | 0.728492 | 30 | 28.833334 | 31.57645 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.266667 | false | false | 13 |
6ad76dad6ec4f73545400f1840f943ab857001f1 | 9,345,848,904,311 | d3515a72883ccad1d89f1d9c9398a59d4c3eb6d0 | /src/entidade/Linha.java | 906df3231c5c59a0b43db41885b1fefd769e7b90 | [] | no_license | rosilva/theseus | https://github.com/rosilva/theseus | ec3fa281536d9501a6c2206bd91405152d873c36 | 870172df695c8ca1286df803b301ce2a44a665cb | refs/heads/master | 2015-08-19T13:03:54.478000 | 2015-02-10T14:14:46 | 2015-02-10T14:14:46 | 29,369,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package entidade;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Linha implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
/* Campo idLinha não pode ser auto incremental, para que os ids das linhas possam ser setados manualmente */
// @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idLinha;
private String descricao;
@OneToMany(mappedBy = "linha")
private List<Onibus> onibus;
public Integer getIdLinha() {
return idLinha;
}
public void setIdLinha(Integer idLinha) {
this.idLinha = idLinha;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public List<Onibus> getOnibus() {
return onibus;
}
public void setOnibus(List<Onibus> onibus) {
this.onibus = onibus;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((idLinha == null) ? 0 : idLinha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Linha other = (Linha) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (idLinha == null) {
if (other.idLinha != null)
return false;
} else if (!idLinha.equals(other.idLinha))
return false;
return true;
}
}
| ISO-8859-1 | Java | 1,730 | java | Linha.java | Java | [] | null | [] | package entidade;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Linha implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
/* Campo idLinha não pode ser auto incremental, para que os ids das linhas possam ser setados manualmente */
// @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idLinha;
private String descricao;
@OneToMany(mappedBy = "linha")
private List<Onibus> onibus;
public Integer getIdLinha() {
return idLinha;
}
public void setIdLinha(Integer idLinha) {
this.idLinha = idLinha;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public List<Onibus> getOnibus() {
return onibus;
}
public void setOnibus(List<Onibus> onibus) {
this.onibus = onibus;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((descricao == null) ? 0 : descricao.hashCode());
result = prime * result + ((idLinha == null) ? 0 : idLinha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Linha other = (Linha) obj;
if (descricao == null) {
if (other.descricao != null)
return false;
} else if (!descricao.equals(other.descricao))
return false;
if (idLinha == null) {
if (other.idLinha != null)
return false;
} else if (!idLinha.equals(other.idLinha))
return false;
return true;
}
}
| 1,730 | 0.683632 | 0.680162 | 85 | 19.341177 | 19.03344 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false | 13 |
96e054883d7620519da5d2459c6c93df658fa595 | 14,491,219,710,943 | 75dbc6f87baa1d7c2c69230cadf3954af9ec270f | /app/src/main/java/com/example/messaging__application/MessageAdapter.java | c627dbd9bf92eeeac5803d2059987f43f1a15d6e | [] | no_license | kamzon/Messaging__Application | https://github.com/kamzon/Messaging__Application | 0b281c8747f6e61c06d3571b8b05232e1955495c | 8cb9ecd48db08cad78ab2cad2766d78b49bd73a1 | refs/heads/master | 2022-12-07T02:26:16.976000 | 2020-09-03T15:30:30 | 2020-09-03T15:30:30 | 292,609,243 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.messaging__application;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.mlkit.nl.smartreply.SmartReply;
import com.google.mlkit.nl.smartreply.SmartReplyGenerator;
import com.google.mlkit.nl.smartreply.SmartReplySuggestion;
import com.google.mlkit.nl.smartreply.SmartReplySuggestionResult;
import com.google.mlkit.nl.smartreply.TextMessage;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>
{
private List<Messages> userMessagesList;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
private ArrayList<TextMessage> conversation = new ArrayList<TextMessage>();
private ChatActivity chatActivity = new ChatActivity();
MyCallback myCallback = null;
public interface MyCallback {
// Declaration of the template function for the interface
public void updateMyText(String rec1,String rec2, String rec3);
}
public MessageAdapter (List<Messages> userMessagesList,MyCallback callback)
{
this.userMessagesList = userMessagesList;
this.myCallback = callback;
}
public class MessageViewHolder extends RecyclerView.ViewHolder
{
public TextView senderMessageText, receiverMessageText,recomandedTextView;
public CircleImageView receiverProfileImage;
public ImageView messageSenderPicture, messageReceiverPicture;
public MessageViewHolder(@NonNull View itemView)
{
super(itemView);
senderMessageText = (TextView) itemView.findViewById(R.id.sender_messsage_text);
receiverMessageText = (TextView) itemView.findViewById(R.id.receiver_message_text);
receiverProfileImage = (CircleImageView) itemView.findViewById(R.id.message_profile_image);
messageReceiverPicture = itemView.findViewById(R.id.message_receiver_image_view);
messageSenderPicture = itemView.findViewById(R.id.message_sender_image_view);
//recomandedTextView = (TextView) itemView.findViewById(R.id.recomanded_text);
}
}
@NonNull
@Override
public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.custom_messages_layout, viewGroup, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final MessageViewHolder messageViewHolder, final int position)
{
String messageSenderId = mAuth.getCurrentUser().getUid();
Messages messages = userMessagesList.get(position);
String fromUserID = messages.getFrom();
String fromMessageType = messages.getType();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.hasChild("image"))
{
String receiverImage = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(receiverImage).placeholder(R.drawable.profile_image).into(messageViewHolder.receiverProfileImage);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
messageViewHolder.receiverMessageText.setVisibility(View.GONE);
messageViewHolder.receiverProfileImage.setVisibility(View.GONE);
messageViewHolder.senderMessageText.setVisibility(View.GONE);
messageViewHolder.messageSenderPicture.setVisibility(View.GONE);
messageViewHolder.messageReceiverPicture.setVisibility(View.GONE);
if (fromMessageType.equals("text"))
{
if (fromUserID.equals(messageSenderId))
{
messageViewHolder.senderMessageText.setVisibility(View.VISIBLE);
messageViewHolder.senderMessageText.setBackgroundResource(R.drawable.sender_messages_layout);
messageViewHolder.senderMessageText.setTextColor(Color.BLACK);
messageViewHolder.senderMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
conversation.add(TextMessage.createForLocalUser(messages.getMessage(), System.currentTimeMillis()));
SmartReplyGenerator smartReply = SmartReply.getClient();
smartReply.suggestReplies(conversation)
.addOnSuccessListener(new OnSuccessListener<SmartReplySuggestionResult>() {
@Override
public void onSuccess(SmartReplySuggestionResult result) {
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so
// the result doesn't contain any suggestions.
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
//Toast.makeText(MessageAdapter.this,"language not detected...",Toast.LENGTH_SHORT).show();
} else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
// Task completed successfully
// ...
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
int i=0;
String rec1="",rec2="",rec3="";
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
//messageViewHolder.recomandedTextView.setText(replyText);
//chatActivity.recomendation.setText("");
//System.out.println("============================================================="+replyText);
if (myCallback != null && i==0) {
rec1=suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==1) {
rec2= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==2) {
rec3= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
i++;
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
//Toast.makeText(MessageAdapter.this,"Error :"+e,Toast.LENGTH_SHORT).show();
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
}
});
}
else
{
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setBackgroundResource(R.drawable.reciever_messages_layout);
messageViewHolder.receiverMessageText.setTextColor(Color.BLACK);
messageViewHolder.receiverMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
conversation.add(TextMessage.createForRemoteUser(messages.getMessage(), System.currentTimeMillis(), fromUserID));
SmartReplyGenerator smartReply = SmartReply.getClient();
smartReply.suggestReplies(conversation)
.addOnSuccessListener(new OnSuccessListener<SmartReplySuggestionResult>() {
@Override
public void onSuccess(SmartReplySuggestionResult result) {
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so
// the result doesn't contain any suggestions.
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
//Toast.makeText(MessageAdapter.this,"language not detected...",Toast.LENGTH_SHORT).show();
} else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
// Task completed successfully
// ...
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
int i=0;
String rec1="",rec2="",rec3="";
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
//messageViewHolder.recomandedTextView.setText(replyText);
//System.out.println("==========================================="+replyText);
//chatActivity.recomendation.setText("");
if (myCallback != null && i==0) {
rec1= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==1) {
rec2= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==2) {
rec3=suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
i++;
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
//Toast.makeText(MessageAdapter.this,"Error :"+e,Toast.LENGTH_SHORT).show();
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
}
});
}
}else if (fromMessageType.equals("image")){
if (fromUserID.equals(messageSenderId)){
messageViewHolder.messageSenderPicture.setVisibility(View.VISIBLE);
Picasso.get().load(messages.getMessage()).into(messageViewHolder.messageSenderPicture);
}else {
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setVisibility(View.VISIBLE);
Picasso.get().load(messages.getMessage()).into(messageViewHolder.messageReceiverPicture);
}
}else {
if (fromUserID.equals(messageSenderId)){
messageViewHolder.messageSenderPicture.setVisibility(View.VISIBLE);
messageViewHolder.messageSenderPicture.setBackgroundResource(R.drawable.file);
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(userMessagesList.get(position).getMessage()));
messageViewHolder.itemView.getContext().startActivity(intent);
}
});
}else {
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setBackgroundResource(R.drawable.file);
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(userMessagesList.get(position).getMessage()));
messageViewHolder.itemView.getContext().startActivity(intent);
}
});
}
}
}
@Override
public int getItemCount()
{
return userMessagesList.size();
}
}
| UTF-8 | Java | 16,444 | java | MessageAdapter.java | Java | [] | null | [] | package com.example.messaging__application;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.mlkit.nl.smartreply.SmartReply;
import com.google.mlkit.nl.smartreply.SmartReplyGenerator;
import com.google.mlkit.nl.smartreply.SmartReplySuggestion;
import com.google.mlkit.nl.smartreply.SmartReplySuggestionResult;
import com.google.mlkit.nl.smartreply.TextMessage;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>
{
private List<Messages> userMessagesList;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
private ArrayList<TextMessage> conversation = new ArrayList<TextMessage>();
private ChatActivity chatActivity = new ChatActivity();
MyCallback myCallback = null;
public interface MyCallback {
// Declaration of the template function for the interface
public void updateMyText(String rec1,String rec2, String rec3);
}
public MessageAdapter (List<Messages> userMessagesList,MyCallback callback)
{
this.userMessagesList = userMessagesList;
this.myCallback = callback;
}
public class MessageViewHolder extends RecyclerView.ViewHolder
{
public TextView senderMessageText, receiverMessageText,recomandedTextView;
public CircleImageView receiverProfileImage;
public ImageView messageSenderPicture, messageReceiverPicture;
public MessageViewHolder(@NonNull View itemView)
{
super(itemView);
senderMessageText = (TextView) itemView.findViewById(R.id.sender_messsage_text);
receiverMessageText = (TextView) itemView.findViewById(R.id.receiver_message_text);
receiverProfileImage = (CircleImageView) itemView.findViewById(R.id.message_profile_image);
messageReceiverPicture = itemView.findViewById(R.id.message_receiver_image_view);
messageSenderPicture = itemView.findViewById(R.id.message_sender_image_view);
//recomandedTextView = (TextView) itemView.findViewById(R.id.recomanded_text);
}
}
@NonNull
@Override
public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.custom_messages_layout, viewGroup, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final MessageViewHolder messageViewHolder, final int position)
{
String messageSenderId = mAuth.getCurrentUser().getUid();
Messages messages = userMessagesList.get(position);
String fromUserID = messages.getFrom();
String fromMessageType = messages.getType();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
usersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.hasChild("image"))
{
String receiverImage = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(receiverImage).placeholder(R.drawable.profile_image).into(messageViewHolder.receiverProfileImage);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
messageViewHolder.receiverMessageText.setVisibility(View.GONE);
messageViewHolder.receiverProfileImage.setVisibility(View.GONE);
messageViewHolder.senderMessageText.setVisibility(View.GONE);
messageViewHolder.messageSenderPicture.setVisibility(View.GONE);
messageViewHolder.messageReceiverPicture.setVisibility(View.GONE);
if (fromMessageType.equals("text"))
{
if (fromUserID.equals(messageSenderId))
{
messageViewHolder.senderMessageText.setVisibility(View.VISIBLE);
messageViewHolder.senderMessageText.setBackgroundResource(R.drawable.sender_messages_layout);
messageViewHolder.senderMessageText.setTextColor(Color.BLACK);
messageViewHolder.senderMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
conversation.add(TextMessage.createForLocalUser(messages.getMessage(), System.currentTimeMillis()));
SmartReplyGenerator smartReply = SmartReply.getClient();
smartReply.suggestReplies(conversation)
.addOnSuccessListener(new OnSuccessListener<SmartReplySuggestionResult>() {
@Override
public void onSuccess(SmartReplySuggestionResult result) {
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so
// the result doesn't contain any suggestions.
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
//Toast.makeText(MessageAdapter.this,"language not detected...",Toast.LENGTH_SHORT).show();
} else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
// Task completed successfully
// ...
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
int i=0;
String rec1="",rec2="",rec3="";
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
//messageViewHolder.recomandedTextView.setText(replyText);
//chatActivity.recomendation.setText("");
//System.out.println("============================================================="+replyText);
if (myCallback != null && i==0) {
rec1=suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==1) {
rec2= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==2) {
rec3= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
i++;
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
//Toast.makeText(MessageAdapter.this,"Error :"+e,Toast.LENGTH_SHORT).show();
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
}
});
}
else
{
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setBackgroundResource(R.drawable.reciever_messages_layout);
messageViewHolder.receiverMessageText.setTextColor(Color.BLACK);
messageViewHolder.receiverMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
conversation.add(TextMessage.createForRemoteUser(messages.getMessage(), System.currentTimeMillis(), fromUserID));
SmartReplyGenerator smartReply = SmartReply.getClient();
smartReply.suggestReplies(conversation)
.addOnSuccessListener(new OnSuccessListener<SmartReplySuggestionResult>() {
@Override
public void onSuccess(SmartReplySuggestionResult result) {
if (result.getStatus() == SmartReplySuggestionResult.STATUS_NOT_SUPPORTED_LANGUAGE) {
// The conversation's language isn't supported, so
// the result doesn't contain any suggestions.
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
//Toast.makeText(MessageAdapter.this,"language not detected...",Toast.LENGTH_SHORT).show();
} else if (result.getStatus() == SmartReplySuggestionResult.STATUS_SUCCESS) {
// Task completed successfully
// ...
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
int i=0;
String rec1="",rec2="",rec3="";
for (SmartReplySuggestion suggestion : result.getSuggestions()) {
String replyText = suggestion.getText();
//messageViewHolder.recomandedTextView.setText(replyText);
//System.out.println("==========================================="+replyText);
//chatActivity.recomendation.setText("");
if (myCallback != null && i==0) {
rec1= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==1) {
rec2= suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
if (myCallback != null && i==2) {
rec3=suggestion.getText();
myCallback.updateMyText(rec1,rec2,rec3);
}
i++;
}
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
//Toast.makeText(MessageAdapter.this,"Error :"+e,Toast.LENGTH_SHORT).show();
//messageViewHolder.recomandedTextView.setText("");
//chatActivity.recomendation.setText("");
if (myCallback != null) {
myCallback.updateMyText("","","");
}
}
});
}
}else if (fromMessageType.equals("image")){
if (fromUserID.equals(messageSenderId)){
messageViewHolder.messageSenderPicture.setVisibility(View.VISIBLE);
Picasso.get().load(messages.getMessage()).into(messageViewHolder.messageSenderPicture);
}else {
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setVisibility(View.VISIBLE);
Picasso.get().load(messages.getMessage()).into(messageViewHolder.messageReceiverPicture);
}
}else {
if (fromUserID.equals(messageSenderId)){
messageViewHolder.messageSenderPicture.setVisibility(View.VISIBLE);
messageViewHolder.messageSenderPicture.setBackgroundResource(R.drawable.file);
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(userMessagesList.get(position).getMessage()));
messageViewHolder.itemView.getContext().startActivity(intent);
}
});
}else {
messageViewHolder.receiverProfileImage.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setVisibility(View.VISIBLE);
messageViewHolder.messageReceiverPicture.setBackgroundResource(R.drawable.file);
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(userMessagesList.get(position).getMessage()));
messageViewHolder.itemView.getContext().startActivity(intent);
}
});
}
}
}
@Override
public int getItemCount()
{
return userMessagesList.size();
}
}
| 16,444 | 0.522926 | 0.520433 | 396 | 40.522728 | 37.737087 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
adce170a25af3edd2b72b62d4fe1e60b522e5c94 | 15,418,932,616,706 | 267b0e6f352431f047cfa68aa73262184feb6a3c | /app/src/main/java/com/example/yzuapp/MainActivity.java | 9f4245574f9a8fb6003c6e70196e837c533a2028 | [] | no_license | axuy312/YZU_APP_Contest-YZUPass | https://github.com/axuy312/YZU_APP_Contest-YZUPass | d7e3123321f75c3cf88ada4f2f7ddc27cd664430 | 9469c9ad4a79b545802fb10bf3fe73ca869c5d77 | refs/heads/master | 2023-01-09T19:19:26.785000 | 2020-11-09T07:17:53 | 2020-11-09T07:17:53 | 300,938,044 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.yzuapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Source;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button loginButton;
private EditText studentID, cardID;
private NfcAdapter nfcAdapter;
CheckBox remember;
LinearLayout progressBar;
TextInputLayout textInputSid, textInputCardid;
boolean darkTheme;
private String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
//region 設定背景顏色
SharedPreferences preferencesTheme = getSharedPreferences("Theme", MODE_PRIVATE);
darkTheme = preferencesTheme.getBoolean("themeColor", false);
if (darkTheme) {
//dark theme
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
setTheme(R.style.darkTheme);
} else {
//light theme
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setTheme(R.style.AppTheme);
}
//endregion
super.onCreate(savedInstanceState);
//建立View
setContentView(R.layout.activity_main);
//強制螢幕直立
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//get xml file id
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
loginButton = findViewById(R.id.loginBtn);
studentID = findViewById(R.id.input_sid);
cardID = findViewById(R.id.input_card_id);
remember = findViewById(R.id.remember_me);
progressBar = findViewById(R.id.progress_bar);
textInputSid = findViewById(R.id.input_layout_sid);
textInputCardid = findViewById(R.id.input_layout_cid);
//checkbox fill with sid & card id
SharedPreferences preferences = getSharedPreferences("checkbox", MODE_PRIVATE);
String checkbox = preferences.getString("remember", "");
//fill in data
if (checkbox.equals("true")) {
String newSid = preferences.getString("studentid", "");
String newCardid = preferences.getString("cardid", "");
studentID.setText(newSid);
cardID.setText(newCardid);
remember.setChecked(true);
} else if (checkbox.equals("false")) {
remember.setChecked(false);
}
textInputSid.setError(null);
textInputSid.setErrorEnabled(false);
textInputCardid.setError(null);
textInputCardid.setErrorEnabled(false);
//default button
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
if (nfcAdapter == null) {
Toast.makeText(this, "Nfc is not supported on this device", Toast.LENGTH_SHORT).show();
} else if (!nfcAdapter.isEnabled()) {
Toast.makeText(this, "NFC disabled on this device. Turn on to proceed", Toast.LENGTH_SHORT).show();
}
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (validateData()) {
SaveData();
//control place
progressBar.setVisibility(View.VISIBLE);
loginButton.setVisibility(View.GONE);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("----Fail----", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
token = task.getResult().getToken();
login();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Please Connect to Internet.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
//postRequest();
}
}
});
remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SaveData();
}
});
studentID.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateSid();
}
@Override
public void afterTextChanged(Editable s) {
}
});
cardID.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateCid();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
enableForegroundDispatchSystem();
}
}
private void enableForegroundDispatchSystem() {
Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (nfcAdapter == null)
return;
//檢查intent 的行動是否是 ACTION_TAG_DISCOVERED
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
//檢查tag是否是我們的格式
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] paramArrayOfbyte = detectedTag.getId();
long l2 = 0L;
long l1 = 1L;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; ; i++) {
if (i >= paramArrayOfbyte.length)
break;
l2 += (paramArrayOfbyte[i] & 0xFFL) * l1;
l1 *= 256L;
}
cardID.setText(String.valueOf(l2));
}
}
void login() {
final String sid, card;
sid = studentID.getText().toString();
card = cardID.getText().toString();
FirebaseFirestore db = FirebaseFirestore.getInstance();
final CollectionReference userRef = db.collection("User");
userRef.document(card)
.get(Source.SERVER)
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists() && documentSnapshot.get("id").toString().equals(sid)) {
Log.d("----token----", token);
if (!documentSnapshot.contains("token") || documentSnapshot.get("token").toString().equals(token) || documentSnapshot.get("token").toString().equals("empty")) {
userRef.document(card).update("token", token);
Intent intent = new Intent(MainActivity.this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "你的帳號已在其他裝置登入", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
} else {
Toast.makeText(MainActivity.this, "學號或卡號錯誤", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Please Connect to Internet.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
}
/*已棄用
private void postRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "https://script.google.com/macros/s/AKfycbzSq8-oakUqsMBqF8p7lgzbxCFOAtuw0q1i2SC_wrTplvwOEco/exec";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.equals("1")) {
Toast.makeText(MainActivity.this, "登入成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "學號或卡號錯誤", Toast.LENGTH_SHORT).show();
loginButton.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "連線失敗~", Toast.LENGTH_SHORT).show();
loginButton.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("method", "CardIDCheck");
params.put("id", studentID.getText().toString());
params.put("code", cardID.getText().toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
*/
private boolean validateData() {
return (validateSid() && validateCid());
}
private boolean validateSid() {
String tmpSid = studentID.getEditableText().toString();
if (tmpSid.isEmpty()) {
textInputSid.setError("Student Id Cannot be Empty");
return false;
} else {
textInputSid.setError(null);
textInputSid.setErrorEnabled(false);
return true;
}
}
private boolean validateCid() {
String tmpCid = cardID.getText().toString();
if (tmpCid.isEmpty()) {
textInputCardid.setError("Card Id cannot be Empty");
return false;
} else {
textInputCardid.setError(null);
textInputCardid.setErrorEnabled(false);
return true;
}
}
private void SaveData() {
//save student id & card variable
SharedPreferences preferences = getSharedPreferences("checkbox", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (remember.isChecked()) {
editor.putString("remember", "true");
} else {
editor.putString("remember", "false");
}
editor.putString("studentid", studentID.getText().toString());
editor.putString("cardid", cardID.getText().toString());
editor.apply();
}
}
| UTF-8 | Java | 15,224 | java | MainActivity.java | Java | [] | null | [] | package com.example.yzuapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.Source;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private Button loginButton;
private EditText studentID, cardID;
private NfcAdapter nfcAdapter;
CheckBox remember;
LinearLayout progressBar;
TextInputLayout textInputSid, textInputCardid;
boolean darkTheme;
private String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
//region 設定背景顏色
SharedPreferences preferencesTheme = getSharedPreferences("Theme", MODE_PRIVATE);
darkTheme = preferencesTheme.getBoolean("themeColor", false);
if (darkTheme) {
//dark theme
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
setTheme(R.style.darkTheme);
} else {
//light theme
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setTheme(R.style.AppTheme);
}
//endregion
super.onCreate(savedInstanceState);
//建立View
setContentView(R.layout.activity_main);
//強制螢幕直立
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//get xml file id
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
loginButton = findViewById(R.id.loginBtn);
studentID = findViewById(R.id.input_sid);
cardID = findViewById(R.id.input_card_id);
remember = findViewById(R.id.remember_me);
progressBar = findViewById(R.id.progress_bar);
textInputSid = findViewById(R.id.input_layout_sid);
textInputCardid = findViewById(R.id.input_layout_cid);
//checkbox fill with sid & card id
SharedPreferences preferences = getSharedPreferences("checkbox", MODE_PRIVATE);
String checkbox = preferences.getString("remember", "");
//fill in data
if (checkbox.equals("true")) {
String newSid = preferences.getString("studentid", "");
String newCardid = preferences.getString("cardid", "");
studentID.setText(newSid);
cardID.setText(newCardid);
remember.setChecked(true);
} else if (checkbox.equals("false")) {
remember.setChecked(false);
}
textInputSid.setError(null);
textInputSid.setErrorEnabled(false);
textInputCardid.setError(null);
textInputCardid.setErrorEnabled(false);
//default button
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
if (nfcAdapter == null) {
Toast.makeText(this, "Nfc is not supported on this device", Toast.LENGTH_SHORT).show();
} else if (!nfcAdapter.isEnabled()) {
Toast.makeText(this, "NFC disabled on this device. Turn on to proceed", Toast.LENGTH_SHORT).show();
}
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (validateData()) {
SaveData();
//control place
progressBar.setVisibility(View.VISIBLE);
loginButton.setVisibility(View.GONE);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("----Fail----", "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
token = task.getResult().getToken();
login();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Please Connect to Internet.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
//postRequest();
}
}
});
remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SaveData();
}
});
studentID.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateSid();
}
@Override
public void afterTextChanged(Editable s) {
}
});
cardID.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
validateCid();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
@Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
enableForegroundDispatchSystem();
}
}
private void enableForegroundDispatchSystem() {
Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] intentFilters = new IntentFilter[]{};
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (nfcAdapter == null)
return;
//檢查intent 的行動是否是 ACTION_TAG_DISCOVERED
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
//檢查tag是否是我們的格式
Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] paramArrayOfbyte = detectedTag.getId();
long l2 = 0L;
long l1 = 1L;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; ; i++) {
if (i >= paramArrayOfbyte.length)
break;
l2 += (paramArrayOfbyte[i] & 0xFFL) * l1;
l1 *= 256L;
}
cardID.setText(String.valueOf(l2));
}
}
void login() {
final String sid, card;
sid = studentID.getText().toString();
card = cardID.getText().toString();
FirebaseFirestore db = FirebaseFirestore.getInstance();
final CollectionReference userRef = db.collection("User");
userRef.document(card)
.get(Source.SERVER)
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists() && documentSnapshot.get("id").toString().equals(sid)) {
Log.d("----token----", token);
if (!documentSnapshot.contains("token") || documentSnapshot.get("token").toString().equals(token) || documentSnapshot.get("token").toString().equals("empty")) {
userRef.document(card).update("token", token);
Intent intent = new Intent(MainActivity.this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "你的帳號已在其他裝置登入", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
} else {
Toast.makeText(MainActivity.this, "學號或卡號錯誤", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Please Connect to Internet.", Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
loginButton.setVisibility(View.VISIBLE);
}
});
}
/*已棄用
private void postRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "https://script.google.com/macros/s/AKfycbzSq8-oakUqsMBqF8p7lgzbxCFOAtuw0q1i2SC_wrTplvwOEco/exec";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.equals("1")) {
Toast.makeText(MainActivity.this, "登入成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "學號或卡號錯誤", Toast.LENGTH_SHORT).show();
loginButton.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "連線失敗~", Toast.LENGTH_SHORT).show();
loginButton.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("method", "CardIDCheck");
params.put("id", studentID.getText().toString());
params.put("code", cardID.getText().toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
requestQueue.add(stringRequest);
}
*/
private boolean validateData() {
return (validateSid() && validateCid());
}
private boolean validateSid() {
String tmpSid = studentID.getEditableText().toString();
if (tmpSid.isEmpty()) {
textInputSid.setError("Student Id Cannot be Empty");
return false;
} else {
textInputSid.setError(null);
textInputSid.setErrorEnabled(false);
return true;
}
}
private boolean validateCid() {
String tmpCid = cardID.getText().toString();
if (tmpCid.isEmpty()) {
textInputCardid.setError("Card Id cannot be Empty");
return false;
} else {
textInputCardid.setError(null);
textInputCardid.setErrorEnabled(false);
return true;
}
}
private void SaveData() {
//save student id & card variable
SharedPreferences preferences = getSharedPreferences("checkbox", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (remember.isChecked()) {
editor.putString("remember", "true");
} else {
editor.putString("remember", "false");
}
editor.putString("studentid", studentID.getText().toString());
editor.putString("cardid", cardID.getText().toString());
editor.apply();
}
}
| 15,224 | 0.591741 | 0.590282 | 397 | 37 | 29.650866 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670025 | false | false | 13 |
05f0c5bd71019829e63549f2eec577708fc7491d | 33,784,212,759,857 | 0772461dcf3fb50818a9eb3792faccbeb0fb9798 | /Submission6/collections/Queue.java | 34001032f84d382e3eddb82cc804838f0d283e87 | [] | no_license | YurDal/Java | https://github.com/YurDal/Java | a4652c46c633b39909a07fd3b4f8f6234ed869d1 | aea747681cf54340d0cb5b5b913aca2a75a0e690 | refs/heads/master | 2020-03-27T16:06:39.467000 | 2018-08-30T15:20:05 | 2018-08-30T15:20:05 | 146,759,942 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package collections;
public interface Queue<E> {
/**
* Inserts the specified element into this queue.
*
* @param data
* the object to add
* @throws QueueException
* if the element cannot be added at this time due to capacity
* restrictions
*/
public void enqueue(E data);
/**
* Retrieves and removes the head of this queue.
*
* @return the head of this queue
* @throws QueueException
* if this queue is empty
*/
public E dequeue();
/**
* Retrieves, but does not remove, the head of this queue.
*
* @return the head of this queue
* @throws QueueException
* if this queue is empty
*/
public E peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if this stack contains no elements
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in this stack
*/
public int size();
}
| UTF-8 | Java | 996 | java | Queue.java | Java | [] | null | [] | package collections;
public interface Queue<E> {
/**
* Inserts the specified element into this queue.
*
* @param data
* the object to add
* @throws QueueException
* if the element cannot be added at this time due to capacity
* restrictions
*/
public void enqueue(E data);
/**
* Retrieves and removes the head of this queue.
*
* @return the head of this queue
* @throws QueueException
* if this queue is empty
*/
public E dequeue();
/**
* Retrieves, but does not remove, the head of this queue.
*
* @return the head of this queue
* @throws QueueException
* if this queue is empty
*/
public E peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if this stack contains no elements
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in this stack
*/
public int size();
}
| 996 | 0.619478 | 0.619478 | 47 | 20.19149 | 19.598782 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.978723 | false | false | 13 |
153a70a934f17e2658cf0f5c6be4e98dcdcf3865 | 28,810,640,683,884 | 4991436c2b266b2892363b4e8d421247a8d29c6e | /checkstyle/src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/linelength/InputLineLengthLongLink.java | c3acd4e189d4f37f030ff98ba5c3040bba4dda86 | [
"Apache-2.0"
] | permissive | spoole167/java-static-analysis-samples | https://github.com/spoole167/java-static-analysis-samples | d9f970104bb69abb968e0ecf09c11aa25c364ebd | 880f9b394e531d8c03af425b1b4e5a95302a3359 | refs/heads/main | 2023-08-14T22:26:12.012000 | 2021-09-15T05:50:20 | 2021-09-15T05:50:20 | 406,629,824 | 0 | 0 | Apache-2.0 | true | 2021-09-15T05:49:41 | 2021-09-15T05:49:41 | 2021-09-14T14:23:13 | 2021-09-14T14:23:10 | 5 | 0 | 0 | 0 | null | false | false | /*
LineLength
fileExtensions = (default)all files
ignorePattern = ^ *\\* *([^ ]+|\\{@code .*|<a href="[^"]+">)$
max = (default)80
*/
package com.puppycrawl.tools.checkstyle.checks.sizes.linelength;
/**
* <a href="a long string that has exceeded the 80 character per line limit">with inline title</a> // violation
* <a href="another long string that has exceeded the 80 character per line limit">
* with wrapped title</a>
*/
public class InputLineLengthLongLink {
}
| UTF-8 | Java | 473 | java | InputLineLengthLongLink.java | Java | [] | null | [] | /*
LineLength
fileExtensions = (default)all files
ignorePattern = ^ *\\* *([^ ]+|\\{@code .*|<a href="[^"]+">)$
max = (default)80
*/
package com.puppycrawl.tools.checkstyle.checks.sizes.linelength;
/**
* <a href="a long string that has exceeded the 80 character per line limit">with inline title</a> // violation
* <a href="another long string that has exceeded the 80 character per line limit">
* with wrapped title</a>
*/
public class InputLineLengthLongLink {
}
| 473 | 0.687104 | 0.674419 | 18 | 25.277779 | 32.690136 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 13 |
55ad4026848838aa1aa3c1435b9648a44be0cbad | 24,103,356,507,067 | c13dad398321d83618daa0ccfca3e74fdbe8610c | /src/main/java/po/NewMailPage.java | cb1a81443202061eb559629693fffc1f0eea983b | [] | no_license | Ivanka10/testMail | https://github.com/Ivanka10/testMail | 0d05492c1917816d7820734f77b9e08ef0ff16ab | 699a0ac540010b031001cbc8f6318a2c7c4b8231 | refs/heads/master | 2021-12-15T01:58:59.161000 | 2020-03-29T22:07:01 | 2020-03-29T22:07:01 | 244,992,296 | 0 | 0 | null | false | 2021-12-14T21:41:39 | 2020-03-04T20:01:16 | 2020-03-29T22:07:18 | 2021-12-14T21:41:39 | 11,309 | 0 | 0 | 6 | Java | false | false | package po;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class NewMailPage extends BasePage {
@FindBy(name = "toFieldInput")
private WebElement receiverField;
@FindBy(name = "subject")
private WebElement subjectField;
@FindBy(xpath = "//button[@class='default send']")
private WebElement sendBtn;
@FindBy(xpath = "//body[contains(@class, 'content')]")
private WebElement messageBody;
private final String FRAME = "mce_0_ifr";
NewMailPage(WebDriver driver) {
super(driver);
}
public NewMailPage inputSubject(String subject) {
waitForElement(subjectField);
subjectField.sendKeys(subject);
return this;
}
public NewMailPage inputReceiver(String receiver) {
waitForElement(receiverField);
receiverField.sendKeys(receiver);
return this;
}
public NewMailPage inputMessage(String message) {
driver.switchTo().frame(FRAME);
waitForElement(messageBody);
messageBody.sendKeys(message);
driver.switchTo().defaultContent();
return this;
}
public HomePage clickSendBtn() {
waitForElementToBeClickable(sendBtn, 5);
sendBtn.click();
return new HomePage(driver);
}
}
| UTF-8 | Java | 1,341 | java | NewMailPage.java | Java | [] | null | [] | package po;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class NewMailPage extends BasePage {
@FindBy(name = "toFieldInput")
private WebElement receiverField;
@FindBy(name = "subject")
private WebElement subjectField;
@FindBy(xpath = "//button[@class='default send']")
private WebElement sendBtn;
@FindBy(xpath = "//body[contains(@class, 'content')]")
private WebElement messageBody;
private final String FRAME = "mce_0_ifr";
NewMailPage(WebDriver driver) {
super(driver);
}
public NewMailPage inputSubject(String subject) {
waitForElement(subjectField);
subjectField.sendKeys(subject);
return this;
}
public NewMailPage inputReceiver(String receiver) {
waitForElement(receiverField);
receiverField.sendKeys(receiver);
return this;
}
public NewMailPage inputMessage(String message) {
driver.switchTo().frame(FRAME);
waitForElement(messageBody);
messageBody.sendKeys(message);
driver.switchTo().defaultContent();
return this;
}
public HomePage clickSendBtn() {
waitForElementToBeClickable(sendBtn, 5);
sendBtn.click();
return new HomePage(driver);
}
}
| 1,341 | 0.66965 | 0.668158 | 52 | 24.788462 | 19.126438 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
6a74307d3ba0743d0d2b545feb6cb02c6c5d5d7b | 31,679,678,815,298 | 0b739b7e3a7dd7398f790f644b5ea99e4d1d4375 | /app/src/main/java/net/squanchy/favorites/view/FavoritesSignedInEmptyLayout.java | ba5c7149cbe18ce47b477708cd52aa1ac0f45610 | [
"Apache-2.0"
] | permissive | haikuowuya/squanchy-android | https://github.com/haikuowuya/squanchy-android | 328e810327872f6f7b240f5e5010ad99a8de5403 | 7ec5c616f1413cba93204da4b9ff832549c6a8e3 | refs/heads/develop | 2020-12-02T22:11:05.708000 | 2017-06-08T11:16:09 | 2017-06-08T11:16:09 | 96,092,300 | 1 | 0 | null | true | 2017-07-03T09:10:12 | 2017-07-03T09:10:12 | 2017-07-03T09:10:12 | 2017-06-28T17:23:05 | 22,233 | 0 | 0 | 0 | null | null | null | package net.squanchy.favorites.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import net.squanchy.R;
public class FavoritesSignedInEmptyLayout extends LinearLayout {
private static final int TAPS_TO_TRIGGER_INITIAL_ACHIEVEMENT = 5;
private static final int TAPS_TO_TRIGGER_PERSEVERANCE_ACHIEVEMENT = 15;
private FloatingActionButton favoriteButton;
public FavoritesSignedInEmptyLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public FavoritesSignedInEmptyLayout(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOrientation(VERTICAL);
}
@Override
public void setOrientation(int orientation) {
throw new UnsupportedOperationException("Changing orientation is not supported for " + FavoritesSignedInEmptyLayout.class.getSimpleName());
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
favoriteButton = (FloatingActionButton) findViewById(R.id.favorite_fab_example);
favoriteButton.setOnClickListener(achievementAwardingClickListener());
}
private OnClickListener achievementAwardingClickListener() {
return new OnClickListener() {
private int counter;
@Override
public void onClick(View view) {
favoriteButton.setImageResource(
counter % 2 == 0
? R.drawable.ic_favorite_filled
: R.drawable.ic_favorite_empty
);
counter++;
if (counter == TAPS_TO_TRIGGER_INITIAL_ACHIEVEMENT) {
showAchievement(R.string.favorites_achievement_fast_learner);
} else if (counter == TAPS_TO_TRIGGER_PERSEVERANCE_ACHIEVEMENT) {
showAchievement(R.string.favorites_achievement_persevering);
favoriteButton.setEnabled(false);
}
}
private void showAchievement(int stringResId) {
Snackbar.make(FavoritesSignedInEmptyLayout.this, readAsHtml(stringResId), Snackbar.LENGTH_LONG).show();
}
private CharSequence readAsHtml(int stringResId) {
String text = favoriteButton.getResources().getString(stringResId);
return Html.fromHtml(text);
}
};
}
}
| UTF-8 | Java | 2,723 | java | FavoritesSignedInEmptyLayout.java | Java | [] | null | [] | package net.squanchy.favorites.view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import net.squanchy.R;
public class FavoritesSignedInEmptyLayout extends LinearLayout {
private static final int TAPS_TO_TRIGGER_INITIAL_ACHIEVEMENT = 5;
private static final int TAPS_TO_TRIGGER_PERSEVERANCE_ACHIEVEMENT = 15;
private FloatingActionButton favoriteButton;
public FavoritesSignedInEmptyLayout(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public FavoritesSignedInEmptyLayout(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOrientation(VERTICAL);
}
@Override
public void setOrientation(int orientation) {
throw new UnsupportedOperationException("Changing orientation is not supported for " + FavoritesSignedInEmptyLayout.class.getSimpleName());
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
favoriteButton = (FloatingActionButton) findViewById(R.id.favorite_fab_example);
favoriteButton.setOnClickListener(achievementAwardingClickListener());
}
private OnClickListener achievementAwardingClickListener() {
return new OnClickListener() {
private int counter;
@Override
public void onClick(View view) {
favoriteButton.setImageResource(
counter % 2 == 0
? R.drawable.ic_favorite_filled
: R.drawable.ic_favorite_empty
);
counter++;
if (counter == TAPS_TO_TRIGGER_INITIAL_ACHIEVEMENT) {
showAchievement(R.string.favorites_achievement_fast_learner);
} else if (counter == TAPS_TO_TRIGGER_PERSEVERANCE_ACHIEVEMENT) {
showAchievement(R.string.favorites_achievement_persevering);
favoriteButton.setEnabled(false);
}
}
private void showAchievement(int stringResId) {
Snackbar.make(FavoritesSignedInEmptyLayout.this, readAsHtml(stringResId), Snackbar.LENGTH_LONG).show();
}
private CharSequence readAsHtml(int stringResId) {
String text = favoriteButton.getResources().getString(stringResId);
return Html.fromHtml(text);
}
};
}
}
| 2,723 | 0.658098 | 0.655894 | 76 | 34.828949 | 32.678814 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513158 | false | false | 13 |
df9ba03fd1599e60e87a40698bd422934db4e89c | 27,659,589,417,733 | 6c8e077c219a94497faef3678df5c25764e8f9c9 | /bll2/src/main/java/com/maoding/project/entity/ProjectEntity.java | 7a1a798aa7c8694193009a374ee1d523277f66c9 | [] | no_license | chengliangzhang/maoding-web | https://github.com/chengliangzhang/maoding-web | af30195f42de58191fb704bd9bb71a88ebd6e53c | acc39723ffe897f7ec5baa2c009642386acbbeaa | refs/heads/master | 2021-05-02T12:48:12.210000 | 2018-09-26T06:49:14 | 2018-09-26T06:49:14 | 120,746,771 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.maoding.project.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.maoding.core.base.entity.BaseEntity;
import org.springframework.format.annotation.DateTimeFormat;
import java.math.BigDecimal;
import java.util.Date;
/**
* 深圳市设计同道技术有限公司
* 类 名:ProjectEntity
* 类描述:权限实体
* 作 者:ChenZJ
* 日 期:2016年7月19日-下午4:11:50
*/
public class ProjectEntity extends BaseEntity {
/**
* 企业id
*/
private String companyId;
/**
* 乙方
*/
private String companyBid;
/**
* 项目类别(冗余,目前没用到)
*/
private String projectType;
/**
* 建筑功能
*/
private String builtType;
/**
* 项目编号
*/
private String projectNo;
/**
* 项目名称
*/
private String projectName;
/**
* 基地面积
*/
private String baseArea;
/**
* 计容面积
*/
private String capacityArea;
/**
* 总建筑面积
*/
private String totalConstructionArea;
/**
* 核增面积
*/
private String increasingArea;
/**
* 覆盖率
*/
private String coverage;
/**
* 绿化率
*/
private String greeningRate;
/**
* 建筑高度
*/
private String builtHeight;
/**
* 建筑层数(地上)
*/
private String builtFloorUp;
/**
* 建筑层数(地下)
*/
private String builtFloorDown;
/**
* 建设单位
*/
private String constructCompany;
/**
* 投资估算
*/
private BigDecimal investmentEstimation;
/**
* 合同总金额
*/
private BigDecimal totalContractAmount;
/**
* 默认为0(1=拟定,2=评审,3=备案,4.签发管理任务书,5.签发设计任务书)
*/
private String status;
/**
* 0=生效,1=不生效
*/
private String pstatus;
/**
* 合同附件
*/
private String contractAttachment;
/**
* 是否是历史数据导入
*/
private Integer isHistory;
/**
* 设计范围
*/
private String designRange;
/**
* 合同签订日期
*/
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date contractDate;
/**
* 立项日期
*/
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date projectCreateDate;
/**
*
*/
private String parentProjectid;
/**
* 企业所属省
*/
private String province;
/**
* 企业所属市
*/
private String city;
/**
* 企业所属县或区或镇
*/
private String county;
/**
* 详细地址
*/
private String detailAddress;
/**
* 容积率
*/
private String volumeRatio;
/**
* 帮助立项的人的id(company_user_id)
*/
private String helperCompanyUserId;
public ProjectEntity() {
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyBid() {
return companyBid;
}
public void setCompanyBid(String companyBid) {
this.companyBid = companyBid;
}
public String getProjectType() {
return projectType;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public String getBuiltType() {
return builtType;
}
public void setBuiltType(String builtType) {
this.builtType = builtType;
}
public String getProjectNo() {
return projectNo;
}
public void setProjectNo(String projectNo) {
this.projectNo = projectNo;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getBaseArea() {
return baseArea;
}
public void setBaseArea(String baseArea) {
this.baseArea = baseArea;
}
public String getCapacityArea() {
return capacityArea;
}
public void setCapacityArea(String capacityArea) {
this.capacityArea = capacityArea;
}
public String getTotalConstructionArea() {
return totalConstructionArea;
}
public void setTotalConstructionArea(String totalConstructionArea) {
this.totalConstructionArea = totalConstructionArea;
}
public String getIncreasingArea() {
return increasingArea;
}
public void setIncreasingArea(String increasingArea) {
this.increasingArea = increasingArea;
}
public String getCoverage() {
return coverage;
}
public void setCoverage(String coverage) {
this.coverage = coverage;
}
public String getGreeningRate() {
return greeningRate;
}
public void setGreeningRate(String greeningRate) {
this.greeningRate = greeningRate;
}
public String getBuiltHeight() {
return builtHeight;
}
public void setBuiltHeight(String builtHeight) {
this.builtHeight = builtHeight;
}
public String getBuiltFloorUp() {
return builtFloorUp;
}
public void setBuiltFloorUp(String builtFloorUp) {
this.builtFloorUp = builtFloorUp;
}
public String getBuiltFloorDown() {
return builtFloorDown;
}
public void setBuiltFloorDown(String builtFloorDown) {
this.builtFloorDown = builtFloorDown;
}
public String getConstructCompany() {
return constructCompany;
}
public void setConstructCompany(String constructCompany) {
this.constructCompany = constructCompany;
}
public BigDecimal getInvestmentEstimation() {
return investmentEstimation;
}
public void setInvestmentEstimation(BigDecimal investmentEstimation) {
this.investmentEstimation = investmentEstimation;
}
public BigDecimal getTotalContractAmount() {
return totalContractAmount;
}
public void setTotalContractAmount(BigDecimal totalContractAmount) {
this.totalContractAmount = totalContractAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPstatus() {
return pstatus;
}
public void setPstatus(String pstatus) {
this.pstatus = pstatus;
}
public String getContractAttachment() {
return contractAttachment;
}
public void setContractAttachment(String contractAttachment) {
this.contractAttachment = contractAttachment;
}
public Integer getIsHistory() {
return isHistory;
}
public void setIsHistory(Integer isHistory) {
this.isHistory = isHistory;
}
public String getDesignRange() {
return designRange;
}
public void setDesignRange(String designRange) {
this.designRange = designRange;
}
public Date getContractDate() {
return contractDate;
}
public void setContractDate(Date contractDate) {
this.contractDate = contractDate;
}
public String getParentProjectid() {
return parentProjectid;
}
public void setParentProjectid(String parentProjectid) {
this.parentProjectid = parentProjectid;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getVolumeRatio() {
return volumeRatio;
}
public void setVolumeRatio(String volumeRatio) {
this.volumeRatio = volumeRatio;
}
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getHelperCompanyUserId() {
return helperCompanyUserId;
}
public void setHelperCompanyUserId(String helperCompanyUserId) {
this.helperCompanyUserId = helperCompanyUserId;
}
public Date getProjectCreateDate() {
return projectCreateDate;
}
public void setProjectCreateDate(Date projectCreateDate) {
this.projectCreateDate = projectCreateDate;
}
}
| UTF-8 | Java | 9,293 | java | ProjectEntity.java | Java | [
{
"context": "\r\n * 类 名:ProjectEntity\r\n * 类描述:权限实体\r\n * 作 者:ChenZJ\r\n * 日 期:2016年7月19日-下午4:11:50\r\n */\r\npublic clas",
"end": 338,
"score": 0.9933142066001892,
"start": 332,
"tag": "USERNAME",
"value": "ChenZJ"
}
] | null | [] | package com.maoding.project.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.maoding.core.base.entity.BaseEntity;
import org.springframework.format.annotation.DateTimeFormat;
import java.math.BigDecimal;
import java.util.Date;
/**
* 深圳市设计同道技术有限公司
* 类 名:ProjectEntity
* 类描述:权限实体
* 作 者:ChenZJ
* 日 期:2016年7月19日-下午4:11:50
*/
public class ProjectEntity extends BaseEntity {
/**
* 企业id
*/
private String companyId;
/**
* 乙方
*/
private String companyBid;
/**
* 项目类别(冗余,目前没用到)
*/
private String projectType;
/**
* 建筑功能
*/
private String builtType;
/**
* 项目编号
*/
private String projectNo;
/**
* 项目名称
*/
private String projectName;
/**
* 基地面积
*/
private String baseArea;
/**
* 计容面积
*/
private String capacityArea;
/**
* 总建筑面积
*/
private String totalConstructionArea;
/**
* 核增面积
*/
private String increasingArea;
/**
* 覆盖率
*/
private String coverage;
/**
* 绿化率
*/
private String greeningRate;
/**
* 建筑高度
*/
private String builtHeight;
/**
* 建筑层数(地上)
*/
private String builtFloorUp;
/**
* 建筑层数(地下)
*/
private String builtFloorDown;
/**
* 建设单位
*/
private String constructCompany;
/**
* 投资估算
*/
private BigDecimal investmentEstimation;
/**
* 合同总金额
*/
private BigDecimal totalContractAmount;
/**
* 默认为0(1=拟定,2=评审,3=备案,4.签发管理任务书,5.签发设计任务书)
*/
private String status;
/**
* 0=生效,1=不生效
*/
private String pstatus;
/**
* 合同附件
*/
private String contractAttachment;
/**
* 是否是历史数据导入
*/
private Integer isHistory;
/**
* 设计范围
*/
private String designRange;
/**
* 合同签订日期
*/
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date contractDate;
/**
* 立项日期
*/
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
private Date projectCreateDate;
/**
*
*/
private String parentProjectid;
/**
* 企业所属省
*/
private String province;
/**
* 企业所属市
*/
private String city;
/**
* 企业所属县或区或镇
*/
private String county;
/**
* 详细地址
*/
private String detailAddress;
/**
* 容积率
*/
private String volumeRatio;
/**
* 帮助立项的人的id(company_user_id)
*/
private String helperCompanyUserId;
public ProjectEntity() {
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getCompanyBid() {
return companyBid;
}
public void setCompanyBid(String companyBid) {
this.companyBid = companyBid;
}
public String getProjectType() {
return projectType;
}
public void setProjectType(String projectType) {
this.projectType = projectType;
}
public String getBuiltType() {
return builtType;
}
public void setBuiltType(String builtType) {
this.builtType = builtType;
}
public String getProjectNo() {
return projectNo;
}
public void setProjectNo(String projectNo) {
this.projectNo = projectNo;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getBaseArea() {
return baseArea;
}
public void setBaseArea(String baseArea) {
this.baseArea = baseArea;
}
public String getCapacityArea() {
return capacityArea;
}
public void setCapacityArea(String capacityArea) {
this.capacityArea = capacityArea;
}
public String getTotalConstructionArea() {
return totalConstructionArea;
}
public void setTotalConstructionArea(String totalConstructionArea) {
this.totalConstructionArea = totalConstructionArea;
}
public String getIncreasingArea() {
return increasingArea;
}
public void setIncreasingArea(String increasingArea) {
this.increasingArea = increasingArea;
}
public String getCoverage() {
return coverage;
}
public void setCoverage(String coverage) {
this.coverage = coverage;
}
public String getGreeningRate() {
return greeningRate;
}
public void setGreeningRate(String greeningRate) {
this.greeningRate = greeningRate;
}
public String getBuiltHeight() {
return builtHeight;
}
public void setBuiltHeight(String builtHeight) {
this.builtHeight = builtHeight;
}
public String getBuiltFloorUp() {
return builtFloorUp;
}
public void setBuiltFloorUp(String builtFloorUp) {
this.builtFloorUp = builtFloorUp;
}
public String getBuiltFloorDown() {
return builtFloorDown;
}
public void setBuiltFloorDown(String builtFloorDown) {
this.builtFloorDown = builtFloorDown;
}
public String getConstructCompany() {
return constructCompany;
}
public void setConstructCompany(String constructCompany) {
this.constructCompany = constructCompany;
}
public BigDecimal getInvestmentEstimation() {
return investmentEstimation;
}
public void setInvestmentEstimation(BigDecimal investmentEstimation) {
this.investmentEstimation = investmentEstimation;
}
public BigDecimal getTotalContractAmount() {
return totalContractAmount;
}
public void setTotalContractAmount(BigDecimal totalContractAmount) {
this.totalContractAmount = totalContractAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPstatus() {
return pstatus;
}
public void setPstatus(String pstatus) {
this.pstatus = pstatus;
}
public String getContractAttachment() {
return contractAttachment;
}
public void setContractAttachment(String contractAttachment) {
this.contractAttachment = contractAttachment;
}
public Integer getIsHistory() {
return isHistory;
}
public void setIsHistory(Integer isHistory) {
this.isHistory = isHistory;
}
public String getDesignRange() {
return designRange;
}
public void setDesignRange(String designRange) {
this.designRange = designRange;
}
public Date getContractDate() {
return contractDate;
}
public void setContractDate(Date contractDate) {
this.contractDate = contractDate;
}
public String getParentProjectid() {
return parentProjectid;
}
public void setParentProjectid(String parentProjectid) {
this.parentProjectid = parentProjectid;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getVolumeRatio() {
return volumeRatio;
}
public void setVolumeRatio(String volumeRatio) {
this.volumeRatio = volumeRatio;
}
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getHelperCompanyUserId() {
return helperCompanyUserId;
}
public void setHelperCompanyUserId(String helperCompanyUserId) {
this.helperCompanyUserId = helperCompanyUserId;
}
public Date getProjectCreateDate() {
return projectCreateDate;
}
public void setProjectCreateDate(Date projectCreateDate) {
this.projectCreateDate = projectCreateDate;
}
}
| 9,293 | 0.584019 | 0.58154 | 441 | 18.120182 | 18.499165 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.235828 | false | false | 13 |
2522f0129cb61977af24dfc4130453a119cfbafe | 26,225,070,326,301 | 648f64c6707e3b422b3d37798692501b052e7b3f | /src/be/vdab/Main.java | c85041bdd0083ab71bd1853d7f7f8d31c40cc251 | [] | no_license | NickMeeus/KleinsteOppervlakte | https://github.com/NickMeeus/KleinsteOppervlakte | ef2c1328f9f50e4f6ba7602056772fb94318e3e1 | df81ce91c9e463580baa600dab0b2f9eaaf0e795 | refs/heads/master | 2016-08-12T15:56:23.445000 | 2016-02-18T15:12:16 | 2016-02-18T15:12:16 | 52,015,967 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.vdab;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
class Rechthoek {
private final int lengte;
private final int breedte;
public Rechthoek(int lengte, int breedte) {
this.lengte = lengte;
this.breedte = breedte;
}
public int getOppervlakte() { return lengte * breedte; }
@Override
public String toString() {
return lengte + " op " + breedte;
}
}
public class Main {
public static void main(String[] args) {
List<Rechthoek> rechthoeken = Arrays.asList(new Rechthoek(6, 2), new Rechthoek(3, 1), new Rechthoek(1, 3));
OptionalInt kleinsteOppervlakte = rechthoeken.stream().mapToInt(rechthoek -> rechthoek.getOppervlakte()).min();
kleinsteOppervlakte.ifPresent(oppervlakte -> { System.out.println(oppervlakte);
rechthoeken.stream().filter(rechthoek -> rechthoek.getOppervlakte() == oppervlakte).forEach(rechthoek -> System.out.println(rechthoek));});
}
}
| UTF-8 | Java | 1,089 | java | Main.java | Java | [] | null | [] | package be.vdab;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
class Rechthoek {
private final int lengte;
private final int breedte;
public Rechthoek(int lengte, int breedte) {
this.lengte = lengte;
this.breedte = breedte;
}
public int getOppervlakte() { return lengte * breedte; }
@Override
public String toString() {
return lengte + " op " + breedte;
}
}
public class Main {
public static void main(String[] args) {
List<Rechthoek> rechthoeken = Arrays.asList(new Rechthoek(6, 2), new Rechthoek(3, 1), new Rechthoek(1, 3));
OptionalInt kleinsteOppervlakte = rechthoeken.stream().mapToInt(rechthoek -> rechthoek.getOppervlakte()).min();
kleinsteOppervlakte.ifPresent(oppervlakte -> { System.out.println(oppervlakte);
rechthoeken.stream().filter(rechthoek -> rechthoek.getOppervlakte() == oppervlakte).forEach(rechthoek -> System.out.println(rechthoek));});
}
}
| 1,089 | 0.62259 | 0.61708 | 31 | 33.129032 | 42.540867 | 195 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.677419 | false | false | 13 |
d02532f4d40efc19f5b18b16010a3dbd047987ca | 31,945,966,765,508 | 3064ff81779c15871b92dc440ffb36b8ffb3c27f | /src/main/java/ru/cherkovskiy/domain/statistics/AggregationStat.java | b1c646e8082ed3a8db14cc886a58f6b47e71e054 | [] | no_license | cherkovskiyandrey/http-to-jms-proxy | https://github.com/cherkovskiyandrey/http-to-jms-proxy | 415da6511cad1aa171a25870b8e0ae345848f89d | b2741fdfb7ce8b4fe5530da7f1f21e5716aa84d8 | refs/heads/master | 2021-01-20T13:26:21.867000 | 2017-05-07T08:29:56 | 2017-05-07T08:29:56 | 90,489,948 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.cherkovskiy.domain.statistics;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AggregationStat {
@JsonProperty("success")
private final long successAmount;
@JsonProperty("process")
private final long inProgressAmount;
@JsonProperty("error")
private final long errorAmount;
public AggregationStat(long successAmount, long inProgressAmount, long errorAmount) {
this.successAmount = successAmount;
this.inProgressAmount = inProgressAmount;
this.errorAmount = errorAmount;
}
public long getSuccessAmount() {
return successAmount;
}
public long getInProgressAmount() {
return inProgressAmount;
}
public long getErrorAmount() {
return errorAmount;
}
@Override
public String toString() {
return "ServerStatus{" +
"successAmount=" + successAmount +
", inProgressAmount=" + inProgressAmount +
", errorAmount=" + errorAmount +
'}';
}
}
| UTF-8 | Java | 1,053 | java | AggregationStat.java | Java | [
{
"context": "package ru.cherkovskiy.domain.statistics;\n\nimport com.fasterxml.jack",
"end": 18,
"score": 0.8003369569778442,
"start": 11,
"tag": "USERNAME",
"value": "cherkov"
}
] | null | [] | package ru.cherkovskiy.domain.statistics;
import com.fasterxml.jackson.annotation.JsonProperty;
public class AggregationStat {
@JsonProperty("success")
private final long successAmount;
@JsonProperty("process")
private final long inProgressAmount;
@JsonProperty("error")
private final long errorAmount;
public AggregationStat(long successAmount, long inProgressAmount, long errorAmount) {
this.successAmount = successAmount;
this.inProgressAmount = inProgressAmount;
this.errorAmount = errorAmount;
}
public long getSuccessAmount() {
return successAmount;
}
public long getInProgressAmount() {
return inProgressAmount;
}
public long getErrorAmount() {
return errorAmount;
}
@Override
public String toString() {
return "ServerStatus{" +
"successAmount=" + successAmount +
", inProgressAmount=" + inProgressAmount +
", errorAmount=" + errorAmount +
'}';
}
}
| 1,053 | 0.645774 | 0.645774 | 41 | 24.682926 | 20.891636 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.390244 | false | false | 13 |
ef7fa929f0cdff9027655bc7b3a516f57915e4f4 | 31,945,966,766,082 | 66090827886d1d495df9dfecb2611321ded1b119 | /app/src/main/java/com/example/student001/sc2/WebActivity.java | c1bd1c6cb49207607ffadfbc0edd66462a627ade | [] | no_license | masa1217a/Schoolsns | https://github.com/masa1217a/Schoolsns | 7f6d6824b9c0847f67e59af9bed1f07e59c1e9ca | 479508b51a7583df6dec45ece8828ad1be9c7628 | refs/heads/master | 2021-01-10T07:21:10.948000 | 2016-03-08T22:56:54 | 2016-03-08T22:56:54 | 53,361,133 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.student001.sc2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/**
* Created by Nyamura on 2016/02/15.
*/
public class WebActivity extends Activity{
private static final String TAG = WebActivity.class.getSimpleName();
private final WebActivity self = this;
//WebView
private WebView mWebView;
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mWebView = (WebView)findViewById(R.id.webView);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings();
mWebView.loadUrl("http://www3.jeed.or.jp/miyagi/college/admission/opencampus.html");
mWebView.getSettings().setJavaScriptEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.return_botton, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_return){
Intent intent = new Intent(this, Top.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy(){
super.onDestroy();
mWebView.stopLoading();
ViewGroup webParent = (ViewGroup)mWebView.getParent();
if(webParent != null){
webParent.removeView(mWebView);
}
mWebView.destroy();
}
}
| UTF-8 | Java | 1,938 | java | WebActivity.java | Java | [
{
"context": "t;\nimport android.widget.Toast;\n\n/**\n * Created by Nyamura on 2016/02/15.\n */\npublic class WebActivity exten",
"end": 373,
"score": 0.9981702566146851,
"start": 366,
"tag": "USERNAME",
"value": "Nyamura"
}
] | null | [] | package com.example.student001.sc2;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/**
* Created by Nyamura on 2016/02/15.
*/
public class WebActivity extends Activity{
private static final String TAG = WebActivity.class.getSimpleName();
private final WebActivity self = this;
//WebView
private WebView mWebView;
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mWebView = (WebView)findViewById(R.id.webView);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings();
mWebView.loadUrl("http://www3.jeed.or.jp/miyagi/college/admission/opencampus.html");
mWebView.getSettings().setJavaScriptEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.return_botton, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_return){
Intent intent = new Intent(this, Top.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy(){
super.onDestroy();
mWebView.stopLoading();
ViewGroup webParent = (ViewGroup)mWebView.getParent();
if(webParent != null){
webParent.removeView(mWebView);
}
mWebView.destroy();
}
}
| 1,938 | 0.679051 | 0.672343 | 70 | 26.685715 | 21.597979 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.514286 | false | false | 13 |
7f5438c322fb20c2d728430ff5f2db96f3eaf425 | 3,255,585,261,970 | cf8d9f2a76fc103461699932089f8b578dacccf7 | /src/sup.java | cd33115619b4fb8317de3c09672caccd842dfaf0 | [] | no_license | kumawatkavita/Demo | https://github.com/kumawatkavita/Demo | 06a5ba97b4d907eb1b63b45e7734133970bd4a2a | e64ee843514aa1d7361b6b93af98efb099a24be3 | refs/heads/master | 2020-03-27T10:51:55.608000 | 2018-12-10T08:30:06 | 2018-12-10T08:30:06 | 146,450,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class sup {
public static void main(String str[]) {
}
}
| UTF-8 | Java | 80 | java | sup.java | Java | [] | null | [] |
public class sup {
public static void main(String str[]) {
}
}
| 80 | 0.5375 | 0.5375 | 7 | 9.142858 | 13.881422 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 13 |
1f1ab3c21d2a7c46fe08e721f75e0f9a4827e82d | 3,255,585,260,190 | 5593847946652aba78fbcc34e3f04c4bb27ac25b | /src/dao/GestorSalasMVC.java | 255d0c35b65c6bdc6ed0f40b114721243f54c173 | [] | no_license | irener07/labMVC | https://github.com/irener07/labMVC | de68af8101c67527ed8dbf0c9bdb011a0da86c8d | 16e79022e2c842f237ce72a265a6deea044fdd9b | refs/heads/master | 2020-11-27T15:39:37.626000 | 2019-12-22T17:45:04 | 2019-12-22T17:45:04 | 229,515,943 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import vista.*;
import controlador.*;
import modelo.*;
/**
* @author irene
*/
public class GestorSalasMVC {
}
| UTF-8 | Java | 140 | java | GestorSalasMVC.java | Java | [
{
"context": " controlador.*;\r\nimport modelo.*;\r\n/**\r\n * @author irene\r\n */\r\n\r\npublic class GestorSalasMVC {\r\n \r\n}\r\n",
"end": 93,
"score": 0.9977356195449829,
"start": 88,
"tag": "USERNAME",
"value": "irene"
}
] | null | [] | package dao;
import vista.*;
import controlador.*;
import modelo.*;
/**
* @author irene
*/
public class GestorSalasMVC {
}
| 140 | 0.614286 | 0.614286 | 11 | 10.727273 | 9.146195 | 29 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 13 |
69d097d369c40cca57eb2d97cb9c4a6e332f656c | 34,454,227,689,711 | 1bc38c1189e9b852ad81c07dcf0e0cce45f0c768 | /TrabalhoGrauA/src/RelatorioSalarial.java | af2a9adadd6085a10f99d34018f48c4bbae16431 | [] | no_license | vitorfurini/java-basico | https://github.com/vitorfurini/java-basico | 2c06f1bae7f58d0d636777dd9ca7fea21a8b8b77 | 245b2c103dce28445cafff2977e24eeae2a050bd | refs/heads/master | 2020-05-18T17:01:54.595000 | 2019-07-15T19:09:11 | 2019-07-15T19:12:01 | 93,866,982 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class RelatorioSalarial {
private double somatorioSalario = 0;
public void registrarSalario(Funcionario funcionario){
somatorioSalario += funcionario.getSalarioMensal();
}
public double getSomatorioSalario(){
return somatorioSalario;
}
}
| UTF-8 | Java | 260 | java | RelatorioSalarial.java | Java | [] | null | [] | public class RelatorioSalarial {
private double somatorioSalario = 0;
public void registrarSalario(Funcionario funcionario){
somatorioSalario += funcionario.getSalarioMensal();
}
public double getSomatorioSalario(){
return somatorioSalario;
}
}
| 260 | 0.776923 | 0.773077 | 12 | 20.666666 | 20.733763 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 13 |
e90503fb99477d9a393a29ec69a3183c29c0f823 | 29,978,871,794,584 | 07f128b05289e9aca4194f742af0ed2aaffba157 | /src/main/java/br/com/sistema_vendas/validation/ProdutoValidation.java | a1523e27b780954a7e966a794b8b5db1fa09ed5d | [] | no_license | victorcasfer/SalesSystem | https://github.com/victorcasfer/SalesSystem | 6fa1867991cbcfe92af8531b807220aab907d6b2 | 7189ce13f5fcfda62ad0509d854a191f179315ed | refs/heads/master | 2020-03-07T01:47:27.925000 | 2018-04-04T21:02:34 | 2018-04-04T21:02:34 | 127,193,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.sistema_vendas.validation;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import br.com.sistema_vendas.models.Produto;
public class ProdutoValidation implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Produto.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "nome", "field.required");
ValidationUtils.rejectIfEmpty(errors, "preco_custo", "field.required");
ValidationUtils.rejectIfEmpty(errors, "preco_venda", "field.required");
ValidationUtils.rejectIfEmpty(errors, "tipo", "field.required");
Produto produto = (Produto) target;
}
}
| UTF-8 | Java | 797 | java | ProdutoValidation.java | Java | [] | null | [] | package br.com.sistema_vendas.validation;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import br.com.sistema_vendas.models.Produto;
public class ProdutoValidation implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Produto.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "nome", "field.required");
ValidationUtils.rejectIfEmpty(errors, "preco_custo", "field.required");
ValidationUtils.rejectIfEmpty(errors, "preco_venda", "field.required");
ValidationUtils.rejectIfEmpty(errors, "tipo", "field.required");
Produto produto = (Produto) target;
}
}
| 797 | 0.780427 | 0.780427 | 26 | 29.653847 | 26.707737 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.615385 | false | false | 13 |
00876c2abadd404f5b7383a673818eea78120be4 | 33,844,342,336,159 | 76ca52991ca1a1e50d066e9f7c4827b6a4453414 | /packages/SystemUI/src/com/android/systemui/volume/SafetyWarningDialog.java | 361604c461b4b16b90161b9a418332f1f6879887 | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | ResurrectionRemix/android_frameworks_base | https://github.com/ResurrectionRemix/android_frameworks_base | 3126048967fa5f14760664bea8002e7911da206a | 5e1db0334755ba47245d69857a17f84503f7ce6f | refs/heads/Q | 2023-02-17T11:50:11.652000 | 2021-09-19T11:36:09 | 2021-09-19T11:36:09 | 17,213,932 | 169 | 1,154 | Apache-2.0 | false | 2023-02-11T12:45:31 | 2014-02-26T14:52:44 | 2022-11-20T20:08:48 | 2023-02-11T11:57:00 | 3,325,928 | 112 | 289 | 0 | Java | false | false | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.android.systemui.volume;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.media.AudioManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import com.android.systemui.statusbar.phone.SystemUIDialog;
abstract public class SafetyWarningDialog extends SystemUIDialog
implements DialogInterface.OnDismissListener, DialogInterface.OnClickListener {
private static final String TAG = Util.logTag(SafetyWarningDialog.class);
private static final int KEY_CONFIRM_ALLOWED_AFTER = 1000; // milliseconds
private final Context mContext;
private final AudioManager mAudioManager;
private long mShowTime;
private boolean mNewVolumeUp;
private boolean mDisableOnVolumeUp;
public SafetyWarningDialog(Context context, AudioManager audioManager) {
super(context);
mContext = context;
mAudioManager = audioManager;
try {
mDisableOnVolumeUp = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_safe_media_disable_on_volume_up);
} catch (NotFoundException e) {
mDisableOnVolumeUp = true;
}
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
setShowForAllUsers(true);
setMessage(mContext.getString(com.android.internal.R.string.safe_media_volume_warning));
setButton(DialogInterface.BUTTON_POSITIVE,
mContext.getString(com.android.internal.R.string.yes), this);
setButton(DialogInterface.BUTTON_NEGATIVE,
mContext.getString(com.android.internal.R.string.no), (OnClickListener) null);
setOnDismissListener(this);
final IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mReceiver, filter);
}
abstract protected void cleanUp();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mDisableOnVolumeUp && keyCode == KeyEvent.KEYCODE_VOLUME_UP
&& event.getRepeatCount() == 0) {
mNewVolumeUp = true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && mNewVolumeUp
&& (System.currentTimeMillis() - mShowTime) > KEY_CONFIRM_ALLOWED_AFTER) {
if (D.BUG) Log.d(TAG, "Confirmed warning via VOLUME_UP");
mAudioManager.disableSafeMediaVolume();
dismiss();
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onClick(DialogInterface dialog, int which) {
mAudioManager.disableSafeMediaVolume();
}
@Override
protected void onStart() {
super.onStart();
mShowTime = System.currentTimeMillis();
}
@Override
public void onDismiss(DialogInterface unused) {
mContext.unregisterReceiver(mReceiver);
cleanUp();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
if (D.BUG) Log.d(TAG, "Received ACTION_CLOSE_SYSTEM_DIALOGS");
cancel();
cleanUp();
}
}
};
}
| UTF-8 | Java | 4,241 | java | SafetyWarningDialog.java | Java | [] | null | [] | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.android.systemui.volume;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.media.AudioManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import com.android.systemui.statusbar.phone.SystemUIDialog;
abstract public class SafetyWarningDialog extends SystemUIDialog
implements DialogInterface.OnDismissListener, DialogInterface.OnClickListener {
private static final String TAG = Util.logTag(SafetyWarningDialog.class);
private static final int KEY_CONFIRM_ALLOWED_AFTER = 1000; // milliseconds
private final Context mContext;
private final AudioManager mAudioManager;
private long mShowTime;
private boolean mNewVolumeUp;
private boolean mDisableOnVolumeUp;
public SafetyWarningDialog(Context context, AudioManager audioManager) {
super(context);
mContext = context;
mAudioManager = audioManager;
try {
mDisableOnVolumeUp = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_safe_media_disable_on_volume_up);
} catch (NotFoundException e) {
mDisableOnVolumeUp = true;
}
getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
setShowForAllUsers(true);
setMessage(mContext.getString(com.android.internal.R.string.safe_media_volume_warning));
setButton(DialogInterface.BUTTON_POSITIVE,
mContext.getString(com.android.internal.R.string.yes), this);
setButton(DialogInterface.BUTTON_NEGATIVE,
mContext.getString(com.android.internal.R.string.no), (OnClickListener) null);
setOnDismissListener(this);
final IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mReceiver, filter);
}
abstract protected void cleanUp();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mDisableOnVolumeUp && keyCode == KeyEvent.KEYCODE_VOLUME_UP
&& event.getRepeatCount() == 0) {
mNewVolumeUp = true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && mNewVolumeUp
&& (System.currentTimeMillis() - mShowTime) > KEY_CONFIRM_ALLOWED_AFTER) {
if (D.BUG) Log.d(TAG, "Confirmed warning via VOLUME_UP");
mAudioManager.disableSafeMediaVolume();
dismiss();
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onClick(DialogInterface dialog, int which) {
mAudioManager.disableSafeMediaVolume();
}
@Override
protected void onStart() {
super.onStart();
mShowTime = System.currentTimeMillis();
}
@Override
public void onDismiss(DialogInterface unused) {
mContext.unregisterReceiver(mReceiver);
cleanUp();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
if (D.BUG) Log.d(TAG, "Received ACTION_CLOSE_SYSTEM_DIALOGS");
cancel();
cleanUp();
}
}
};
}
| 4,241 | 0.686866 | 0.683801 | 118 | 34.940678 | 27.971624 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576271 | false | false | 13 |
08698342aacc4df04cd77ec69ad89a9576f5ef80 | 4,844,723,147,960 | 2a9fefd5388cc33c42d86a10c3017bf1dca70a39 | /app/src/main/java/com/anhdt/doranewsvermain/adapter/viewpagerarticle/ArticleInViewPagerAdapter.java | 5e6490004a10ce21db151c03190418f931cde18f | [] | no_license | dangtrunganh/DoraNewsVerMain | https://github.com/dangtrunganh/DoraNewsVerMain | 696cb9c03ce204cd8d3ba77a41be5caaa4811ae3 | 1cad001861cc69dd90d3ab54ba907e196b757010 | refs/heads/master | 2020-05-07T12:54:05.219000 | 2019-08-24T10:58:27 | 2019-08-24T10:58:27 | 180,524,629 | 0 | 0 | null | false | 2019-08-24T10:58:28 | 2019-04-10T07:16:10 | 2019-07-19T05:41:36 | 2019-08-24T10:58:28 | 17,823 | 0 | 0 | 0 | Java | false | false | package com.anhdt.doranewsvermain.adapter.viewpagerarticle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.anhdt.doranewsvermain.fragment.secondchildfragment.ArticleFramentInDetailNewsFragment;
import com.anhdt.doranewsvermain.model.newsresult.Article;
import com.anhdt.doranewsvermain.service.voice.interfacewithmainactivity.ControlVoice;
import com.google.gson.Gson;
import java.util.ArrayList;
public class ArticleInViewPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<Article> mArrayNews;
private FragmentManager fragmentManager;
private ControlVoice controlVoice;
public ArticleInViewPagerAdapter(FragmentManager fm, ArrayList<Article> mArrayNews, ControlVoice controlVoice) {
super(fm);
this.fragmentManager = fm;
this.mArrayNews = mArrayNews;
this.controlVoice = controlVoice;
}
@Override
public ArticleFramentInDetailNewsFragment getItem(int position) {
Gson gson = new Gson();
Article article = mArrayNews.get(position);
String jsonArticle = gson.toJson(article);
String jsonListTotal = gson.toJson(mArrayNews);
ArticleFramentInDetailNewsFragment articleFramentInDetailNewsFragment = ArticleFramentInDetailNewsFragment.newInstance(jsonArticle, jsonListTotal, position);
articleFramentInDetailNewsFragment.setControlVoice(this.controlVoice);
return articleFramentInDetailNewsFragment;
}
@Override
public int getCount() {
if (mArrayNews == null) {
return 0;
}
return mArrayNews.size();
}
}
| UTF-8 | Java | 1,658 | java | ArticleInViewPagerAdapter.java | Java | [] | null | [] | package com.anhdt.doranewsvermain.adapter.viewpagerarticle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.anhdt.doranewsvermain.fragment.secondchildfragment.ArticleFramentInDetailNewsFragment;
import com.anhdt.doranewsvermain.model.newsresult.Article;
import com.anhdt.doranewsvermain.service.voice.interfacewithmainactivity.ControlVoice;
import com.google.gson.Gson;
import java.util.ArrayList;
public class ArticleInViewPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<Article> mArrayNews;
private FragmentManager fragmentManager;
private ControlVoice controlVoice;
public ArticleInViewPagerAdapter(FragmentManager fm, ArrayList<Article> mArrayNews, ControlVoice controlVoice) {
super(fm);
this.fragmentManager = fm;
this.mArrayNews = mArrayNews;
this.controlVoice = controlVoice;
}
@Override
public ArticleFramentInDetailNewsFragment getItem(int position) {
Gson gson = new Gson();
Article article = mArrayNews.get(position);
String jsonArticle = gson.toJson(article);
String jsonListTotal = gson.toJson(mArrayNews);
ArticleFramentInDetailNewsFragment articleFramentInDetailNewsFragment = ArticleFramentInDetailNewsFragment.newInstance(jsonArticle, jsonListTotal, position);
articleFramentInDetailNewsFragment.setControlVoice(this.controlVoice);
return articleFramentInDetailNewsFragment;
}
@Override
public int getCount() {
if (mArrayNews == null) {
return 0;
}
return mArrayNews.size();
}
}
| 1,658 | 0.761158 | 0.759349 | 43 | 37.55814 | 34.729721 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651163 | false | false | 13 |
3ca48f7dcbd334fe55a4c56bb870629520b4d33a | 38,886,633,924,953 | e8d9a96be8e009f262cc473bb29c7a2d87f09d92 | /ResourceServer/src/main/java/com/harsha/resource/security/JWTAccessTokenCustomizer.java | abc751300f7da8701cfb3803acfb2aa426d44500 | [] | no_license | Harshamendu/OAuth2_Keycloak | https://github.com/Harshamendu/OAuth2_Keycloak | fd69233f7261d0addc96640226dea9ee83499f6e | 6ef8411fe4b8a52cf3df94a978603b28e24dedf4 | refs/heads/master | 2023-01-09T10:29:45.925000 | 2020-11-08T23:56:09 | 2020-11-08T23:56:09 | 311,178,410 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.harsha.resource.security;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JWTAccessTokenCustomizer extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer {
private ObjectMapper mapper;
public JWTAccessTokenCustomizer(ObjectMapper mapper) {
super();
this.mapper = mapper;
}
@Override
public void configure(JwtAccessTokenConverter converter) {
converter.setAccessTokenConverter(this);
}
public OAuth2Authentication extractAuthenication(Map<String,?> tokenMap) {
JsonNode token = mapper.convertValue(tokenMap, JsonNode.class);
Set<String> audienceList = extractClients(token);
List<GrantedAuthority> authorities = extractRoles(token);
OAuth2Authentication authentication = super.extractAuthentication(tokenMap);
OAuth2Request oAuth2Request = authentication.getOAuth2Request();
OAuth2Request request = new OAuth2Request(oAuth2Request.getRequestParameters(),oAuth2Request.getClientId()
,authorities,true,oAuth2Request.getScope(),audienceList,null,null,null);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "N/A" ,authorities);
return new OAuth2Authentication(request, usernamePasswordAuthenticationToken);
}
private List<GrantedAuthority> extractRoles(JsonNode token) {
Set<String> rolesWithPrefix = new HashSet<>();
token.path("resource_access").elements().forEachRemaining
(s -> s.path("roles").elements().forEachRemaining(r -> rolesWithPrefix.add(r.asText())));
List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(rolesWithPrefix.toArray(new String[0]));
return authorityList;
}
private Set<String> extractClients(JsonNode token) {
Set<String> clientNames = new HashSet<>();
if(token.has("resource_access")) {
JsonNode resouceAccessJsonNode = token.findPath("resource_access");
JsonNode azpJsonNode = token.path("azp");
JsonNode audJsonNode = token.path("aud");
clientNames.add(azpJsonNode.asText());
audJsonNode.fieldNames().forEachRemaining(clientNames::add);
resouceAccessJsonNode.fieldNames().forEachRemaining(clientNames::add);
}
return clientNames;
}
}
| UTF-8 | Java | 3,072 | java | JWTAccessTokenCustomizer.java | Java | [] | null | [] | package com.harsha.resource.security;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JWTAccessTokenCustomizer extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer {
private ObjectMapper mapper;
public JWTAccessTokenCustomizer(ObjectMapper mapper) {
super();
this.mapper = mapper;
}
@Override
public void configure(JwtAccessTokenConverter converter) {
converter.setAccessTokenConverter(this);
}
public OAuth2Authentication extractAuthenication(Map<String,?> tokenMap) {
JsonNode token = mapper.convertValue(tokenMap, JsonNode.class);
Set<String> audienceList = extractClients(token);
List<GrantedAuthority> authorities = extractRoles(token);
OAuth2Authentication authentication = super.extractAuthentication(tokenMap);
OAuth2Request oAuth2Request = authentication.getOAuth2Request();
OAuth2Request request = new OAuth2Request(oAuth2Request.getRequestParameters(),oAuth2Request.getClientId()
,authorities,true,oAuth2Request.getScope(),audienceList,null,null,null);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "N/A" ,authorities);
return new OAuth2Authentication(request, usernamePasswordAuthenticationToken);
}
private List<GrantedAuthority> extractRoles(JsonNode token) {
Set<String> rolesWithPrefix = new HashSet<>();
token.path("resource_access").elements().forEachRemaining
(s -> s.path("roles").elements().forEachRemaining(r -> rolesWithPrefix.add(r.asText())));
List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(rolesWithPrefix.toArray(new String[0]));
return authorityList;
}
private Set<String> extractClients(JsonNode token) {
Set<String> clientNames = new HashSet<>();
if(token.has("resource_access")) {
JsonNode resouceAccessJsonNode = token.findPath("resource_access");
JsonNode azpJsonNode = token.path("azp");
JsonNode audJsonNode = token.path("aud");
clientNames.add(azpJsonNode.asText());
audJsonNode.fieldNames().forEachRemaining(clientNames::add);
resouceAccessJsonNode.fieldNames().forEachRemaining(clientNames::add);
}
return clientNames;
}
}
| 3,072 | 0.796224 | 0.790039 | 90 | 33.133335 | 36.942059 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.922222 | false | false | 13 |
b92fa1b0884086a715d6fcdf1e8134e2bc85dd9c | 20,993,800,195,524 | cba744e3cc927b7297d027240de414e8f4faf148 | /src/main/java/cn/parkinfo/controller/StringUtil.java | 60009972b7c43570c183cefaaa830325d88fb904 | [] | no_license | ruoxingzpc/parkinfo | https://github.com/ruoxingzpc/parkinfo | 9c3870e656cb9bac97589c6b64199277665d73df | c6a8ab9b5e0c759882fbdb753dfeee99fefea35c | refs/heads/master | 2018-12-18T10:25:18.770000 | 2018-12-14T08:07:42 | 2018-12-14T08:07:42 | 134,513,849 | 0 | 1 | null | false | 2019-11-13T09:34:37 | 2018-05-23T04:34:17 | 2019-08-11T06:12:57 | 2019-11-13T09:34:36 | 88,759 | 0 | 1 | 2 | JavaScript | false | false | /**
*
*/
package cn.parkinfo.controller;
import java.util.Map;
import java.util.UUID;
/**
* @author Administrator
*
*/
public class StringUtil {
public static String mapToLogInfo(Map<String, String> map) {
if (map == null || map.size() <= 0)
return null;
String[] splits = new String[] {
"=", ";" };
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = removeSplit(entry.getKey(), splits);
String value = removeSplit(entry.getValue(), splits);
sb.append(key);
sb.append(splits[0]);
sb.append(value);
sb.append(splits[1]);
}
return sb.toString();
}
public static String mapToString(Map<String, String> map, String[] splits) {
if (map == null || map.size() <= 0)
return null;
if (splits == null || splits.length < 2)
return null;
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = removeSplit(entry.getKey(), splits);
String value = removeSplit(entry.getValue(), splits);
sb.append(key);
sb.append(splits[0]);
sb.append(value);
sb.append(splits[1]);
}
return sb.toString();
}
private static String removeSplit(String source, String[] splits) {
if (source == null || source.trim().length() <= 0)
return null;
if (splits == null || splits.length <= 0)
return source;
for (String split : splits) {
source = source.replaceAll(split, "");
}
return source;
}
public static String getCn(){
UUID uuid = UUID.randomUUID();
String str = uuid.toString();
return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
}
public static String getString(Object obj){
return obj==null?"":obj.toString();
}
public static boolean isEmpty(String obj){
return obj==null||obj.trim().length()==0;
}
}
| UTF-8 | Java | 2,008 | java | StringUtil.java | Java | [
{
"context": "a.util.Map;\nimport java.util.UUID;\n\n/**\n * @author Administrator\n * \n */\npublic class StringUtil {\n\n public stati",
"end": 119,
"score": 0.9882916808128357,
"start": 106,
"tag": "NAME",
"value": "Administrator"
}
] | null | [] | /**
*
*/
package cn.parkinfo.controller;
import java.util.Map;
import java.util.UUID;
/**
* @author Administrator
*
*/
public class StringUtil {
public static String mapToLogInfo(Map<String, String> map) {
if (map == null || map.size() <= 0)
return null;
String[] splits = new String[] {
"=", ";" };
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = removeSplit(entry.getKey(), splits);
String value = removeSplit(entry.getValue(), splits);
sb.append(key);
sb.append(splits[0]);
sb.append(value);
sb.append(splits[1]);
}
return sb.toString();
}
public static String mapToString(Map<String, String> map, String[] splits) {
if (map == null || map.size() <= 0)
return null;
if (splits == null || splits.length < 2)
return null;
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = removeSplit(entry.getKey(), splits);
String value = removeSplit(entry.getValue(), splits);
sb.append(key);
sb.append(splits[0]);
sb.append(value);
sb.append(splits[1]);
}
return sb.toString();
}
private static String removeSplit(String source, String[] splits) {
if (source == null || source.trim().length() <= 0)
return null;
if (splits == null || splits.length <= 0)
return source;
for (String split : splits) {
source = source.replaceAll(split, "");
}
return source;
}
public static String getCn(){
UUID uuid = UUID.randomUUID();
String str = uuid.toString();
return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
}
public static String getString(Object obj){
return obj==null?"":obj.toString();
}
public static boolean isEmpty(String obj){
return obj==null||obj.trim().length()==0;
}
}
| 2,008 | 0.602092 | 0.589641 | 79 | 24.417721 | 23.500933 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78481 | false | false | 13 |
bc96922323f227a4edc3fb7d2f12d57527858ea7 | 34,892,314,373,609 | 8382a2f9c8e570fe01c34b4115573cceb36356bd | /Week1/ObjectDay4/src/day4/practice/ManagerInfo.java | d7ff3377a7a55207bacd5de7718136ccc996dad7 | [] | no_license | Genesis2011/Java-Basic-Practice | https://github.com/Genesis2011/Java-Basic-Practice | 93f68ca0228ec1d403f7c9e8b28394bdab817320 | d389d3d39914623915d35ee50988b9ebd89d022d | refs/heads/master | 2020-12-02T09:55:12.063000 | 2017-07-14T03:56:22 | 2017-07-14T03:56:22 | 96,660,278 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day4.practice;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ManagerInfo {
List<Person> list = new ArrayList();
//初始化列表信息
public void init(){
list = new ArrayList();
list.add(new Teacher("张", 33, 3));
list.add(new Teacher("王", 30, 2));
list.add(new Master("李", 26, 2));
list.add(new Master("赵", 23, 2));
list.add(new Student("冯", 20, "三班"));
list.add(new Student("楚", 20, "四班"));
}
// 添加信息
public boolean add() {
list.add(getObject());
return true;
}
// 查询信息
public void query() {
for (Person p : list) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
}
}
// 根据姓名查询信息
/* public void seach(String name) {
for (Person p : list) {
if (p.getName().equals(name)) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
return ;
}
}
System.out.println("没有找到此人信息");
}*/
//姓名的模糊查询
public void seach(String name) {
for (Person p : list) {
//indexOf 在字符串中找到指定字符的位置 如果没找到是-1
if (p.getName().indexOf(name)!=-1) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
}
}
System.out.println("没有找到此人信息");
}
//根据姓名删除
public void del(String name){
for(Person p : list) {
if(p.getName().equals(name)){
list.remove(p);
System.out.println("删除成功");
return ;
}
}
System.out.println("没有找到此人信息");
}
//根据姓名修改
public void updateData(){
Person upPerson=getObject();
for (int i=0;i<list.size();i++) {
Person p=list.get(i);
if(p.getName().equals(upPerson.getName())){
list.set(i, upPerson);
System.out.println("修改完成");
return;
}
}
System.out.println("没有找到此人信息");
}
private String toolsChangeClass(Person p) {
String threeValue = "";
if (p instanceof IWorkYear) {
threeValue = ((IWorkYear) p).getWorkYear() + "";
}
if (p instanceof Student) {
threeValue = ((Student) p).getClassRoom() + "";
}
return threeValue;
}
private Person getObject(){
Person p = null;
Scanner input = new Scanner(System.in);
System.out.println("1、教师;2、班主任;3、学生");
int menu = input.nextInt();
System.out.println("输入姓名");
String name = input.next();
System.out.println("输入年龄");
int age = input.nextInt();
switch (menu) {
case 1:
System.out.println("输入工龄");
int workYear = input.nextInt();
p = new Teacher(name, age, workYear);
break;
case 2:
System.out.println("输入工龄");
workYear = input.nextInt();
p = new Master(name, age, workYear);
break;
case 3:
System.out.println("输入班级");
String classRoom = input.next();
p = new Student(name, age, classRoom);
break;
default:
System.out.println("输入错误");
break;
}
return p;
}
}
| UTF-8 | Java | 3,043 | java | ManagerInfo.java | Java | [
{
"context": "\t\tlist = new ArrayList();\n\t\tlist.add(new Teacher(\"张\", 33, 3));\n\t\tlist.add(new Teacher(\"王\", 30, 2));\n\t",
"end": 250,
"score": 0.9998685121536255,
"start": 249,
"tag": "NAME",
"value": "张"
},
{
"context": "new Teacher(\"张\", 33, 3));\n\t\tlist.add(new Teacher(\"王\", 30, 2));\n\t\tlist.add(new Master(\"李\", 26, 2));\n\t\t",
"end": 287,
"score": 0.9998690485954285,
"start": 286,
"tag": "NAME",
"value": "王"
},
{
"context": "(new Teacher(\"王\", 30, 2));\n\t\tlist.add(new Master(\"李\", 26, 2));\n\t\tlist.add(new Master(\"赵\", 23, 2));\n\t\t",
"end": 323,
"score": 0.999864935874939,
"start": 322,
"tag": "NAME",
"value": "李"
},
{
"context": "d(new Master(\"李\", 26, 2));\n\t\tlist.add(new Master(\"赵\", 23, 2));\n\t\tlist.add(new Student(\"冯\", 20, \"三班\"))",
"end": 359,
"score": 0.9980313777923584,
"start": 358,
"tag": "NAME",
"value": "赵"
},
{
"context": "(new Master(\"赵\", 23, 2));\n\t\tlist.add(new Student(\"冯\", 20, \"三班\"));\n\t\tlist.add(new Student(\"楚\", 20, \"四班",
"end": 396,
"score": 0.9989098310470581,
"start": 395,
"tag": "NAME",
"value": "冯"
},
{
"context": " Student(\"冯\", 20, \"三班\"));\n\t\tlist.add(new Student(\"楚\", 20, \"四班\"));\n\t}\n\t// 添加信息\n\tpublic boolean add() {",
"end": 436,
"score": 0.9990729093551636,
"start": 435,
"tag": "NAME",
"value": "楚"
}
] | null | [] | package day4.practice;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ManagerInfo {
List<Person> list = new ArrayList();
//初始化列表信息
public void init(){
list = new ArrayList();
list.add(new Teacher("张", 33, 3));
list.add(new Teacher("王", 30, 2));
list.add(new Master("李", 26, 2));
list.add(new Master("赵", 23, 2));
list.add(new Student("冯", 20, "三班"));
list.add(new Student("楚", 20, "四班"));
}
// 添加信息
public boolean add() {
list.add(getObject());
return true;
}
// 查询信息
public void query() {
for (Person p : list) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
}
}
// 根据姓名查询信息
/* public void seach(String name) {
for (Person p : list) {
if (p.getName().equals(name)) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
return ;
}
}
System.out.println("没有找到此人信息");
}*/
//姓名的模糊查询
public void seach(String name) {
for (Person p : list) {
//indexOf 在字符串中找到指定字符的位置 如果没找到是-1
if (p.getName().indexOf(name)!=-1) {
System.out.println(p.getName() + " " + p.getAge() + " " + toolsChangeClass(p));
}
}
System.out.println("没有找到此人信息");
}
//根据姓名删除
public void del(String name){
for(Person p : list) {
if(p.getName().equals(name)){
list.remove(p);
System.out.println("删除成功");
return ;
}
}
System.out.println("没有找到此人信息");
}
//根据姓名修改
public void updateData(){
Person upPerson=getObject();
for (int i=0;i<list.size();i++) {
Person p=list.get(i);
if(p.getName().equals(upPerson.getName())){
list.set(i, upPerson);
System.out.println("修改完成");
return;
}
}
System.out.println("没有找到此人信息");
}
private String toolsChangeClass(Person p) {
String threeValue = "";
if (p instanceof IWorkYear) {
threeValue = ((IWorkYear) p).getWorkYear() + "";
}
if (p instanceof Student) {
threeValue = ((Student) p).getClassRoom() + "";
}
return threeValue;
}
private Person getObject(){
Person p = null;
Scanner input = new Scanner(System.in);
System.out.println("1、教师;2、班主任;3、学生");
int menu = input.nextInt();
System.out.println("输入姓名");
String name = input.next();
System.out.println("输入年龄");
int age = input.nextInt();
switch (menu) {
case 1:
System.out.println("输入工龄");
int workYear = input.nextInt();
p = new Teacher(name, age, workYear);
break;
case 2:
System.out.println("输入工龄");
workYear = input.nextInt();
p = new Master(name, age, workYear);
break;
case 3:
System.out.println("输入班级");
String classRoom = input.next();
p = new Student(name, age, classRoom);
break;
default:
System.out.println("输入错误");
break;
}
return p;
}
}
| 3,043 | 0.6102 | 0.600729 | 119 | 22.067226 | 16.953585 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.655462 | false | false | 13 |
4d8970fbc2aa8c0ac7ecc7efccc6ad55954b5529 | 29,875,792,576,954 | 7e24a8d22ed0bce7e3a290130a7def76f53a5378 | /urtruck/com.urt.sdk/src/main/java/com/urt/interfaces/traffic/TimerTrafficQueryService.java | 2f94d38b23ac93e6b91f7ce1fae85b0b0c18e2fe | [
"Apache-2.0"
] | permissive | tenchoo/URTrack | https://github.com/tenchoo/URTrack | 4b036e1e23af8c28afd1a381a950c4bc455dc00e | 3ac0b03b3a0359b51d6bd794629cf9b27191976c | refs/heads/master | 2021-07-02T13:13:52.814000 | 2017-09-23T14:09:50 | 2017-09-23T14:09:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.urt.interfaces.traffic;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.urt.dto.Goods.LaoUserDto;
import com.urt.dto.traffic.LaoTrafficDetailDto;
import com.urt.dto.traffic.LaoTrafficMmDto;
public interface TimerTrafficQueryService {
// 定时 批量查询流量
LaoTrafficDetailDto doTrafficQuery (LaoUserDto user);
public void sendUserMsg(List<Map<String, Object>> listMap);
// 记录每月记录
int insertSelective(LaoTrafficMmDto record);
// 根据userId查询月记录
LaoTrafficMmDto selectByUseId(Long userId, String dataCycleMm);
// 更新每月记录(每天更新累计使用流量)
int updateByPrimaryKeySelective(LaoTrafficMmDto record);
BigDecimal getNotSendFlow(Long userId);
}
| UTF-8 | Java | 782 | java | TimerTrafficQueryService.java | Java | [] | null | [] | package com.urt.interfaces.traffic;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.urt.dto.Goods.LaoUserDto;
import com.urt.dto.traffic.LaoTrafficDetailDto;
import com.urt.dto.traffic.LaoTrafficMmDto;
public interface TimerTrafficQueryService {
// 定时 批量查询流量
LaoTrafficDetailDto doTrafficQuery (LaoUserDto user);
public void sendUserMsg(List<Map<String, Object>> listMap);
// 记录每月记录
int insertSelective(LaoTrafficMmDto record);
// 根据userId查询月记录
LaoTrafficMmDto selectByUseId(Long userId, String dataCycleMm);
// 更新每月记录(每天更新累计使用流量)
int updateByPrimaryKeySelective(LaoTrafficMmDto record);
BigDecimal getNotSendFlow(Long userId);
}
| 782 | 0.779661 | 0.779661 | 26 | 26.23077 | 21.766785 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.807692 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.