blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
eed89e8cebbefe7c05df58a539645e46499ceec7
9,131,100,477,958
928e6bdcb47f35c0386d6f144b968edc744febcb
/src/nus/extensions/tests/cornercases/PropagateMethodReturn.java
db779b74b187ecd1411c328b06e82297f154f21a
[]
no_license
rubinovk/FlowdroidTests
https://github.com/rubinovk/FlowdroidTests
e5c5ecc73a0b3134ae7df911b6f1ae7e8d2b11cd
caee712831592c098019e44993b7507bcd0262e5
refs/heads/master
2021-01-21T09:14:55.313000
2014-11-14T08:51:03
2014-11-14T08:51:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nus.extensions.tests.cornercases; import java.io.PrintWriter; import nus.extensions.tests.MainActivity; import nus.extensions.tests.SinkEmulator; import nus.extensions.tests.SourceEmulator; import nus.extensions.tests.datastructures.Datastructures2.C; public class PropagateMethodReturn extends MainActivity { private static final String FIELD_NAME = "name"; public class C { private String str; private C next; public String getData() { return this.str; } public String useDataPropagateToReturn(String str) { String modificator = Integer.toString(RESULT_OK); return str + modificator; } public void setData(String str) { this.str = str; } public void setNext(C next) { this.next = next; } public C getNext(){ return this.next; } } protected void main(SourceEmulator source, SinkEmulator sink) { String name = source.getParameter(FIELD_NAME); // other statements C c1 = new C(); c1.setData("def"); // using sensitive data C c2 = new C(); String result = c2.useDataPropagateToReturn(name); // result is tainted c1.setData(result); // c1.str is tainted String str = c1.getData(); PrintWriter writer = sink.getWriter(); writer.println(str); /* BAD */ } public String getDescription() { return "flow to field to next"; } public int getVulnerabilityCount() { return 1; } }
UTF-8
Java
1,378
java
PropagateMethodReturn.java
Java
[]
null
[]
package nus.extensions.tests.cornercases; import java.io.PrintWriter; import nus.extensions.tests.MainActivity; import nus.extensions.tests.SinkEmulator; import nus.extensions.tests.SourceEmulator; import nus.extensions.tests.datastructures.Datastructures2.C; public class PropagateMethodReturn extends MainActivity { private static final String FIELD_NAME = "name"; public class C { private String str; private C next; public String getData() { return this.str; } public String useDataPropagateToReturn(String str) { String modificator = Integer.toString(RESULT_OK); return str + modificator; } public void setData(String str) { this.str = str; } public void setNext(C next) { this.next = next; } public C getNext(){ return this.next; } } protected void main(SourceEmulator source, SinkEmulator sink) { String name = source.getParameter(FIELD_NAME); // other statements C c1 = new C(); c1.setData("def"); // using sensitive data C c2 = new C(); String result = c2.useDataPropagateToReturn(name); // result is tainted c1.setData(result); // c1.str is tainted String str = c1.getData(); PrintWriter writer = sink.getWriter(); writer.println(str); /* BAD */ } public String getDescription() { return "flow to field to next"; } public int getVulnerabilityCount() { return 1; } }
1,378
0.706822
0.70029
64
20.546875
19.777615
73
false
false
0
0
0
0
0
0
1.78125
false
false
9
f1f4df7ba0e928ac9f6972334996b8242a5cf6cd
11,252,814,325,227
d8a4007f6a38c1edfd7f1182418050ff55c36026
/worf-exception/src/main/java/orj/worf/exception/BaseException.java
58f5ca87a68101a5e96eee080da7cf754e73a9f2
[ "Apache-2.0" ]
permissive
liu-project/worf
https://github.com/liu-project/worf
d326a65dbe30e5fc1d1626eba6feb21cf7de2155
c4372bb17f44ac964631759104e71e106d8f703f
refs/heads/master
2022-12-25T21:34:38.540000
2021-06-04T23:51:57
2021-06-04T23:51:57
226,672,941
0
0
Apache-2.0
false
2022-12-16T05:01:45
2019-12-08T13:35:41
2021-06-04T23:52:03
2022-12-16T05:01:41
62,745
0
0
27
Java
false
false
package orj.worf.exception; import java.util.Date; public interface BaseException { String getCode(); String[] getArgs(); void setTime(Date time); Date getTime(); void setClassName(String className); String getClassName(); void setMethodName(String methodName); String getMethodName(); void setParameters(String[] parameters); String[] getParameters(); void setHandled(boolean handled); boolean isHandled(); String getMessage(); void setI18nMessage(String i18nMessage); String getI18nMessage(); }
UTF-8
Java
575
java
BaseException.java
Java
[]
null
[]
package orj.worf.exception; import java.util.Date; public interface BaseException { String getCode(); String[] getArgs(); void setTime(Date time); Date getTime(); void setClassName(String className); String getClassName(); void setMethodName(String methodName); String getMethodName(); void setParameters(String[] parameters); String[] getParameters(); void setHandled(boolean handled); boolean isHandled(); String getMessage(); void setI18nMessage(String i18nMessage); String getI18nMessage(); }
575
0.683478
0.673043
37
14.540541
15.868709
44
false
false
0
0
0
0
0
0
0.459459
false
false
9
d9cc87ded4f7b2856ede1f696782c815afcdcfb0
14,680,198,255,888
ec77ef643b741ff6ea54e28c3948ba475a69c837
/ctci/v2/chapter2/Problem1.java
7144e50dd63d5be3c196507f8b57355d902be43d
[]
no_license
siddharthgoel88/problem-solving
https://github.com/siddharthgoel88/problem-solving
8281fa842c6c0a6fa455d6265b9a6588dcadcb84
5876343dc739b384a37a95b2544808e5e5558c49
refs/heads/master
2020-04-12T01:48:35.985000
2020-04-11T01:05:32
2020-04-11T01:05:32
23,728,387
1
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter2; import java.util.HashSet; import java.util.Set; public class Problem1 { class Node { int value; Node next = null; } private Node head = null; public void add(int number) { Node node = new Node(); node.value = number; node.next = head; head = node; } public boolean isEmpty() { return head == null; } public void displayList() { Node runner = head; System.out.print("List : "); while (runner != null) { String seperator = runner.next != null ? " -> " : ""; System.out.print(runner.value + seperator); runner = runner.next; } System.out.println(); } /* * Assumption here is that use of an extra buffer is allowed */ public void deleteDuplicatesWithBuffer() { if (isEmpty()) { return; } Set<Integer> uniqueElements = new HashSet<>(); Node prev = head; uniqueElements.add(prev.value); Node runner = prev.next; while (runner != null) { if (uniqueElements.contains(runner.value)) { prev.next = runner.next; } else { prev = runner; uniqueElements.add(prev.value); } runner = runner.next; } } /* * Assumption extra buffer is not allowed to use. */ public void deleteDuplicatesWithoutBuffer() { if (isEmpty()) { return; } Node firstRunner = head; while(firstRunner != null) { Node secondRunner = firstRunner.next; Node prev = firstRunner; while(secondRunner != null) { if (firstRunner.value == secondRunner.value) { prev.next = secondRunner.next; } else { prev = secondRunner; } secondRunner = secondRunner.next; } firstRunner = firstRunner.next; } } public static void main(String[] args) { Problem1 object = new Problem1(); for (int i=0; i<100; i++) { for (int j=1; j<=100; j++) { object.add(j%2); } } object.displayList(); object.deleteDuplicatesWithBuffer(); object.displayList(); } }
UTF-8
Java
1,895
java
Problem1.java
Java
[]
null
[]
package chapter2; import java.util.HashSet; import java.util.Set; public class Problem1 { class Node { int value; Node next = null; } private Node head = null; public void add(int number) { Node node = new Node(); node.value = number; node.next = head; head = node; } public boolean isEmpty() { return head == null; } public void displayList() { Node runner = head; System.out.print("List : "); while (runner != null) { String seperator = runner.next != null ? " -> " : ""; System.out.print(runner.value + seperator); runner = runner.next; } System.out.println(); } /* * Assumption here is that use of an extra buffer is allowed */ public void deleteDuplicatesWithBuffer() { if (isEmpty()) { return; } Set<Integer> uniqueElements = new HashSet<>(); Node prev = head; uniqueElements.add(prev.value); Node runner = prev.next; while (runner != null) { if (uniqueElements.contains(runner.value)) { prev.next = runner.next; } else { prev = runner; uniqueElements.add(prev.value); } runner = runner.next; } } /* * Assumption extra buffer is not allowed to use. */ public void deleteDuplicatesWithoutBuffer() { if (isEmpty()) { return; } Node firstRunner = head; while(firstRunner != null) { Node secondRunner = firstRunner.next; Node prev = firstRunner; while(secondRunner != null) { if (firstRunner.value == secondRunner.value) { prev.next = secondRunner.next; } else { prev = secondRunner; } secondRunner = secondRunner.next; } firstRunner = firstRunner.next; } } public static void main(String[] args) { Problem1 object = new Problem1(); for (int i=0; i<100; i++) { for (int j=1; j<=100; j++) { object.add(j%2); } } object.displayList(); object.deleteDuplicatesWithBuffer(); object.displayList(); } }
1,895
0.630079
0.623219
94
19.159575
15.580473
61
false
false
0
0
0
0
0
0
2.393617
false
false
9
8f5a23109749a85850921278d0485895b2f2797c
9,938,554,357,842
a9af31948c6642b35c4bda49f638de29f8d73c82
/src/main/java/entities/Bundle.java
3d915f3659d2704c666683b2c3694faa46b70fc4
[]
no_license
Princess-Sherry/bundle-calculator
https://github.com/Princess-Sherry/bundle-calculator
d363f9695e92fa6a765414285eb7ffd019677fc4
34c6d2a695859fb16f334ddfe07b77afaed9be2c
refs/heads/main
2023-08-16T18:42:42.949000
2021-09-14T14:01:24
2021-09-14T14:01:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.util.List; /** * A class for each type of media and its related bundle items information */ @Setter @Getter @AllArgsConstructor public class Bundle { private String formatCode; private List<BundleItem> bundleItems; }
UTF-8
Java
338
java
Bundle.java
Java
[]
null
[]
package entities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import java.util.List; /** * A class for each type of media and its related bundle items information */ @Setter @Getter @AllArgsConstructor public class Bundle { private String formatCode; private List<BundleItem> bundleItems; }
338
0.769231
0.769231
18
17.777779
18.304691
74
false
false
0
0
0
0
0
0
0.388889
false
false
9
5a214b562947846e8b2e76f897ec3fca304d4f8b
13,761,075,249,498
e6853bb1092461ce0a11429fe303461a355f7a27
/algorithms/src/main/java/org/russell/algorithms/ds/Graph.java
ebc774bd2040e1a7f7df7cd89a0849f58709c6e2
[]
no_license
RussellRC/RussellTests
https://github.com/RussellRC/RussellTests
4885ba2260c4c54ab3694e3e3fd30b50d4a8c8dc
6c56f3ced3527ae879f4188f2a5391b791bdb4fe
refs/heads/master
2022-07-01T22:49:12.714000
2022-06-08T17:20:08
2022-06-08T17:20:08
52,841,551
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.russell.algorithms.ds; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Undirected graph * @author russellrazo * */ public class Graph { public static final Logger log = LoggerFactory.getLogger(Graph.class); public Node root; public List<Node> roots; Graph(final Node root) { this.root = root; } Graph(final List<Node> roots) { this.roots = roots; } /** * Inner Node class */ static class Node { Integer value; List<Node> adjacents; Node(final int value) { this.value = value; } @Override public String toString() { return String.format("{value:%d}", value); } @Override public int hashCode() { int result = 1; final int prime = 31; result = result*prime + value.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; Node other = (Node) obj; if (value.equals(other.value)) return false; return true; } } /** * Inner BFS Result class */ static class BFSResult { final Node originNode; final Node destNode; final Map<Node, Node> path; BFSResult(final Node originNode, final Node destNode, final Map<Node, Node> path) { this.originNode = originNode; this.destNode = destNode; this.path = path; } } public static boolean areConnected(final Graph graph, final int a, final int b) { final BFSResult fromGraphToA = findNodeBFS(graph.root, a); if (fromGraphToA.destNode != null) { final BFSResult fromAToB = findNodeBFS(fromGraphToA.destNode, b); if (fromAToB.destNode != null) { printPath(fromAToB); return true; } } // No path from root to A, search B -> A final BFSResult fromGraphToB = findNodeBFS(graph.root, b); if (fromGraphToB.destNode != null) { final BFSResult fromBtoA = findNodeBFS(fromGraphToB.destNode, a); if (fromBtoA.destNode != null) { printPath(fromBtoA); return true; } } return false; } private static void printPath(final BFSResult bfsResult) { final LinkedList<Node> path = new LinkedList<>(); Node node = null; for (node = bfsResult.destNode; node != bfsResult.originNode; node = bfsResult.path.get(node)) { path.addFirst(node); } path.addFirst(node); System.out.println(String.format("Path from %s to %s: %s", bfsResult.originNode.value, bfsResult.destNode.value, path)); } public static BFSResult findNodeBFS(final Node originNode, final int destValue) { final Queue<Node> pending = new LinkedList<>(); pending.add(originNode); final Set<Node> visited = new HashSet<>(); visited.add(originNode); // Map that holds the link from previous to node final Map<Node, Node> previous = new HashMap<Node, Node>(); while (!pending.isEmpty()) { final Node node = pending.poll(); log.debug("visiting: " + node); if (node.value == destValue) { log.debug("found it: " + destValue); return new BFSResult(originNode, node, previous); } if (node.adjacents != null) { for (final Node adjacent : node.adjacents) { if (!visited.contains(adjacent)) { pending.add(adjacent); visited.add(adjacent); previous.put(adjacent, node); } } } } return new BFSResult(originNode, null, null); } /** * Detph First Search * @param originNode * @param value * @param visited * @return */ public static Node findNodeDFS(final Node originNode, final int value, final Set<Node> visited) { if (originNode == null || visited.contains(originNode)) { return null; } log.debug("visiting: " + originNode); visited.add(originNode); if (originNode.value == value) { log.debug("found it: " + value); return originNode; } if (originNode.adjacents != null) { for (final Node node : originNode.adjacents) { final Node foundNode = findNodeDFS(node, value, visited); if (foundNode != null) { return foundNode; } } } return null; } /** * DFS iterative * @param originNode * @param value * @return */ public static Node dfsIterative(final Node originNode, final int value) { final Set<Node> visited = new HashSet<>(); final Deque<Node> pending = new LinkedList<>(); pending.push(originNode); while (!pending.isEmpty()) { final Node pop = pending.pop(); if (!visited.contains(pop)) { visited.add(pop); System.out.println("Visiting: "+ pop.value); if (pop.value == value) { return pop; } } if (pop.adjacents != null) { for (final Node adj : pop.adjacents) { pending.addFirst(adj); } } } return null; } public static Graph cloneGraph(final Node node) { // Map of visited nodes, where k=node v=clone, so that there is only 1 clone per node final Map<Node, Node> visited = new HashMap<>(); final Queue<Node> pending = new LinkedList<>(); Node root = new Node(node.value); visited.put(node, root); pending.add(node); Node current, clone; while (!pending.isEmpty()) { current = pending.poll(); clone = visited.get(current); clone.adjacents = new ArrayList<>(); for (Node adjacent : current.adjacents) { Node adjacentClone = visited.get(adjacent); if (adjacentClone == null) { // Create new clone when it doesn't already exist adjacentClone = new Node(adjacent.value); } clone.adjacents.add(adjacentClone); if (!visited.containsKey(adjacent)) { pending.add(adjacent); visited.put(adjacent, adjacentClone); } } } return new Graph(root); } /** * * @param g */ public static Deque<Node> topologicalSort(Graph g) { final Deque<Node> stack = new LinkedList<>(); final Set<Node> visited = new LinkedHashSet<>(); for (Node root : g.roots) { if (!visited.contains(root)) { visitTopologicalSort(root, visited, stack); } } return stack; } private static void visitTopologicalSort(final Node node, final Set<Node> visited, final Deque<Node> stack) { visited.add(node); for (Node adj : node.adjacents) { if (!visited.contains(adj)) { visitTopologicalSort(adj, visited, stack); } } stack.push(node); } }
UTF-8
Java
7,900
java
Graph.java
Java
[ { "context": "LoggerFactory;\n\n/**\n * Undirected graph\n * @author russellrazo\n *\n */\npublic class Graph {\n\n\tpublic static final", "end": 397, "score": 0.9349074959754944, "start": 386, "tag": "USERNAME", "value": "russellrazo" } ]
null
[]
package org.russell.algorithms.ds; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Undirected graph * @author russellrazo * */ public class Graph { public static final Logger log = LoggerFactory.getLogger(Graph.class); public Node root; public List<Node> roots; Graph(final Node root) { this.root = root; } Graph(final List<Node> roots) { this.roots = roots; } /** * Inner Node class */ static class Node { Integer value; List<Node> adjacents; Node(final int value) { this.value = value; } @Override public String toString() { return String.format("{value:%d}", value); } @Override public int hashCode() { int result = 1; final int prime = 31; result = result*prime + value.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; Node other = (Node) obj; if (value.equals(other.value)) return false; return true; } } /** * Inner BFS Result class */ static class BFSResult { final Node originNode; final Node destNode; final Map<Node, Node> path; BFSResult(final Node originNode, final Node destNode, final Map<Node, Node> path) { this.originNode = originNode; this.destNode = destNode; this.path = path; } } public static boolean areConnected(final Graph graph, final int a, final int b) { final BFSResult fromGraphToA = findNodeBFS(graph.root, a); if (fromGraphToA.destNode != null) { final BFSResult fromAToB = findNodeBFS(fromGraphToA.destNode, b); if (fromAToB.destNode != null) { printPath(fromAToB); return true; } } // No path from root to A, search B -> A final BFSResult fromGraphToB = findNodeBFS(graph.root, b); if (fromGraphToB.destNode != null) { final BFSResult fromBtoA = findNodeBFS(fromGraphToB.destNode, a); if (fromBtoA.destNode != null) { printPath(fromBtoA); return true; } } return false; } private static void printPath(final BFSResult bfsResult) { final LinkedList<Node> path = new LinkedList<>(); Node node = null; for (node = bfsResult.destNode; node != bfsResult.originNode; node = bfsResult.path.get(node)) { path.addFirst(node); } path.addFirst(node); System.out.println(String.format("Path from %s to %s: %s", bfsResult.originNode.value, bfsResult.destNode.value, path)); } public static BFSResult findNodeBFS(final Node originNode, final int destValue) { final Queue<Node> pending = new LinkedList<>(); pending.add(originNode); final Set<Node> visited = new HashSet<>(); visited.add(originNode); // Map that holds the link from previous to node final Map<Node, Node> previous = new HashMap<Node, Node>(); while (!pending.isEmpty()) { final Node node = pending.poll(); log.debug("visiting: " + node); if (node.value == destValue) { log.debug("found it: " + destValue); return new BFSResult(originNode, node, previous); } if (node.adjacents != null) { for (final Node adjacent : node.adjacents) { if (!visited.contains(adjacent)) { pending.add(adjacent); visited.add(adjacent); previous.put(adjacent, node); } } } } return new BFSResult(originNode, null, null); } /** * Detph First Search * @param originNode * @param value * @param visited * @return */ public static Node findNodeDFS(final Node originNode, final int value, final Set<Node> visited) { if (originNode == null || visited.contains(originNode)) { return null; } log.debug("visiting: " + originNode); visited.add(originNode); if (originNode.value == value) { log.debug("found it: " + value); return originNode; } if (originNode.adjacents != null) { for (final Node node : originNode.adjacents) { final Node foundNode = findNodeDFS(node, value, visited); if (foundNode != null) { return foundNode; } } } return null; } /** * DFS iterative * @param originNode * @param value * @return */ public static Node dfsIterative(final Node originNode, final int value) { final Set<Node> visited = new HashSet<>(); final Deque<Node> pending = new LinkedList<>(); pending.push(originNode); while (!pending.isEmpty()) { final Node pop = pending.pop(); if (!visited.contains(pop)) { visited.add(pop); System.out.println("Visiting: "+ pop.value); if (pop.value == value) { return pop; } } if (pop.adjacents != null) { for (final Node adj : pop.adjacents) { pending.addFirst(adj); } } } return null; } public static Graph cloneGraph(final Node node) { // Map of visited nodes, where k=node v=clone, so that there is only 1 clone per node final Map<Node, Node> visited = new HashMap<>(); final Queue<Node> pending = new LinkedList<>(); Node root = new Node(node.value); visited.put(node, root); pending.add(node); Node current, clone; while (!pending.isEmpty()) { current = pending.poll(); clone = visited.get(current); clone.adjacents = new ArrayList<>(); for (Node adjacent : current.adjacents) { Node adjacentClone = visited.get(adjacent); if (adjacentClone == null) { // Create new clone when it doesn't already exist adjacentClone = new Node(adjacent.value); } clone.adjacents.add(adjacentClone); if (!visited.containsKey(adjacent)) { pending.add(adjacent); visited.put(adjacent, adjacentClone); } } } return new Graph(root); } /** * * @param g */ public static Deque<Node> topologicalSort(Graph g) { final Deque<Node> stack = new LinkedList<>(); final Set<Node> visited = new LinkedHashSet<>(); for (Node root : g.roots) { if (!visited.contains(root)) { visitTopologicalSort(root, visited, stack); } } return stack; } private static void visitTopologicalSort(final Node node, final Set<Node> visited, final Deque<Node> stack) { visited.add(node); for (Node adj : node.adjacents) { if (!visited.contains(adj)) { visitTopologicalSort(adj, visited, stack); } } stack.push(node); } }
7,900
0.537848
0.537089
287
26.529617
22.941336
128
false
false
0
0
0
0
0
0
0.933798
false
false
9
f162121518aaf55422e421b22dd0e0d11a66e19a
23,218,593,272,841
2225e69b7a6851e66e7ef87352b601b92e9d4051
/app/src/main/java/com/carlosbaquero/notasapp/MainActivity.java
06b65ad091e30b179b7681ba897d2d7b8a2d550a
[]
no_license
ingkb/MovilNotas
https://github.com/ingkb/MovilNotas
a09cd555a8ffe8785933b93720f6d75abdc9a227
4d693f7e6cb2b7af90be8fc39a04252f47a4d83e
refs/heads/main
2023-05-13T22:14:46.660000
2020-10-10T22:14:21
2020-10-10T22:14:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.carlosbaquero.notasapp; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.carlosbaquero.notasapp.Helper.DataBaseHelper; public class MainActivity extends AppCompatActivity { DataBaseHelper myDb; Button btnRegistrar,btnNotas,btnEvals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDb = new DataBaseHelper(this); btnRegistrar = findViewById(R.id.btnGoToRegistrar); btnNotas = findViewById(R.id.btnGoToNotas); btnEvals = findViewById(R.id.btnGoToEvals); goToRegistrar(); goToNotas(); goToEvals(); } public void goToRegistrar(){ btnRegistrar.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegistroMateria.class); startActivity(intent); } } ); } public void goToNotas(){ btnNotas.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegistrarNotas.class); startActivity(intent); } } ); } public void goToEvals(){ btnEvals.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, VerEvaluaciones.class); startActivity(intent); } } ); } }
UTF-8
Java
2,004
java
MainActivity.java
Java
[]
null
[]
package com.carlosbaquero.notasapp; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.carlosbaquero.notasapp.Helper.DataBaseHelper; public class MainActivity extends AppCompatActivity { DataBaseHelper myDb; Button btnRegistrar,btnNotas,btnEvals; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myDb = new DataBaseHelper(this); btnRegistrar = findViewById(R.id.btnGoToRegistrar); btnNotas = findViewById(R.id.btnGoToNotas); btnEvals = findViewById(R.id.btnGoToEvals); goToRegistrar(); goToNotas(); goToEvals(); } public void goToRegistrar(){ btnRegistrar.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegistroMateria.class); startActivity(intent); } } ); } public void goToNotas(){ btnNotas.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegistrarNotas.class); startActivity(intent); } } ); } public void goToEvals(){ btnEvals.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, VerEvaluaciones.class); startActivity(intent); } } ); } }
2,004
0.562874
0.562874
67
28.925373
22.78669
93
false
false
0
0
0
0
0
0
0.477612
false
false
9
fdd1b066fab4e0fa81ce8de1dbfd0360f4435670
28,338,194,272,438
10cf7b94119b40e038e6776a70957fa059c36e98
/app/src/main/java/com/example/usuario/ejemplointentcamera/MainActivity.java
e0e33192fab6c4633b29ddb79c02adb568138084
[]
no_license
ngardue2/EjemploIntentCamera
https://github.com/ngardue2/EjemploIntentCamera
a536fa8bb1d85cf01ac88a94592599d437020b51
8f48c43b56a19d91568b030b6e8ee526a75a396c
refs/heads/master
2020-04-06T22:41:54.888000
2018-11-16T09:27:50
2018-11-16T09:27:50
157,837,167
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.usuario.ejemplointentcamera; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { static int VENGO_DE_LA_CAMARA = 1; static int VENGO_DE_LA_CAMARA_CON_FICHERO = 2; static final int PEDI_PERMISOS_PARA_ESCRIBIR = 3; Button captura; Button captura2; ImageView imageViewfoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); captura = (Button) findViewById(R.id.captura); captura2 = (Button) findViewById(R.id.button2); imageViewfoto = (ImageView)findViewById(R.id.imageView); captura.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent haceFoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(haceFoto.resolveActivity(getPackageManager())!=null){ startActivityForResult(haceFoto,VENGO_DE_LA_CAMARA); }else{ Toast.makeText(MainActivity.this, "Necesito un programa de hacer fotos.", Toast.LENGTH_SHORT).show(); } } }); captura2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pedirPermisoDeEscriturayHagoFoto(); } }); } void hacerFoto(){ Intent haceFoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(haceFoto.resolveActivity(getPackageManager())!=null){ File ficheroFoto = null; try { ficheroFoto = crearFicheroDeImagen(); } catch (IOException e) { e.printStackTrace(); } if(ficheroFoto!=null){ //cuando haga la foto la guarde en ese fichero haceFoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(ficheroFoto)); } startActivityForResult(haceFoto,VENGO_DE_LA_CAMARA_CON_FICHERO); }else{ Toast.makeText(MainActivity.this, "Necesito un programa de hacer fotos.", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if((requestCode == VENGO_DE_LA_CAMARA) && (resultCode == RESULT_OK)){ Bundle extras = data.getExtras(); Bitmap foto = (Bitmap) extras.get("data"); imageViewfoto.setImageBitmap(foto); } } void pedirPermisoDeEscriturayHagoFoto(){ if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE )!=PackageManager.PERMISSION_GRANTED){ if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){ }else{ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PEDI_PERMISOS_PARA_ESCRIBIR); } }else{ hacerFoto(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case PEDI_PERMISOS_PARA_ESCRIBIR: { if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ hacerFoto(); } else{ Toast.makeText(this, "Sin permisos, no funciona.", Toast.LENGTH_SHORT).show(); } return; } } } File crearFicheroDeImagen() throws IOException { String fecha = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date()); String nombreFichero = "MisFotos_"+fecha; File carpetaDeFotos = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(fecha,".jpg",carpetaDeFotos); return image; } }
UTF-8
Java
4,803
java
MainActivity.java
Java
[]
null
[]
package com.example.usuario.ejemplointentcamera; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { static int VENGO_DE_LA_CAMARA = 1; static int VENGO_DE_LA_CAMARA_CON_FICHERO = 2; static final int PEDI_PERMISOS_PARA_ESCRIBIR = 3; Button captura; Button captura2; ImageView imageViewfoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); captura = (Button) findViewById(R.id.captura); captura2 = (Button) findViewById(R.id.button2); imageViewfoto = (ImageView)findViewById(R.id.imageView); captura.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent haceFoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(haceFoto.resolveActivity(getPackageManager())!=null){ startActivityForResult(haceFoto,VENGO_DE_LA_CAMARA); }else{ Toast.makeText(MainActivity.this, "Necesito un programa de hacer fotos.", Toast.LENGTH_SHORT).show(); } } }); captura2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pedirPermisoDeEscriturayHagoFoto(); } }); } void hacerFoto(){ Intent haceFoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(haceFoto.resolveActivity(getPackageManager())!=null){ File ficheroFoto = null; try { ficheroFoto = crearFicheroDeImagen(); } catch (IOException e) { e.printStackTrace(); } if(ficheroFoto!=null){ //cuando haga la foto la guarde en ese fichero haceFoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(ficheroFoto)); } startActivityForResult(haceFoto,VENGO_DE_LA_CAMARA_CON_FICHERO); }else{ Toast.makeText(MainActivity.this, "Necesito un programa de hacer fotos.", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if((requestCode == VENGO_DE_LA_CAMARA) && (resultCode == RESULT_OK)){ Bundle extras = data.getExtras(); Bitmap foto = (Bitmap) extras.get("data"); imageViewfoto.setImageBitmap(foto); } } void pedirPermisoDeEscriturayHagoFoto(){ if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE )!=PackageManager.PERMISSION_GRANTED){ if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)){ }else{ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PEDI_PERMISOS_PARA_ESCRIBIR); } }else{ hacerFoto(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case PEDI_PERMISOS_PARA_ESCRIBIR: { if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ hacerFoto(); } else{ Toast.makeText(this, "Sin permisos, no funciona.", Toast.LENGTH_SHORT).show(); } return; } } } File crearFicheroDeImagen() throws IOException { String fecha = new SimpleDateFormat("yyMMdd_HHmmss").format(new Date()); String nombreFichero = "MisFotos_"+fecha; File carpetaDeFotos = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(fecha,".jpg",carpetaDeFotos); return image; } }
4,803
0.643348
0.640849
156
29.788462
31.750633
142
false
false
0
0
0
0
0
0
0.512821
false
false
9
1291a60ccdf7d1dab526e96715e8f80b311ca221
26,680,336,881,636
a5a42d46f316a502424a7864feaeef989be48345
/app/src/main/java/com/example/kamil/machininghelper/Adapters/SimilarAdapter.java
9ce2d0ad32e3131a2fc694068c127aa41063103f
[]
no_license
KamilSafin/Machining-Helper
https://github.com/KamilSafin/Machining-Helper
685b53e066547948cfcfb407756b72db2e167ab6
036fcb95089cf1ddb6e4e4c9cc06803998981d48
refs/heads/master
2020-09-20T05:26:48.025000
2017-04-14T19:32:46
2017-04-14T19:32:46
66,160,476
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.kamil.machininghelper.Adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.kamil.machininghelper.Activities.GCodeDetailActivity; import com.example.kamil.machininghelper.Model.GCode; import com.example.kamil.machininghelper.Model.GCodeLab; import com.example.kamil.machininghelper.R; import java.util.List; /** * Created by Kamil Safin on 9/25/2016. */ public class SimilarAdapter extends RecyclerView.Adapter<SimilarAdapter.SimilarHolder> { private Context mContext; private String[] mNames; private List<GCode> mGCodes; private int mIndex; public SimilarAdapter(Context context, int index) { mContext = context; mIndex = index; mGCodes = GCodeLab.getGCodeLab(mContext).getGCodes(); mNames = mGCodes.get(mIndex).getSimilar(); } @Override public SimilarHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.row_g_code_similar, parent, false); SimilarHolder similarHolder = new SimilarHolder(view); return similarHolder; } @Override public void onBindViewHolder(SimilarHolder holder, int position) { holder.bindView(mNames[position]); } @Override public int getItemCount() { return mNames.length; } class SimilarHolder extends RecyclerView.ViewHolder{ private TextView mName; public SimilarHolder(View itemView) { super(itemView); mName = (TextView) itemView.findViewById(R.id.g_code_text); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int index = 0; for (int j = 0; j < mGCodes.size(); j++) { if (mGCodes.get(j).getG().equals(mGCodes.get(mIndex).getSimilar()[getLayoutPosition()])) { index = j; } } Intent intent = GCodeDetailActivity.newIntent(mContext, index); mContext.startActivity(intent); } }); } public void bindView(String name){ mName.setText(name); } } }
UTF-8
Java
2,543
java
SimilarAdapter.java
Java
[ { "context": "lper.R;\n\nimport java.util.List;\n\n/**\n * Created by Kamil Safin on 9/25/2016.\n */\npublic class SimilarAdapter ext", "end": 571, "score": 0.9998394250869751, "start": 560, "tag": "NAME", "value": "Kamil Safin" } ]
null
[]
package com.example.kamil.machininghelper.Adapters; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.kamil.machininghelper.Activities.GCodeDetailActivity; import com.example.kamil.machininghelper.Model.GCode; import com.example.kamil.machininghelper.Model.GCodeLab; import com.example.kamil.machininghelper.R; import java.util.List; /** * Created by <NAME> on 9/25/2016. */ public class SimilarAdapter extends RecyclerView.Adapter<SimilarAdapter.SimilarHolder> { private Context mContext; private String[] mNames; private List<GCode> mGCodes; private int mIndex; public SimilarAdapter(Context context, int index) { mContext = context; mIndex = index; mGCodes = GCodeLab.getGCodeLab(mContext).getGCodes(); mNames = mGCodes.get(mIndex).getSimilar(); } @Override public SimilarHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.row_g_code_similar, parent, false); SimilarHolder similarHolder = new SimilarHolder(view); return similarHolder; } @Override public void onBindViewHolder(SimilarHolder holder, int position) { holder.bindView(mNames[position]); } @Override public int getItemCount() { return mNames.length; } class SimilarHolder extends RecyclerView.ViewHolder{ private TextView mName; public SimilarHolder(View itemView) { super(itemView); mName = (TextView) itemView.findViewById(R.id.g_code_text); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int index = 0; for (int j = 0; j < mGCodes.size(); j++) { if (mGCodes.get(j).getG().equals(mGCodes.get(mIndex).getSimilar()[getLayoutPosition()])) { index = j; } } Intent intent = GCodeDetailActivity.newIntent(mContext, index); mContext.startActivity(intent); } }); } public void bindView(String name){ mName.setText(name); } } }
2,538
0.640582
0.63665
83
29.638554
26.236908
114
false
false
0
0
0
0
0
0
0.53012
false
false
9
3c3a08533163b6f034e840d318bc4160ffb556dd
231,928,260,674
d91c1ebf7338fb1fbbb65edf963ba7a0f65ebf24
/homelike-security/homelike-security-demo/src/main/java/com/homelike/security/demo/rest/UserRest.java
a03b92bf3084d6f6d081db947cf597247bb5b7fe
[]
no_license
lj5635906/homelike
https://github.com/lj5635906/homelike
439c2ffb14b02fd18707f225ee8aa69912e25124
50d35a07054236cd8501e7cb8784d280c7ae83e1
refs/heads/master
2020-03-10T00:05:20.840000
2018-06-01T06:47:21
2018-06-01T06:47:21
129,073,449
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.homelike.security.demo.rest; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ${DESCRIPTION} * * @author roger * @email 190642964@qq.com * @create 2018-04-16 14:25 **/ @RestController @RequestMapping("/user") public class UserRest { @GetMapping("/user") public Authentication user(Authentication authentication) { return authentication; } }
UTF-8
Java
580
java
UserRest.java
Java
[ { "context": "estController;\n/**\n * ${DESCRIPTION}\n *\n * @author roger\n * @email 190642964@qq.com\n * @create 2018-04-16 ", "end": 325, "score": 0.9993984699249268, "start": 320, "tag": "USERNAME", "value": "roger" }, { "context": "*\n * ${DESCRIPTION}\n *\n * @author roger\n * ...
null
[]
package com.homelike.security.demo.rest; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * ${DESCRIPTION} * * @author roger * @email <EMAIL> * @create 2018-04-16 14:25 **/ @RestController @RequestMapping("/user") public class UserRest { @GetMapping("/user") public Authentication user(Authentication authentication) { return authentication; } }
571
0.760345
0.724138
22
25.363636
21.75806
63
false
false
0
0
0
0
0
0
0.272727
false
false
9
d77334e2beba3e50500d63c65ec3012aa74c8769
23,587,960,398,755
c0d1860a1d1174ffe863f0632b469292fcd8fc15
/app/src/main/java/com/chegou/motorista/MyWalletActivity.java
fa7ab3932e3de9bdaaf7e56210cb2dbc7a57d8ab
[ "Apache-2.0" ]
permissive
rutherlesdev/ChegouDrive
https://github.com/rutherlesdev/ChegouDrive
1d6c9d7fb63fc2cae24b7caedcfa4f3e3617b4f7
b17462cc0cb8f4f5d0c004ca37c3a67cab093cf4
refs/heads/main
2023-03-14T22:25:53.779000
2021-03-24T11:14:52
2021-03-24T11:14:52
351,040,230
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.chegou.motorista; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatCheckBox; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import com.adapter.files.WalletHistoryRecycleAdapter; import com.autofit.et.lib.AutoFitEditText; import com.general.files.CustomDialog; import com.general.files.DecimalDigitsInputFilter; import com.general.files.ExecuteWebServerUrl; import com.general.files.GeneralFunctions; import com.general.files.InternetConnection; import com.general.files.MyApp; import com.general.files.StartActProcess; import com.squareup.picasso.Picasso; import com.utils.CommonUtilities; import com.utils.Logger; import com.utils.Utils; import com.view.ErrorView; import com.view.GenerateAlertBox; import com.view.MButton; import com.view.MTextView; import com.view.MaterialRippleLayout; import com.view.SelectableRoundedImageView; import com.view.anim.loader.AVLoadingIndicatorView; import com.view.editBox.MaterialEditText; import org.json.JSONArray; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Timer; /** * Created by Admin on 04-11-2016. */ public class MyWalletActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { private final long DELAY = 1000; // in ms public GeneralFunctions generalFunc; MTextView titleTxt; ImageView backImgView; ProgressBar loading_wallet_history; MTextView viewTransactionsTxt; ErrorView errorView; String required_str = ""; String error_money_str = ""; String userProfileJson = ""; boolean mIsLoading = false; String next_page_str = "0"; // private MTextView policyTxt; // private MTextView termsTxt; private MTextView yourBalTxt; private MButton btn_type1; //private MTextView addMoneyTagTxt; private MTextView addMoneyTxt; private Timer timer = new Timer(); private static final int SEL_CARD = 004; public static final int TRANSFER_MONEY = 87; AppCompatCheckBox useBalChkBox; MTextView useBalanceTxt; InternetConnection intCheck; AVLoadingIndicatorView loaderView; WebView paymentWebview; // Go Pay view declaration start LinearLayout addTransferArea, ProfileImageArea; String transferState = "SEARCH"; MTextView sendMoneyTxt, transferMoneyTagTxt; RadioButton driverRadioBtn, userRadioBtn; RadioGroup rg_whomType; MaterialEditText detailBox, otpverificationCodeBox; FrameLayout verificationArea; LinearLayout infoArea; ImageView ic_back_arrow; MTextView whomTxt, userNameTxt, moneyTitleTxt; MButton btn_type3, btn_type4, btn_otp; SelectableRoundedImageView toUserImgView; CardView moneyDetailArea; LinearLayout transferMoneyAddDetailArea; String error_email_str = ""; String error_verification_code = ""; LinearLayout toWhomTransferArea; String isRegenerate = "No"; boolean isClicked = false; // Go Pay view declaration end CardView transerCardArea, addMoneyCardArea; LinearLayout addMoneyArea, transerArea, TransactionArea; MTextView transferTxt, transactionTxt, recentTransHTxt, noTransactionTxt; ArrayList<HashMap<String, String>> list = new ArrayList<>(); boolean isNextPageAvailable = false; RecyclerView recentTransactionRecyclerView; private WalletHistoryRecycleAdapter wallethistoryRecyclerAdapter; LinearLayout transferMoneyToWallet; String detailBoxVal = ""; LinearLayout resendOtpArea, otpArea, moneyArea; String iUserId = ""; String eUserType = ""; String verificationCode = ""; String username = ""; String userImage = ""; String userEmail = ""; String userPhone = ""; String amount = ""; String transactionDate = ""; LinearLayout WalletContentArea; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mywallet); generalFunc = MyApp.getInstance().getGeneralFun(getActContext()); intCheck = new InternetConnection(getActContext()); userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); WalletContentArea = (LinearLayout) findViewById(R.id.WalletContentArea); titleTxt = (MTextView) findViewById(R.id.titleTxt); backImgView = (ImageView) findViewById(R.id.backImgView); loading_wallet_history = (ProgressBar) findViewById(R.id.loading_wallet_history); viewTransactionsTxt = (MTextView) findViewById(R.id.viewTransactionsTxt); errorView = (ErrorView) findViewById(R.id.errorView); addMoneyTxt = (MTextView) findViewById(R.id.addMoneyTxt); //addMoneyTagTxt = (MTextView) findViewById(R.id.addMoneyTagTxt); addMoneyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_TXT")); errorView = (ErrorView) findViewById(R.id.errorView); // termsTxt = (MTextView) findViewById(R.id.termsTxt); yourBalTxt = (MTextView) findViewById(R.id.yourBalTxt); //policyTxt = (MTextView) findViewById(R.id.policyTxt); btn_type1 = ((MaterialRippleLayout) findViewById(R.id.btn_type1)).getChildView(); transerCardArea = (CardView) findViewById(R.id.transerCardArea); addMoneyCardArea = (CardView) findViewById(R.id.addMoneyCardArea); addMoneyArea = (LinearLayout) findViewById(R.id.addMoneyArea); transerArea = (LinearLayout) findViewById(R.id.transerArea); TransactionArea = (LinearLayout) findViewById(R.id.TransactionArea); transferTxt = (MTextView) findViewById(R.id.transferTxt); transactionTxt = (MTextView) findViewById(R.id.transactionTxt); recentTransHTxt = (MTextView) findViewById(R.id.recentTransHTxt); noTransactionTxt = (MTextView) findViewById(R.id.noTransactionTxt); recentTransactionRecyclerView = (RecyclerView) findViewById(R.id.recentTransactionRecyclerView); addMoneyArea.setOnClickListener(new setOnClickList()); transerArea.setOnClickListener(new setOnClickList()); TransactionArea.setOnClickListener(new setOnClickList()); useBalanceTxt = (MTextView) findViewById(R.id.useBalanceTxt); useBalChkBox = (AppCompatCheckBox) findViewById(R.id.useBalChkBox); paymentWebview = (WebView) findViewById(R.id.paymentWebview); loaderView = (AVLoadingIndicatorView) findViewById(R.id.loaderView); backImgView.setOnClickListener(new setOnClickList()); viewTransactionsTxt.setOnClickListener(new setOnClickList()); btn_type1.setId(Utils.generateViewId()); btn_type1.setOnClickListener(new setOnClickList()); //termsTxt.setOnClickListener(new setOnClickList()); setLabels(); useBalChkBox.setOnCheckedChangeListener(this); // getWalletBalDetails(); wallethistoryRecyclerAdapter = new WalletHistoryRecycleAdapter(getActContext(), list, generalFunc, false); recentTransactionRecyclerView.setAdapter(wallethistoryRecyclerAdapter); recentTransactionRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = recyclerView.getLayoutManager().getChildCount(); int totalItemCount = recyclerView.getLayoutManager().getItemCount(); int firstVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition(); int lastInScreen = firstVisibleItemPosition + visibleItemCount; if ((lastInScreen == totalItemCount) && !(mIsLoading) && isNextPageAvailable == true) { mIsLoading = true; wallethistoryRecyclerAdapter.addFooterView(); getRecentTransction(true); } else if (isNextPageAvailable == false) { wallethistoryRecyclerAdapter.removeFooterView(); } } }); getRecentTransction(false); if (getIntent().getBooleanExtra("isAddMoney", false)) { openAddMoneyDialog(); } else if (getIntent().getBooleanExtra("isSendMoney", false)) { openTransferDialog(); } showHideButton(""); } private void showHideButton(String setView) { boolean isOnlyCashEnabled = generalFunc.getJsonValue("APP_PAYMENT_MODE", userProfileJson).equalsIgnoreCase("Cash"); /*Go Pay Enabled Or Not - Delete Start if you don't want gopay */ boolean isTransferMoneyEnabled = generalFunc.retrieveValue(Utils.ENABLE_GOPAY_KEY).equalsIgnoreCase("Yes"); /*Go Pay Enabled Or Not - Delete End if you don't want gopay */ Log.e("isTransferMoneyEnabled", "::" + isTransferMoneyEnabled); if (TextUtils.isEmpty(setView)) { if (isOnlyCashEnabled) { transerCardArea.setVisibility(isTransferMoneyEnabled ? View.VISIBLE : View.GONE); addMoneyCardArea.setVisibility(View.GONE); } else if (!isOnlyCashEnabled) { transerCardArea.setVisibility(isTransferMoneyEnabled ? View.VISIBLE : View.GONE); } } /*Go Pay Enabled Or Not - Delete Start if you don't want gopay */ else if (setView.equalsIgnoreCase("add")) { removeValues(true); //rechargeBox.setText(""); btn_type1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); transferState = "SEARCH"; configureView(); transferMoneyToWallet.setVisibility(View.GONE); addTransferArea.setVisibility(View.VISIBLE); ProfileImageArea.setVisibility(View.VISIBLE); btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_TO") + " " + username); } else if (setView.equalsIgnoreCase("transfer")) { removeValues(true); btn_type1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); addTransferArea.setVisibility(View.GONE); ProfileImageArea.setVisibility(View.GONE); transferMoneyToWallet.setVisibility(View.VISIBLE); transferState = "SEARCH"; configureView(); btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_TXT")); } /*Go Pay Enabled Or Not - Delete End if you don't want gopay */ } // Go Pay implementation start // private void showUserInfoArea(boolean show) { // if (show) { // // // addTransferArea.setVisibility(View.VISIBLE); // transferMoneyToWallet.setVisibility(View.GONE); // } else { // addTransferArea.setVisibility(View.GONE); // transferMoneyToWallet.setVisibility(View.VISIBLE); // // } // } private void addAmountDetailArea(boolean show) { if (show) { LinearLayout.LayoutParams lyParams = (LinearLayout.LayoutParams) transferMoneyAddDetailArea.getLayoutParams(); lyParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; transferMoneyAddDetailArea.setLayoutParams(lyParams); } else { LinearLayout.LayoutParams lyParams = (LinearLayout.LayoutParams) transferMoneyAddDetailArea.getLayoutParams(); lyParams.height = 0; transferMoneyAddDetailArea.setLayoutParams(lyParams); } } private void configureView() { hideShowViews(transferState); if (transferState.equalsIgnoreCase("SEARCH")) { btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_Search")); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { userNameTxt.setText(username); Picasso.get().load(userImage).placeholder(R.mipmap.ic_no_pic_user).into(toUserImgView); // btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_PAYMENT_TXT")); transferMoneyToWallet.setVisibility(View.GONE); addTransferArea.setVisibility(View.VISIBLE); ProfileImageArea.setVisibility(View.VISIBLE); } else if (transferState.equalsIgnoreCase("VERIFY")) { // ((MTextView) findViewById(R.id.moneyAmountTxt)).setText(transferMap.containsKey("fAmount") ? transferMap.get("fAmount") : ""); btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_SUBMIT_TXT")); otpArea.setVisibility(View.VISIBLE); moneyArea.setVisibility(View.GONE); } } public void goback() { if (transferMoneyAddDetailArea.getHeight() != 0 && Utils.checkText(transferState) && !transferState.equalsIgnoreCase("SEARCH")) { if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { transferState = "SEARCH"; configureView(); } else if (transferState.equalsIgnoreCase("VERIFY")) { transferState = "ENTER_AMOUNT"; configureView(); } return; } onBackPressed(); } private void hideShowViews(String transferState) { // addAmountDetailArea(true); //ic_back_arrow.setOnClickListener(transferState.equalsIgnoreCase("SEARCH") ? null : new setOnClickList()); //ic_back_arrow.setVisibility(transferState.equalsIgnoreCase("SEARCH") ? View.GONE : View.VISIBLE); // removeValues(transferState.equalsIgnoreCase("SEARCH")); // showUserInfoArea(!transferState.equalsIgnoreCase("SEARCH")); // findViewById(R.id.resendOtpArea).setVisibility(View.GONE); // findViewById(R.id.resendOtpArea).setOnClickListener(null); } private void removeValues(boolean removeValues) { if (removeValues) { //detailBox.setText(""); //rechargeBox.setText(""); if (otpverificationCodeBox != null) { otpverificationCodeBox.setText(""); } iUserId = ""; eUserType = ""; verificationCode = ""; if (rg_whomType != null) { rg_whomType.clearCheck(); } } } private void transferMoneyToWallet() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("fromUserId", generalFunc.getMemberId()); parameters.put("fromUserType", Utils.userType); //parameters.put("transferType", emailRadioBtn.isChecked() ? "Email" : "Phone"); parameters.put("searchUserType", userRadioBtn.isChecked() ? "Passenger" : Utils.userType); parameters.put("UserType", Utils.userType); if (transferState.equalsIgnoreCase("SEARCH")) { parameters.put("type", "GopayCheckPhoneEmail"); parameters.put("vPhoneOrEmailTxt", detailBoxVal); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { parameters.put("type", "GoPayVerifyAmount"); parameters.put("isRegenerate", isRegenerate); parameters.put("fAmount", Utils.getText(autofitEditText)); parameters.put("toUserId", iUserId); parameters.put("toUserType", eUserType); } else if (transferState.equalsIgnoreCase("VERIFY")) { parameters.put("type", "GoPayTransferAmount"); parameters.put("toUserId", iUserId); parameters.put("toUserType", eUserType); parameters.put("fAmount", Utils.getText(autofitEditText)); } ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (isRegenerate.equalsIgnoreCase("Yes")) { isClicked = false; } if (responseString != null && !responseString.equals("")) { String action = generalFunc.getJsonValue(Utils.action_str, responseString); if (action.equals("1")) { String message = generalFunc.getJsonValue(Utils.message_str, responseString); if (transferState.equalsIgnoreCase("SEARCH")) { iUserId = generalFunc.getJsonValue("iUserId", message); eUserType = generalFunc.getJsonValue("eUserType", message); username = generalFunc.getJsonValue("vName", message); userImage = generalFunc.getJsonValue("vImgName", message); userEmail = generalFunc.getJsonValue("vEmail", message); userPhone = generalFunc.getJsonValue("vPhone", message); // transferMap.put("eUserTypeLBl", eUserType.equalsIgnoreCase("driver") ? generalFunc.retrieveLangLBl("", "LBL_DRIVER") : generalFunc.retrieveLangLBl("", "LBL_RIDER")); if (btn_type4 != null) { btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_TO") + " " + username); } transferState = "ENTER_AMOUNT"; configureView(); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { if (isRegenerate.equalsIgnoreCase("Yes")) { otpverificationCodeBox.setText(""); isRegenerate = "No"; resendOtpArea.setVisibility(View.GONE); resendOtpArea.setOnClickListener(null); } transferState = "VERIFY"; verificationCode = generalFunc.getJsonValue("verificationCode", message); String amount = String.format("%.2f", (double) generalFunc.parseDoubleValue(0.00, Utils.getText(autofitEditText))); this.amount = generalFunc.getJsonValue("CurrencySymbol", userProfileJson) + "" + generalFunc.convertNumberWithRTL(amount); ; //transferMap.put("fAmount", generalFunc.getJsonValue("CurrencySymbol", userProfileJson) + "" + generalFunc.convertNumberWithRTL(amount)); configureView(); } else if (transferState.equalsIgnoreCase("VERIFY")) { if (isRegenerate.equalsIgnoreCase("Yes")) { isRegenerate = "No"; resendOtpArea.setVisibility(View.GONE); resendOtpArea.setOnClickListener(null); } successDialog(generalFunc.retrieveLangLBl("", message), generalFunc.retrieveLangLBl("Ok", "LBL_BTN_OK_TXT")); } } else { String message = generalFunc.getJsonValue(Utils.message_str, responseString); String showAddMoney = generalFunc.getJsonValue("showAddMoney", responseString); if (transferState.equalsIgnoreCase("ENTER_AMOUNT") && (message.equalsIgnoreCase("LBL_WALLET_AMOUNT_GREATER_THAN_ZERO") || showAddMoney.equalsIgnoreCase("Yes"))) { final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", message)); boolean isOnlyCashEnabled = generalFunc.getJsonValue("APP_PAYMENT_MODE", userProfileJson).equalsIgnoreCase("Cash"); if (!isOnlyCashEnabled) { generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY")); } generateAlert.setNegativeBtn(!isOnlyCashEnabled ? generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT") : generalFunc.retrieveLangLBl("", "LBL_OK")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { generateAlert.closeAlertBox(); //must change openAddMoneyDialog(); dialog_transfer.dismiss(); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); return; } else if (transferState.equalsIgnoreCase("VERIFY")) { if (message.equalsIgnoreCase("LBL_OTP_EXPIRED")) { isRegenerate = "Yes"; resendOtpArea.setVisibility(View.VISIBLE); return; } //manage new for sucess dialog // removeValues(true); if (dialog_transfer != null) { dialog_transfer.dismiss(); } // successDialog(action.equalsIgnoreCase("2") ? message : generalFunc.retrieveLangLBl("", message), generalFunc.retrieveLangLBl("Ok", "LBL_BTN_OK_TXT")); generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue("message_profile_data", responseString)); transactionDate = generalFunc.getJsonValue("transactionDate", responseString); openSucessDialog(); } else { generalFunc.showGeneralMessage("", action.equalsIgnoreCase("2") ? message : generalFunc.retrieveLangLBl("", message)); } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } private void animateDialog(LinearLayout infoArea) { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_RETRIVE_OTP_TITLE_TXT")*/, generalFunc.retrieveLangLBl("", "LBL_TRANSFER_WALLET_OTP_INFO_TXT"), generalFunc.retrieveLangLBl("", "LBL_BTN_OK_TXT"), "", false, R.drawable.ic_normal_info, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_1); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } private void successDialog(String message, String positiveBtnTxt) { if (isRegenerate.equalsIgnoreCase("yes")) { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_OTP_EXPIRED_TXT")*/, message, positiveBtnTxt, "", false, R.drawable.ic_hand_gesture, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_2); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { otpverificationCodeBox.setText(""); resendOtpArea.setVisibility(View.VISIBLE); resendOtpArea.setOnClickListener(new setOnClickList()); } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } else { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_MONEY_TRANSFER_CONFIRMATION_TITLE_TXT")*/, message, positiveBtnTxt, "", false, R.drawable.ic_correct, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_2); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { transferState = "SEARCH"; configureView(); generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); list.clear(); getRecentTransction(false); // getWalletBalDetails(); } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } } // Go Pay implementation end public class myWebClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { String data = url; Logger.d("WebData", "::" + data); data = data.substring(data.indexOf("data") + 5, data.length()); try { String datajson = URLDecoder.decode(data, "UTF-8"); Logger.d("WebData", "::2222222::" + datajson); loaderView.setVisibility(View.VISIBLE); view.setOnTouchListener(null); if (url.contains("success=1")) { paymentWebview.setVisibility(View.GONE); //rechargeBox.setText(""); generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.retrieveLangLBl("", "LBL_WALLET_MONEY_CREDITED")), "", generalFunc.retrieveLangLBl("", "LBL_OK"), i -> { // isFinish = true; list.clear(); getRecentTransction(false); // getWalletBalDetails(); }); } if (url.contains("success=0")) { } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { generalFunc.showError(); loaderView.setVisibility(View.GONE); } @Override public void onPageFinished(WebView view, String url) { loaderView.setVisibility(View.GONE); view.setOnTouchListener((v, event) -> { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!v.hasFocus()) { v.requestFocus(); } break; } return false; }); } } public void setLabels() { titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_LEFT_MENU_WALLET")); yourBalTxt.setText(generalFunc.retrieveLangLBl("", "LBL_USER_BALANCE")); viewTransactionsTxt.setText(generalFunc.retrieveLangLBl("", "LBL_VIEW_TRANS_HISTORY")); btn_type1.setText(generalFunc.retrieveLangLBl("", "LBL_VIEW_TRANS_HISTORY")); useBalanceTxt.setText(generalFunc.retrieveLangLBl("", "LBL_USE_WALLET_BALANCE_NOTE")); // policyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_PRIVACY_POLICY")); //termsTxt.setText(generalFunc.retrieveLangLBl("", "LBL_PRIVACY_POLICY1")); required_str = generalFunc.retrieveLangLBl("", "LBL_FEILD_REQUIRD"); error_money_str = generalFunc.retrieveLangLBl("", "LBL_ADD_CORRECT_DETAIL_TXT"); if (generalFunc.getJsonValue("eWalletAdjustment", userProfileJson).equals("No")) { useBalChkBox.setChecked(false); } else { useBalChkBox.setChecked(true); } transferTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER")); transactionTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSACTIONS")); recentTransHTxt.setText(generalFunc.retrieveLangLBl("", "LBL_RECENT_TRANSACTION")); } public void UpdateUserWalletAdjustment(boolean value) { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "UpdateUserWalletAdjustment"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); parameters.put("eWalletAdjustment", value == true ? "Yes" : "No"); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setCancelAble(false); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail == true) { generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue(Utils.message_str, responseString)); userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); generalFunc.showMessage(generalFunc.getCurrentView((Activity) getActContext()), generalFunc.retrieveLangLBl("", "LBL_INFO_UPDATED_TXT")); } else { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); useBalChkBox.setOnCheckedChangeListener(null); useBalChkBox.setChecked(value == true ? false : true); useBalChkBox.setOnCheckedChangeListener(this); } } else { generalFunc.showError(); useBalChkBox.setOnCheckedChangeListener(null); useBalChkBox.setChecked(value == true ? false : true); useBalChkBox.setOnCheckedChangeListener(this); } }); exeWebServer.execute(); } // private void filterAddMoneyPrice() { // // if (Utils.checkText(rechargeBox) == true) { // String amount = "" + rechargeBox.getText().toString(); // Utils.removeInput(rechargeBox); // rechargeBox.setText("" + generalFunc.addSemiColonToPrice(amount.trim())); // } // // } public void checkValues(AutoFitEditText rechargeBox) { Double moneyAdded = 0.0; if (Utils.checkText(rechargeBox) == true) { moneyAdded = generalFunc.parseDoubleValue(0, Utils.getText(rechargeBox)); } boolean addMoneyAmountEntered = Utils.checkText(rechargeBox) ? (moneyAdded > 0 ? true : Utils.setErrorFields(rechargeBox, error_money_str)) : Utils.setErrorFields(rechargeBox, required_str); if (addMoneyAmountEntered == false) { return; } /*if (generalFunc.isDeliverOnlyEnabled()) { Bundle bn = new Bundle(); bn.putBoolean("isWallet", true); bn.putString("fAmount", Utils.getText(rechargeBox)); new StartActProcess(getActContext()).startActForResult(PaymentCardActivity.class, bn, SEL_CARD); } else {*/ if (generalFunc.getJsonValue("SYSTEM_PAYMENT_FLOW", userProfileJson).equalsIgnoreCase("Method-1")) { addMoneyToWallet(rechargeBox); } else if (!generalFunc.getJsonValue("SYSTEM_PAYMENT_FLOW", userProfileJson).equalsIgnoreCase("Method-1")) { dialog_add_money.dismiss(); String url = CommonUtilities.PAYMENTLINK + "amount=" + Utils.getText(rechargeBox) + "&iUserId=" + generalFunc.getMemberId() + "&UserType=" + Utils.app_type + "&vUserDeviceCountry=" + generalFunc.retrieveValue(Utils.DefaultCountryCode) + "&ccode=" + generalFunc.getJsonValue("vCurrencyDriver", userProfileJson) + "&UniqueCode=" + System.currentTimeMillis(); paymentWebview.setWebViewClient(new myWebClient()); paymentWebview.getSettings().setJavaScriptEnabled(true); paymentWebview.loadUrl(url); paymentWebview.setFocusable(true); paymentWebview.setVisibility(View.VISIBLE); loaderView.setVisibility(View.VISIBLE); } // } } private void addMoneyToWallet(AutoFitEditText rechargeBox) { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "addMoneyUserWallet"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("fAmount", Utils.getText(rechargeBox)); parameters.put("UserType", Utils.app_type); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail == true) { if (dialog_add_money != null) { dialog_add_money.dismiss(); } String memberBalance = generalFunc.getJsonValue("MemberBalance", responseString); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(memberBalance)); generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue(Utils.message_str, responseString)); generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str_one, responseString))); list.clear(); getRecentTransction(false); } else { String message = generalFunc.getJsonValue(Utils.message_str, responseString); if (message.equalsIgnoreCase("LBL_NO_CARD_AVAIL_NOTE")) { final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_ADD_CARD")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { if (dialog_add_money != null) { dialog_add_money.dismiss(); } generateAlert.closeAlertBox(); Bundle bn = new Bundle(); new StartActProcess(getActContext()).startActForResult(CardPaymentActivity.class, bn, Utils.CARD_PAYMENT_REQ_CODE); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); } else { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } @Override public void onBackPressed() { if (paymentWebview.getVisibility() == View.VISIBLE) { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", "LBL_CANCEL_PAYMENT_PROCESS"), generalFunc.retrieveLangLBl("", "LBL_NO"), generalFunc.retrieveLangLBl("", "LBL_YES"), buttonId -> { if (buttonId == 1) { paymentWebview.setVisibility(View.GONE); paymentWebview.stopLoading(); loaderView.setVisibility(View.GONE); } }); return; } super.onBackPressed(); } public void closeLoader() { if (loading_wallet_history.getVisibility() == View.VISIBLE) { loading_wallet_history.setVisibility(View.GONE); } } public void generateErrorView() { closeLoader(); generalFunc.generateErrorView(errorView, "LBL_ERROR_TXT", "LBL_NO_INTERNET_TXT"); if (errorView.getVisibility() != View.VISIBLE) { errorView.setVisibility(View.VISIBLE); } errorView.setOnRetryListener(() -> getTransactionHistory(false)); } public void getTransactionHistory(final boolean isLoadMore) { if (errorView.getVisibility() == View.VISIBLE) { errorView.setVisibility(View.GONE); } if (loading_wallet_history.getVisibility() != View.VISIBLE && isLoadMore == false) { loading_wallet_history.setVisibility(View.VISIBLE); } final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "getTransactionHistory"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); //parameters.put("TimeZone", generalFunc.getTimezone()); if (isLoadMore == true) { parameters.put("page", next_page_str); } final ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); String LBL_BALANCE = generalFunc.getJsonValue("user_available_balance", responseString); ((MTextView) findViewById(R.id.yourBalTxt)).setText(generalFunc.retrieveLangLBl("", "LBL_USER_BALANCE")); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(LBL_BALANCE)); } else { if (isLoadMore == false) { generateErrorView(); } } mIsLoading = false; }); exeWebServer.execute(); } public Context getActContext() { return MyWalletActivity.this; } @Override protected void onResume() { super.onResume(); // getWalletBalDetails(); Logger.d(",",""); } @Override protected void onDestroy() { // store prev service id if (getIntent().hasExtra("iServiceId")) { generalFunc.storeData(Utils.iServiceId_KEY, getIntent().getStringExtra("iServiceId")); } super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == SEL_CARD) { getTransactionHistory(false); } else if (resultCode == RESULT_OK && requestCode == TRANSFER_MONEY) { list.clear(); getRecentTransction(false); // getWalletBalDetails(); } } public void getWalletBalDetails() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "GetMemberWalletBalance"); parameters.put("iUserId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail) { try { String userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); JSONObject object = generalFunc.getJsonObject(userProfileJson); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("MemberBalance", responseString))); if (!generalFunc.getJsonValue("user_available_balance", userProfileJson).equalsIgnoreCase(generalFunc.getJsonValue("MemberBalance", responseString))) { generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); } } catch (Exception e) { } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) { UpdateUserWalletAdjustment(isCheck); } public class setOnClickList implements View.OnClickListener { @Override public void onClick(View view) { Utils.hideKeyboard(getActContext()); if (view.getId() == btn_type1.getId()) { new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); } switch (view.getId()) { case R.id.backImgView: onBackPressed(); break; case R.id.viewTransactionsTxt: new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); break; // case R.id.termsTxt: // Bundle bn = new Bundle(); // bn.putString("staticpage", "4"); // new StartActProcess(getActContext()).startActWithData(StaticPageActivity.class, bn); // break; case R.id.ic_back_arrow: goback(); break; // case R.id.addTransferBtnArea: // btn_type4.performClick(); // break; /*Go Pay view Click handling start*/ case R.id.viewTransactionsBtnArea: btn_type1.performClick(); break; case R.id.infoArea: animateDialog(infoArea); break; case R.id.resendOtpArea: if (!isClicked) { isClicked = true; isRegenerate = "Yes"; transferState = "ENTER_AMOUNT"; transferMoneyToWallet(); } break; case R.id.addMoneyArea: openAddMoneyDialog(); break; case R.id.transerArea: openTransferDialog(); break; case R.id.TransactionArea: new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); break; /*Go Pay view Click handling end*/ } } } public void getRecentTransction(final boolean isLoadMore) { if (errorView.getVisibility() == View.VISIBLE) { errorView.setVisibility(View.GONE); } if (loading_wallet_history.getVisibility() != View.VISIBLE && isLoadMore == false) { if (list.size() == 0) { loading_wallet_history.setVisibility(View.VISIBLE); } WalletContentArea.setVisibility(View.GONE); } final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "getTransactionHistory"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); parameters.put("ListType", Utils.Wallet_all); if (isLoadMore == true) { parameters.put("page", next_page_str); } noTransactionTxt.setVisibility(View.GONE); final ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setDataResponseListener(responseString -> { noTransactionTxt.setVisibility(View.GONE); if (responseString != null && !responseString.equals("")) { closeLoader(); if (generalFunc.checkDataAvail(Utils.action_str, responseString) == true) { String nextPage = generalFunc.getJsonValue("NextPage", responseString); JSONArray arr_transhistory = generalFunc.getJsonArray(Utils.message_str, responseString); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("MemberBalance", responseString))); if (!generalFunc.getJsonValue("user_available_balance", userProfileJson).equalsIgnoreCase(generalFunc.getJsonValue("MemberBalance", responseString))) { generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); } if (arr_transhistory != null && arr_transhistory.length() > 0) { for (int i = 0; i < arr_transhistory.length(); i++) { // for (int i = 0; i < 10; i++) { JSONObject obj_temp = generalFunc.getJsonObject(arr_transhistory, i); HashMap<String, String> map = new HashMap<String, String>(); map.put("iUserWalletId", generalFunc.getJsonValueStr("iUserWalletId", obj_temp)); map.put("iUserId", generalFunc.getJsonValueStr("iUserId", obj_temp)); map.put("eUserType", generalFunc.getJsonValueStr("eUserType", obj_temp)); map.put("eType", generalFunc.getJsonValueStr("eType", obj_temp)); map.put("iTripId", generalFunc.getJsonValueStr("iTripId", obj_temp)); map.put("eFor", generalFunc.getJsonValueStr("eFor", obj_temp)); String tDescription = generalFunc.getJsonValueStr("tDescription", obj_temp); map.put("tDescription", tDescription); map.put("tDescriptionConverted", generalFunc.convertNumberWithRTL(tDescription)); map.put("ePaymentStatus", generalFunc.getJsonValueStr("ePaymentStatus", obj_temp)); map.put("currentbal", generalFunc.getJsonValueStr("currentbal", obj_temp)); map.put("LBL_Status", generalFunc.retrieveLangLBl("", "LBL_Status")); map.put("LBL_TRIP_NO", generalFunc.retrieveLangLBl("", "LBL_TRIP_NO")); map.put("LBL_BALANCE_TYPE", generalFunc.retrieveLangLBl("", "LBL_BALANCE_TYPE")); map.put("LBL_DESCRIPTION", generalFunc.retrieveLangLBl("", "LBL_DESCRIPTION")); map.put("LBL_AMOUNT", generalFunc.retrieveLangLBl("", "LBL_AMOUNT")); String dDateOrig = generalFunc.getJsonValueStr("dDateOrig", obj_temp); map.put("dDateOrig", dDateOrig); map.put("listingFormattedDate", generalFunc.convertNumberWithRTL(generalFunc.getDateFormatedType(dDateOrig, Utils.OriginalDateFormate, CommonUtilities.OriginalDateFormate))); String iBalance = generalFunc.getJsonValueStr("iBalance", obj_temp); map.put("iBalance", iBalance); map.put("FormattediBalance", generalFunc.convertNumberWithRTL(iBalance)); list.add(map); } } if (!nextPage.equals("") && !nextPage.equals("0")) { next_page_str = nextPage; isNextPageAvailable = true; } else { removeNextPageConfig(); } wallethistoryRecyclerAdapter.notifyDataSetChanged(); } else { if (list.size() == 0) { removeNextPageConfig(); noTransactionTxt.setText(generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); noTransactionTxt.setVisibility(View.VISIBLE); } } wallethistoryRecyclerAdapter.notifyDataSetChanged(); } else { if (isLoadMore == false) { removeNextPageConfig(); generateErrorView(); } } mIsLoading = false; WalletContentArea.setVisibility(View.VISIBLE); }); if (!isLoadMore) { if (list.size() == 0) { exeWebServer.execute(); } } else { exeWebServer.execute(); } } public void removeNextPageConfig() { next_page_str = ""; isNextPageAvailable = false; mIsLoading = false; wallethistoryRecyclerAdapter.removeFooterView(); } Dialog dialog_add_money, dialog_transfer, dialog_sucess; MTextView otpInfoTxt; public void openTransferDialog() { dialog_transfer = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_transfer.setContentView(R.layout.design_transfer_money); /*Go Pay view initialization start*/ sendMoneyTxt = (MTextView) dialog_transfer.findViewById(R.id.sendMoneyTxt); resendOtpArea = (LinearLayout) dialog_transfer.findViewById(R.id.resendOtpArea); otpArea = (LinearLayout) dialog_transfer.findViewById(R.id.otpArea); moneyArea = (LinearLayout) dialog_transfer.findViewById(R.id.moneyArea); whomTxt = (MTextView) dialog_transfer.findViewById(R.id.whomTxt); transferMoneyTagTxt = (MTextView) dialog_transfer.findViewById(R.id.transferMoneyTagTxt); driverRadioBtn = (RadioButton) dialog_transfer.findViewById(R.id.driverRadioBtn); userRadioBtn = (RadioButton) dialog_transfer.findViewById(R.id.userRadioBtn); rg_whomType = (RadioGroup) dialog_transfer.findViewById(R.id.rg_whomType); detailBox = (MaterialEditText) dialog_transfer.findViewById(R.id.detailBox); verificationArea = (FrameLayout) dialog_transfer.findViewById(R.id.verificationArea); infoArea = (LinearLayout) dialog_transfer.findViewById(R.id.infoArea); otpverificationCodeBox = (MaterialEditText) dialog_transfer.findViewById(R.id.otpverificationCodeBox); moneyTitleTxt = (MTextView) dialog_transfer.findViewById(R.id.moneyTitleTxt); userNameTxt = (MTextView) dialog_transfer.findViewById(R.id.userNameTxt); toWhomTransferArea = (LinearLayout) dialog_transfer.findViewById(R.id.toWhomTransferArea); moneyDetailArea = (CardView) dialog_transfer.findViewById(R.id.moneyDetailArea); transferMoneyAddDetailArea = (LinearLayout) dialog_transfer.findViewById(R.id.transferMoneyAddDetailArea); toUserImgView = (SelectableRoundedImageView) dialog_transfer.findViewById(R.id.toUserImgView); btn_type3 = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_type3)).getChildView(); btn_type4 = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_type4)).getChildView(); btn_type4.setEnabled(false); btn_otp = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_otp)).getChildView(); MTextView cancelTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelTxt); MTextView cancelTransTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelTransTxt); MTextView cancelOtpTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelOtpTxt); MTextView addMoneyNote = (MTextView) dialog_transfer.findViewById(R.id.addMoneyNote); transferMoneyToWallet = (LinearLayout) dialog_transfer.findViewById(R.id.transferMoneyToWallet); autofitEditText = (AutoFitEditText) dialog_transfer.findViewById(R.id.autofitEditText); ImageView backTansImage = (ImageView) dialog_transfer.findViewById(R.id.backTansImage); otpInfoTxt = (MTextView) dialog_transfer.findViewById(R.id.otpInfoTxt); MTextView currencyTxt = (MTextView) dialog_transfer.findViewById(R.id.currencyTxt); if (generalFunc.isRTLmode()) { backTansImage.setRotation(180); } currencyTxt.setText(generalFunc.getJsonValue("vCurrencyDriver", userProfileJson)); cancelTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); cancelTransTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); cancelOtpTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_NEXT_TXT")); btn_otp.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_SUBMIT_TXT")); MTextView resendOtpTxt = (MTextView) dialog_transfer.findViewById(R.id.resendOtpTxt); resendOtpTxt.setText(generalFunc.retrieveLangLBl("", "LBL_RESEND_OTP_TXT")); addMoneyNote.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_MSG")); ic_back_arrow = (ImageView) dialog_transfer.findViewById(R.id.ic_back_arrow); addTransferArea = (LinearLayout) dialog_transfer.findViewById(R.id.addTransferArea); ProfileImageArea = (LinearLayout) dialog_transfer.findViewById(R.id.ProfileImageArea); infoArea.setOnClickListener(new setOnClickList()); // dialog_transfer.findViewById(R.id.viewTransactionsBtnArea).setOnClickListener(new setOnClickList()); addTransferArea.setOnClickListener(new setOnClickList()); rechargeBox = (MaterialEditText) dialog_transfer.findViewById(R.id.rechargeBox); //rechargeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT"), generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT")); // rechargeBox.setInputType(InputType.TYPE_CLASS_NUMBER); autofitEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); autofitEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)}); rechargeBox.setBackgroundResource(android.R.color.transparent); rechargeBox.setHideUnderline(true); rechargeBox.setTextSize(getActContext().getResources().getDimension(R.dimen._18ssp)); autofitEditText.setText(defaultAmountVal); autofitEditText.setTextColor(getActContext().getResources().getColor(R.color.black)); rechargeBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); ImageView minusImageView = (ImageView) dialog_transfer.findViewById(R.id.minusImageView); ImageView addImageView = (ImageView) dialog_transfer.findViewById(R.id.addImageView); addImageView.setOnClickListener(view -> mangePluseView(autofitEditText)); minusImageView.setOnClickListener(view -> mangeMinusView(autofitEditText)); /*Go Pay Label Start*/ sendMoneyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY")); whomTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_TO_WHOM")); transferMoneyTagTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY_TXT1")); otpInfoTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_WALLET_OTP_INFO_TXT")); otpInfoTxt.setVisibility(View.VISIBLE); String lblDriver = "LBL_DRIVER"; if (generalFunc.getJsonValue("APP_TYPE", userProfileJson).equalsIgnoreCase(Utils.CabGeneralTypeRide_Delivery_UberX) || generalFunc.getJsonValue("APP_TYPE", userProfileJson).equalsIgnoreCase(Utils.CabGeneralType_UberX)) { lblDriver = "LBL_PROVIDER"; } driverRadioBtn.setText(generalFunc.retrieveLangLBl("", lblDriver)); userRadioBtn.setText(generalFunc.retrieveLangLBl("", "LBL_RIDER")); detailBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_GO_PAY_EMAIL_OR_PHONE_TXT")); otpverificationCodeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_ENTER_GOPAY_VERIFICATION_CODE")); moneyTitleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_MONEY_TXT")); error_email_str = generalFunc.retrieveLangLBl("", "LBL_FEILD_EMAIL_ERROR_TXT"); error_verification_code = generalFunc.retrieveLangLBl("", "LBL_VERIFICATION_CODE_INVALID"); btn_type4.setId(Utils.generateViewId()); /*Go Pay Label End*/ /*Go Pay view initialization end*/ /*Go Pay view Click handling Start*/ btn_type3.setOnClickListener(v -> { transferState = "Search"; if (rg_whomType.getCheckedRadioButtonId() != driverRadioBtn.getId() && rg_whomType.getCheckedRadioButtonId() != userRadioBtn.getId()) { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", "LBL_SELECT_ANY_MEMBER_OPTION_TXT")); return; } boolean detailEntered = Utils.checkText(detailBox) ? true : Utils.setErrorFields(detailBox, required_str); if (detailEntered == false) { return; } String regexStr = "^[0-9]*$"; if (detailBox.getText().toString().trim().replace("+", "").matches(regexStr)) { if (detailEntered) { detailEntered = detailBox.length() >= 3 ? true : Utils.setErrorFields(detailBox, generalFunc.retrieveLangLBl("", "LBL_INVALID_MOBILE_NO")); } } else { detailEntered = Utils.checkText(detailBox) ? (generalFunc.isEmailValid(Utils.getText(detailBox)) ? true : Utils.setErrorFields(detailBox, error_email_str)) : Utils.setErrorFields(detailBox, required_str); } if (detailEntered == false) { return; } detailBoxVal = Utils.getText(detailBox); transferMoneyToWallet(); }); resendOtpArea.setOnClickListener(v -> { if (!isClicked) { isClicked = true; isRegenerate = "Yes"; transferState = "ENTER_AMOUNT"; transferMoneyToWallet(); } }); btn_type4.setOnClickListener(v -> { if (Utils.checkText(autofitEditText) == true && GeneralFunctions.parseDoubleValue(0, autofitEditText.getText().toString()) > 0) { } else { return; } Double moneyAdded = 0.0; if (Utils.checkText(autofitEditText) == true) { moneyAdded = generalFunc.parseDoubleValue(0, Utils.getText(autofitEditText)); } boolean addMoneyAmountEntered = Utils.checkText(autofitEditText) ? (moneyAdded > 0 ? true : Utils.setErrorFields(autofitEditText, error_money_str)) : Utils.setErrorFields(autofitEditText, required_str); if (addMoneyAmountEntered == false) { return; } final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", "LBL_CONFIRM_TRANSFER_TO_WALLET_TXT") + " " + generalFunc.retrieveLangLBl("", "LBL_CONFIRM_TRANSFER_TO_WALLET_TXT1") + " " + username); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_YES")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_NO")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { transferMoneyToWallet(); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); }); btn_otp.setOnClickListener(v -> { boolean isCodeEntered = Utils.checkText(otpverificationCodeBox) ? ((verificationCode.equalsIgnoreCase(Utils.getText(otpverificationCodeBox))) ? true : Utils.setErrorFields(otpverificationCodeBox, error_verification_code)) : Utils.setErrorFields(otpverificationCodeBox, required_str); if (isCodeEntered == false) { return; } transferMoneyToWallet(); }); autofitEditText.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) { manageButton(btn_type4, autofitEditText); } @Override public void afterTextChanged(Editable s) { if (autofitEditText.getText().length() == 1) { if (autofitEditText.getText().toString().contains(".")) { autofitEditText.setText("0."); autofitEditText.setSelection(autofitEditText.length()); } } } }); /*Go Pay view Click handling End*/ cancelTxt.setOnClickListener(view -> dialog_transfer.dismiss()); cancelTransTxt.setOnClickListener(view -> { // rechargeBox.setText("0.0"); // transferMoneyToWallet.setVisibility(View.VISIBLE); // addTransferArea.setVisibility(View.GONE); // ProfileImageArea.setVisibility(View.GONE); // transferState = "Search"; dialog_transfer.dismiss(); //goback(); }); backTansImage.setOnClickListener(view -> { if (otpArea.getVisibility() == View.VISIBLE) { moneyArea.setVisibility(View.VISIBLE); otpArea.setVisibility(View.GONE); transferState = "ENTER_AMOUNT"; } else { autofitEditText.setText(defaultAmountVal); transferMoneyToWallet.setVisibility(View.VISIBLE); addTransferArea.setVisibility(View.GONE); ProfileImageArea.setVisibility(View.GONE); transferState = "Search"; } }); cancelOtpTxt.setOnClickListener(view -> { // moneyArea.setVisibility(View.VISIBLE); // otpArea.setVisibility(View.GONE); // transferState = "ENTER_AMOUNT"; //goback(); dialog_transfer.dismiss(); }); dialog_transfer.setCanceledOnTouchOutside(true); Window window = dialog_transfer.getWindow(); window.setGravity(Gravity.BOTTOM); window.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); dialog_transfer.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); if (generalFunc.isRTLmode()) { dialog_transfer.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } dialog_transfer.show(); } MaterialEditText rechargeBox; AutoFitEditText autofitEditText; String defaultAmountVal = "0.00"; public void openAddMoneyDialog() { dialog_add_money = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_add_money.setContentView(R.layout.add_money_layout); MTextView titleTxt = (MTextView) dialog_add_money.findViewById(R.id.titleTxt); MTextView addMoneyNote = (MTextView) dialog_add_money.findViewById(R.id.addMoneyNote); ImageView minusImageView = (ImageView) dialog_add_money.findViewById(R.id.minusImageView); ImageView addImageView = (ImageView) dialog_add_money.findViewById(R.id.addImageView); MTextView addMoneybtn1 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn1); MTextView addMoneybtn2 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn2); MTextView addMoneybtn3 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn3); MTextView cancelTxt = (MTextView) dialog_add_money.findViewById(R.id.cancelTxt); MTextView currencyTxt = (MTextView) dialog_add_money.findViewById(R.id.currencyTxt); autofitEditText = (AutoFitEditText) dialog_add_money.findViewById(R.id.autofitEditText); rechargeBox = (MaterialEditText) dialog_add_money.findViewById(R.id.rechargeBox); //rechargeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT"), generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT")); // rechargeBox.setInputType(InputType.TYPE_CLASS_NUMBER); autofitEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); currencyTxt.setText(generalFunc.getJsonValue("vCurrencyDriver", userProfileJson)); autofitEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)}); rechargeBox.setBackgroundResource(android.R.color.transparent); rechargeBox.setHideUnderline(true); rechargeBox.setTextSize(getActContext().getResources().getDimension(R.dimen._18ssp)); autofitEditText.setText(defaultAmountVal); rechargeBox.setTextColor(getActContext().getResources().getColor(R.color.black)); rechargeBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY")); addMoneyNote.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_MSG")); addMoneybtn1.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_1", userProfileJson))); addMoneybtn2.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_2", userProfileJson))); addMoneybtn3.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_3", userProfileJson))); MButton btn_type2 = ((MaterialRippleLayout) dialog_add_money.findViewById(R.id.btn_type2)).getChildView(); btn_type2.setEnabled(false); btn_type2.setText(generalFunc.retrieveLangLBl("", "LBL_DONE")); cancelTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); autofitEditText.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) { manageButton(btn_type2, autofitEditText); } @Override public void afterTextChanged(Editable s) { if (autofitEditText.getText().length() == 1) { if (autofitEditText.getText().toString().contains(".")) { autofitEditText.setText("0."); autofitEditText.setSelection(autofitEditText.length()); } } } }); btn_type2.setOnClickListener(view -> manageButtonView(autofitEditText)); cancelTxt.setOnClickListener(view -> dialog_add_money.dismiss()); addImageView.setOnClickListener(view -> mangePluseView(autofitEditText)); minusImageView.setOnClickListener(view -> mangeMinusView(autofitEditText)); addMoneybtn1.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_1", userProfileJson))))); }); addMoneybtn2.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_2", userProfileJson))))); }); addMoneybtn3.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_3", userProfileJson))))); }); //dialog_add_money.setCanceledOnTouchOutside(true); Window window = dialog_add_money.getWindow(); window.setGravity(Gravity.BOTTOM); window.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); dialog_add_money.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); if (generalFunc.isRTLmode()) { dialog_add_money.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } dialog_add_money.show(); } public void manageButton(MButton btn, AutoFitEditText editText) { if (Utils.checkText(editText)) { if (generalFunc.parseDoubleValue(0, Utils.getText(editText)) > 0) { btn.setEnabled(true); } else { btn.setEnabled(false); } } else { btn.setEnabled(false); } } public void openSucessDialog() { dialog_sucess = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_sucess.setContentView(R.layout.sucess_layout); MTextView titleTxt = (MTextView) dialog_sucess.findViewById(R.id.titleTxt); MTextView msgTxt = (MTextView) dialog_sucess.findViewById(R.id.msgTxt); MTextView priceTxt = (MTextView) dialog_sucess.findViewById(R.id.priceTxt); MTextView nametxt = (MTextView) dialog_sucess.findViewById(R.id.nametxt); MTextView transDateTxt = (MTextView) dialog_sucess.findViewById(R.id.transDateTxt); MTextView transDateValTxt = (MTextView) dialog_sucess.findViewById(R.id.transDateValTxt); SelectableRoundedImageView UserImgView = (SelectableRoundedImageView) dialog_sucess.findViewById(R.id.UserImgView); transDateTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSACTION_DONE")); transDateValTxt.setText(generalFunc.convertNumberWithRTL(transactionDate)); msgTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY_TO") + " " + username); titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SUCCESSFULLY")); nametxt.setText(username); priceTxt.setText(amount); Picasso.get().load(userImage).placeholder(R.mipmap.ic_no_pic_user).into(UserImgView); MButton btn_type2 = ((MaterialRippleLayout) dialog_sucess.findViewById(R.id.btn_type2)).getChildView(); btn_type2.setText(generalFunc.retrieveLangLBl("", "LBL_DONE")); btn_type2.setOnClickListener(view -> { removeValues(true); //getWalletBalDetails(); list.clear(); getRecentTransction(false); dialog_sucess.dismiss(); }); dialog_sucess.show(); } public void manageButtonView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true && GeneralFunctions.parseDoubleValue(0, rechargeBox.getText().toString()) > 0) { checkValues(rechargeBox); rechargeBox.setText(defaultAmountVal); } } public void mangeMinusView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true && GeneralFunctions.parseDoubleValue(0, rechargeBox.getText().toString()) > 0) { rechargeBox.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.0, rechargeBox.getText().toString()) - 1))); } else { rechargeBox.setText(defaultAmountVal); } } public void mangePluseView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true) { rechargeBox.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.0, rechargeBox.getText().toString()) + 1))); } else { rechargeBox.setText("1.00"); } } }
UTF-8
Java
75,287
java
MyWalletActivity.java
Java
[ { "context": "ashMap;\nimport java.util.Timer;\n\n/**\n * Created by Admin on 04-11-2016.\n */\npublic class MyWalletActivity ", "end": 2208, "score": 0.82553631067276, "start": 2203, "tag": "USERNAME", "value": "Admin" }, { "context": "NTER_AMOUNT\")) {\n\n userNameTxt.se...
null
[]
package com.chegou.motorista; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatCheckBox; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import com.adapter.files.WalletHistoryRecycleAdapter; import com.autofit.et.lib.AutoFitEditText; import com.general.files.CustomDialog; import com.general.files.DecimalDigitsInputFilter; import com.general.files.ExecuteWebServerUrl; import com.general.files.GeneralFunctions; import com.general.files.InternetConnection; import com.general.files.MyApp; import com.general.files.StartActProcess; import com.squareup.picasso.Picasso; import com.utils.CommonUtilities; import com.utils.Logger; import com.utils.Utils; import com.view.ErrorView; import com.view.GenerateAlertBox; import com.view.MButton; import com.view.MTextView; import com.view.MaterialRippleLayout; import com.view.SelectableRoundedImageView; import com.view.anim.loader.AVLoadingIndicatorView; import com.view.editBox.MaterialEditText; import org.json.JSONArray; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Timer; /** * Created by Admin on 04-11-2016. */ public class MyWalletActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { private final long DELAY = 1000; // in ms public GeneralFunctions generalFunc; MTextView titleTxt; ImageView backImgView; ProgressBar loading_wallet_history; MTextView viewTransactionsTxt; ErrorView errorView; String required_str = ""; String error_money_str = ""; String userProfileJson = ""; boolean mIsLoading = false; String next_page_str = "0"; // private MTextView policyTxt; // private MTextView termsTxt; private MTextView yourBalTxt; private MButton btn_type1; //private MTextView addMoneyTagTxt; private MTextView addMoneyTxt; private Timer timer = new Timer(); private static final int SEL_CARD = 004; public static final int TRANSFER_MONEY = 87; AppCompatCheckBox useBalChkBox; MTextView useBalanceTxt; InternetConnection intCheck; AVLoadingIndicatorView loaderView; WebView paymentWebview; // Go Pay view declaration start LinearLayout addTransferArea, ProfileImageArea; String transferState = "SEARCH"; MTextView sendMoneyTxt, transferMoneyTagTxt; RadioButton driverRadioBtn, userRadioBtn; RadioGroup rg_whomType; MaterialEditText detailBox, otpverificationCodeBox; FrameLayout verificationArea; LinearLayout infoArea; ImageView ic_back_arrow; MTextView whomTxt, userNameTxt, moneyTitleTxt; MButton btn_type3, btn_type4, btn_otp; SelectableRoundedImageView toUserImgView; CardView moneyDetailArea; LinearLayout transferMoneyAddDetailArea; String error_email_str = ""; String error_verification_code = ""; LinearLayout toWhomTransferArea; String isRegenerate = "No"; boolean isClicked = false; // Go Pay view declaration end CardView transerCardArea, addMoneyCardArea; LinearLayout addMoneyArea, transerArea, TransactionArea; MTextView transferTxt, transactionTxt, recentTransHTxt, noTransactionTxt; ArrayList<HashMap<String, String>> list = new ArrayList<>(); boolean isNextPageAvailable = false; RecyclerView recentTransactionRecyclerView; private WalletHistoryRecycleAdapter wallethistoryRecyclerAdapter; LinearLayout transferMoneyToWallet; String detailBoxVal = ""; LinearLayout resendOtpArea, otpArea, moneyArea; String iUserId = ""; String eUserType = ""; String verificationCode = ""; String username = ""; String userImage = ""; String userEmail = ""; String userPhone = ""; String amount = ""; String transactionDate = ""; LinearLayout WalletContentArea; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mywallet); generalFunc = MyApp.getInstance().getGeneralFun(getActContext()); intCheck = new InternetConnection(getActContext()); userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); WalletContentArea = (LinearLayout) findViewById(R.id.WalletContentArea); titleTxt = (MTextView) findViewById(R.id.titleTxt); backImgView = (ImageView) findViewById(R.id.backImgView); loading_wallet_history = (ProgressBar) findViewById(R.id.loading_wallet_history); viewTransactionsTxt = (MTextView) findViewById(R.id.viewTransactionsTxt); errorView = (ErrorView) findViewById(R.id.errorView); addMoneyTxt = (MTextView) findViewById(R.id.addMoneyTxt); //addMoneyTagTxt = (MTextView) findViewById(R.id.addMoneyTagTxt); addMoneyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_TXT")); errorView = (ErrorView) findViewById(R.id.errorView); // termsTxt = (MTextView) findViewById(R.id.termsTxt); yourBalTxt = (MTextView) findViewById(R.id.yourBalTxt); //policyTxt = (MTextView) findViewById(R.id.policyTxt); btn_type1 = ((MaterialRippleLayout) findViewById(R.id.btn_type1)).getChildView(); transerCardArea = (CardView) findViewById(R.id.transerCardArea); addMoneyCardArea = (CardView) findViewById(R.id.addMoneyCardArea); addMoneyArea = (LinearLayout) findViewById(R.id.addMoneyArea); transerArea = (LinearLayout) findViewById(R.id.transerArea); TransactionArea = (LinearLayout) findViewById(R.id.TransactionArea); transferTxt = (MTextView) findViewById(R.id.transferTxt); transactionTxt = (MTextView) findViewById(R.id.transactionTxt); recentTransHTxt = (MTextView) findViewById(R.id.recentTransHTxt); noTransactionTxt = (MTextView) findViewById(R.id.noTransactionTxt); recentTransactionRecyclerView = (RecyclerView) findViewById(R.id.recentTransactionRecyclerView); addMoneyArea.setOnClickListener(new setOnClickList()); transerArea.setOnClickListener(new setOnClickList()); TransactionArea.setOnClickListener(new setOnClickList()); useBalanceTxt = (MTextView) findViewById(R.id.useBalanceTxt); useBalChkBox = (AppCompatCheckBox) findViewById(R.id.useBalChkBox); paymentWebview = (WebView) findViewById(R.id.paymentWebview); loaderView = (AVLoadingIndicatorView) findViewById(R.id.loaderView); backImgView.setOnClickListener(new setOnClickList()); viewTransactionsTxt.setOnClickListener(new setOnClickList()); btn_type1.setId(Utils.generateViewId()); btn_type1.setOnClickListener(new setOnClickList()); //termsTxt.setOnClickListener(new setOnClickList()); setLabels(); useBalChkBox.setOnCheckedChangeListener(this); // getWalletBalDetails(); wallethistoryRecyclerAdapter = new WalletHistoryRecycleAdapter(getActContext(), list, generalFunc, false); recentTransactionRecyclerView.setAdapter(wallethistoryRecyclerAdapter); recentTransactionRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = recyclerView.getLayoutManager().getChildCount(); int totalItemCount = recyclerView.getLayoutManager().getItemCount(); int firstVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition(); int lastInScreen = firstVisibleItemPosition + visibleItemCount; if ((lastInScreen == totalItemCount) && !(mIsLoading) && isNextPageAvailable == true) { mIsLoading = true; wallethistoryRecyclerAdapter.addFooterView(); getRecentTransction(true); } else if (isNextPageAvailable == false) { wallethistoryRecyclerAdapter.removeFooterView(); } } }); getRecentTransction(false); if (getIntent().getBooleanExtra("isAddMoney", false)) { openAddMoneyDialog(); } else if (getIntent().getBooleanExtra("isSendMoney", false)) { openTransferDialog(); } showHideButton(""); } private void showHideButton(String setView) { boolean isOnlyCashEnabled = generalFunc.getJsonValue("APP_PAYMENT_MODE", userProfileJson).equalsIgnoreCase("Cash"); /*Go Pay Enabled Or Not - Delete Start if you don't want gopay */ boolean isTransferMoneyEnabled = generalFunc.retrieveValue(Utils.ENABLE_GOPAY_KEY).equalsIgnoreCase("Yes"); /*Go Pay Enabled Or Not - Delete End if you don't want gopay */ Log.e("isTransferMoneyEnabled", "::" + isTransferMoneyEnabled); if (TextUtils.isEmpty(setView)) { if (isOnlyCashEnabled) { transerCardArea.setVisibility(isTransferMoneyEnabled ? View.VISIBLE : View.GONE); addMoneyCardArea.setVisibility(View.GONE); } else if (!isOnlyCashEnabled) { transerCardArea.setVisibility(isTransferMoneyEnabled ? View.VISIBLE : View.GONE); } } /*Go Pay Enabled Or Not - Delete Start if you don't want gopay */ else if (setView.equalsIgnoreCase("add")) { removeValues(true); //rechargeBox.setText(""); btn_type1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); transferState = "SEARCH"; configureView(); transferMoneyToWallet.setVisibility(View.GONE); addTransferArea.setVisibility(View.VISIBLE); ProfileImageArea.setVisibility(View.VISIBLE); btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_TO") + " " + username); } else if (setView.equalsIgnoreCase("transfer")) { removeValues(true); btn_type1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12); addTransferArea.setVisibility(View.GONE); ProfileImageArea.setVisibility(View.GONE); transferMoneyToWallet.setVisibility(View.VISIBLE); transferState = "SEARCH"; configureView(); btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_TXT")); } /*Go Pay Enabled Or Not - Delete End if you don't want gopay */ } // Go Pay implementation start // private void showUserInfoArea(boolean show) { // if (show) { // // // addTransferArea.setVisibility(View.VISIBLE); // transferMoneyToWallet.setVisibility(View.GONE); // } else { // addTransferArea.setVisibility(View.GONE); // transferMoneyToWallet.setVisibility(View.VISIBLE); // // } // } private void addAmountDetailArea(boolean show) { if (show) { LinearLayout.LayoutParams lyParams = (LinearLayout.LayoutParams) transferMoneyAddDetailArea.getLayoutParams(); lyParams.height = LinearLayout.LayoutParams.WRAP_CONTENT; transferMoneyAddDetailArea.setLayoutParams(lyParams); } else { LinearLayout.LayoutParams lyParams = (LinearLayout.LayoutParams) transferMoneyAddDetailArea.getLayoutParams(); lyParams.height = 0; transferMoneyAddDetailArea.setLayoutParams(lyParams); } } private void configureView() { hideShowViews(transferState); if (transferState.equalsIgnoreCase("SEARCH")) { btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_Search")); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { userNameTxt.setText(username); Picasso.get().load(userImage).placeholder(R.mipmap.ic_no_pic_user).into(toUserImgView); // btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_PAYMENT_TXT")); transferMoneyToWallet.setVisibility(View.GONE); addTransferArea.setVisibility(View.VISIBLE); ProfileImageArea.setVisibility(View.VISIBLE); } else if (transferState.equalsIgnoreCase("VERIFY")) { // ((MTextView) findViewById(R.id.moneyAmountTxt)).setText(transferMap.containsKey("fAmount") ? transferMap.get("fAmount") : ""); btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_SUBMIT_TXT")); otpArea.setVisibility(View.VISIBLE); moneyArea.setVisibility(View.GONE); } } public void goback() { if (transferMoneyAddDetailArea.getHeight() != 0 && Utils.checkText(transferState) && !transferState.equalsIgnoreCase("SEARCH")) { if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { transferState = "SEARCH"; configureView(); } else if (transferState.equalsIgnoreCase("VERIFY")) { transferState = "ENTER_AMOUNT"; configureView(); } return; } onBackPressed(); } private void hideShowViews(String transferState) { // addAmountDetailArea(true); //ic_back_arrow.setOnClickListener(transferState.equalsIgnoreCase("SEARCH") ? null : new setOnClickList()); //ic_back_arrow.setVisibility(transferState.equalsIgnoreCase("SEARCH") ? View.GONE : View.VISIBLE); // removeValues(transferState.equalsIgnoreCase("SEARCH")); // showUserInfoArea(!transferState.equalsIgnoreCase("SEARCH")); // findViewById(R.id.resendOtpArea).setVisibility(View.GONE); // findViewById(R.id.resendOtpArea).setOnClickListener(null); } private void removeValues(boolean removeValues) { if (removeValues) { //detailBox.setText(""); //rechargeBox.setText(""); if (otpverificationCodeBox != null) { otpverificationCodeBox.setText(""); } iUserId = ""; eUserType = ""; verificationCode = ""; if (rg_whomType != null) { rg_whomType.clearCheck(); } } } private void transferMoneyToWallet() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("fromUserId", generalFunc.getMemberId()); parameters.put("fromUserType", Utils.userType); //parameters.put("transferType", emailRadioBtn.isChecked() ? "Email" : "Phone"); parameters.put("searchUserType", userRadioBtn.isChecked() ? "Passenger" : Utils.userType); parameters.put("UserType", Utils.userType); if (transferState.equalsIgnoreCase("SEARCH")) { parameters.put("type", "GopayCheckPhoneEmail"); parameters.put("vPhoneOrEmailTxt", detailBoxVal); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { parameters.put("type", "GoPayVerifyAmount"); parameters.put("isRegenerate", isRegenerate); parameters.put("fAmount", Utils.getText(autofitEditText)); parameters.put("toUserId", iUserId); parameters.put("toUserType", eUserType); } else if (transferState.equalsIgnoreCase("VERIFY")) { parameters.put("type", "GoPayTransferAmount"); parameters.put("toUserId", iUserId); parameters.put("toUserType", eUserType); parameters.put("fAmount", Utils.getText(autofitEditText)); } ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (isRegenerate.equalsIgnoreCase("Yes")) { isClicked = false; } if (responseString != null && !responseString.equals("")) { String action = generalFunc.getJsonValue(Utils.action_str, responseString); if (action.equals("1")) { String message = generalFunc.getJsonValue(Utils.message_str, responseString); if (transferState.equalsIgnoreCase("SEARCH")) { iUserId = generalFunc.getJsonValue("iUserId", message); eUserType = generalFunc.getJsonValue("eUserType", message); username = generalFunc.getJsonValue("vName", message); userImage = generalFunc.getJsonValue("vImgName", message); userEmail = generalFunc.getJsonValue("vEmail", message); userPhone = generalFunc.getJsonValue("vPhone", message); // transferMap.put("eUserTypeLBl", eUserType.equalsIgnoreCase("driver") ? generalFunc.retrieveLangLBl("", "LBL_DRIVER") : generalFunc.retrieveLangLBl("", "LBL_RIDER")); if (btn_type4 != null) { btn_type4.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_TO") + " " + username); } transferState = "ENTER_AMOUNT"; configureView(); } else if (transferState.equalsIgnoreCase("ENTER_AMOUNT")) { if (isRegenerate.equalsIgnoreCase("Yes")) { otpverificationCodeBox.setText(""); isRegenerate = "No"; resendOtpArea.setVisibility(View.GONE); resendOtpArea.setOnClickListener(null); } transferState = "VERIFY"; verificationCode = generalFunc.getJsonValue("verificationCode", message); String amount = String.format("%.2f", (double) generalFunc.parseDoubleValue(0.00, Utils.getText(autofitEditText))); this.amount = generalFunc.getJsonValue("CurrencySymbol", userProfileJson) + "" + generalFunc.convertNumberWithRTL(amount); ; //transferMap.put("fAmount", generalFunc.getJsonValue("CurrencySymbol", userProfileJson) + "" + generalFunc.convertNumberWithRTL(amount)); configureView(); } else if (transferState.equalsIgnoreCase("VERIFY")) { if (isRegenerate.equalsIgnoreCase("Yes")) { isRegenerate = "No"; resendOtpArea.setVisibility(View.GONE); resendOtpArea.setOnClickListener(null); } successDialog(generalFunc.retrieveLangLBl("", message), generalFunc.retrieveLangLBl("Ok", "LBL_BTN_OK_TXT")); } } else { String message = generalFunc.getJsonValue(Utils.message_str, responseString); String showAddMoney = generalFunc.getJsonValue("showAddMoney", responseString); if (transferState.equalsIgnoreCase("ENTER_AMOUNT") && (message.equalsIgnoreCase("LBL_WALLET_AMOUNT_GREATER_THAN_ZERO") || showAddMoney.equalsIgnoreCase("Yes"))) { final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", message)); boolean isOnlyCashEnabled = generalFunc.getJsonValue("APP_PAYMENT_MODE", userProfileJson).equalsIgnoreCase("Cash"); if (!isOnlyCashEnabled) { generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY")); } generateAlert.setNegativeBtn(!isOnlyCashEnabled ? generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT") : generalFunc.retrieveLangLBl("", "LBL_OK")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { generateAlert.closeAlertBox(); //must change openAddMoneyDialog(); dialog_transfer.dismiss(); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); return; } else if (transferState.equalsIgnoreCase("VERIFY")) { if (message.equalsIgnoreCase("LBL_OTP_EXPIRED")) { isRegenerate = "Yes"; resendOtpArea.setVisibility(View.VISIBLE); return; } //manage new for sucess dialog // removeValues(true); if (dialog_transfer != null) { dialog_transfer.dismiss(); } // successDialog(action.equalsIgnoreCase("2") ? message : generalFunc.retrieveLangLBl("", message), generalFunc.retrieveLangLBl("Ok", "LBL_BTN_OK_TXT")); generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue("message_profile_data", responseString)); transactionDate = generalFunc.getJsonValue("transactionDate", responseString); openSucessDialog(); } else { generalFunc.showGeneralMessage("", action.equalsIgnoreCase("2") ? message : generalFunc.retrieveLangLBl("", message)); } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } private void animateDialog(LinearLayout infoArea) { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_RETRIVE_OTP_TITLE_TXT")*/, generalFunc.retrieveLangLBl("", "LBL_TRANSFER_WALLET_OTP_INFO_TXT"), generalFunc.retrieveLangLBl("", "LBL_BTN_OK_TXT"), "", false, R.drawable.ic_normal_info, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_1); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } private void successDialog(String message, String positiveBtnTxt) { if (isRegenerate.equalsIgnoreCase("yes")) { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_OTP_EXPIRED_TXT")*/, message, positiveBtnTxt, "", false, R.drawable.ic_hand_gesture, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_2); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { otpverificationCodeBox.setText(""); resendOtpArea.setVisibility(View.VISIBLE); resendOtpArea.setOnClickListener(new setOnClickList()); } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } else { CustomDialog customDialog = new CustomDialog(getActContext()); customDialog.setDetails(""/*generalFunc.retrieveLangLBl("","LBL_MONEY_TRANSFER_CONFIRMATION_TITLE_TXT")*/, message, positiveBtnTxt, "", false, R.drawable.ic_correct, false, 2); customDialog.setRoundedViewBackgroundColor(R.color.appThemeColor_1); customDialog.setRoundedViewBorderColor(R.color.white); customDialog.setImgStrokWidth(15); customDialog.setBtnRadius(10); customDialog.setIconTintColor(R.color.white); customDialog.setPositiveBtnBackColor(R.color.appThemeColor_2); customDialog.setPositiveBtnTextColor(R.color.white); customDialog.createDialog(); customDialog.setPositiveButtonClick(new com.general.files.Closure() { @Override public void exec() { transferState = "SEARCH"; configureView(); generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); list.clear(); getRecentTransction(false); // getWalletBalDetails(); } }); customDialog.setNegativeButtonClick(new com.general.files.Closure() { @Override public void exec() { } }); customDialog.show(); } } // Go Pay implementation end public class myWebClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { String data = url; Logger.d("WebData", "::" + data); data = data.substring(data.indexOf("data") + 5, data.length()); try { String datajson = URLDecoder.decode(data, "UTF-8"); Logger.d("WebData", "::2222222::" + datajson); loaderView.setVisibility(View.VISIBLE); view.setOnTouchListener(null); if (url.contains("success=1")) { paymentWebview.setVisibility(View.GONE); //rechargeBox.setText(""); generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.retrieveLangLBl("", "LBL_WALLET_MONEY_CREDITED")), "", generalFunc.retrieveLangLBl("", "LBL_OK"), i -> { // isFinish = true; list.clear(); getRecentTransction(false); // getWalletBalDetails(); }); } if (url.contains("success=0")) { } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { generalFunc.showError(); loaderView.setVisibility(View.GONE); } @Override public void onPageFinished(WebView view, String url) { loaderView.setVisibility(View.GONE); view.setOnTouchListener((v, event) -> { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!v.hasFocus()) { v.requestFocus(); } break; } return false; }); } } public void setLabels() { titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_LEFT_MENU_WALLET")); yourBalTxt.setText(generalFunc.retrieveLangLBl("", "LBL_USER_BALANCE")); viewTransactionsTxt.setText(generalFunc.retrieveLangLBl("", "LBL_VIEW_TRANS_HISTORY")); btn_type1.setText(generalFunc.retrieveLangLBl("", "LBL_VIEW_TRANS_HISTORY")); useBalanceTxt.setText(generalFunc.retrieveLangLBl("", "LBL_USE_WALLET_BALANCE_NOTE")); // policyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_PRIVACY_POLICY")); //termsTxt.setText(generalFunc.retrieveLangLBl("", "LBL_PRIVACY_POLICY1")); required_str = generalFunc.retrieveLangLBl("", "LBL_FEILD_REQUIRD"); error_money_str = generalFunc.retrieveLangLBl("", "LBL_ADD_CORRECT_DETAIL_TXT"); if (generalFunc.getJsonValue("eWalletAdjustment", userProfileJson).equals("No")) { useBalChkBox.setChecked(false); } else { useBalChkBox.setChecked(true); } transferTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER")); transactionTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSACTIONS")); recentTransHTxt.setText(generalFunc.retrieveLangLBl("", "LBL_RECENT_TRANSACTION")); } public void UpdateUserWalletAdjustment(boolean value) { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "UpdateUserWalletAdjustment"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); parameters.put("eWalletAdjustment", value == true ? "Yes" : "No"); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setCancelAble(false); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail == true) { generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue(Utils.message_str, responseString)); userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); generalFunc.showMessage(generalFunc.getCurrentView((Activity) getActContext()), generalFunc.retrieveLangLBl("", "LBL_INFO_UPDATED_TXT")); } else { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); useBalChkBox.setOnCheckedChangeListener(null); useBalChkBox.setChecked(value == true ? false : true); useBalChkBox.setOnCheckedChangeListener(this); } } else { generalFunc.showError(); useBalChkBox.setOnCheckedChangeListener(null); useBalChkBox.setChecked(value == true ? false : true); useBalChkBox.setOnCheckedChangeListener(this); } }); exeWebServer.execute(); } // private void filterAddMoneyPrice() { // // if (Utils.checkText(rechargeBox) == true) { // String amount = "" + rechargeBox.getText().toString(); // Utils.removeInput(rechargeBox); // rechargeBox.setText("" + generalFunc.addSemiColonToPrice(amount.trim())); // } // // } public void checkValues(AutoFitEditText rechargeBox) { Double moneyAdded = 0.0; if (Utils.checkText(rechargeBox) == true) { moneyAdded = generalFunc.parseDoubleValue(0, Utils.getText(rechargeBox)); } boolean addMoneyAmountEntered = Utils.checkText(rechargeBox) ? (moneyAdded > 0 ? true : Utils.setErrorFields(rechargeBox, error_money_str)) : Utils.setErrorFields(rechargeBox, required_str); if (addMoneyAmountEntered == false) { return; } /*if (generalFunc.isDeliverOnlyEnabled()) { Bundle bn = new Bundle(); bn.putBoolean("isWallet", true); bn.putString("fAmount", Utils.getText(rechargeBox)); new StartActProcess(getActContext()).startActForResult(PaymentCardActivity.class, bn, SEL_CARD); } else {*/ if (generalFunc.getJsonValue("SYSTEM_PAYMENT_FLOW", userProfileJson).equalsIgnoreCase("Method-1")) { addMoneyToWallet(rechargeBox); } else if (!generalFunc.getJsonValue("SYSTEM_PAYMENT_FLOW", userProfileJson).equalsIgnoreCase("Method-1")) { dialog_add_money.dismiss(); String url = CommonUtilities.PAYMENTLINK + "amount=" + Utils.getText(rechargeBox) + "&iUserId=" + generalFunc.getMemberId() + "&UserType=" + Utils.app_type + "&vUserDeviceCountry=" + generalFunc.retrieveValue(Utils.DefaultCountryCode) + "&ccode=" + generalFunc.getJsonValue("vCurrencyDriver", userProfileJson) + "&UniqueCode=" + System.currentTimeMillis(); paymentWebview.setWebViewClient(new myWebClient()); paymentWebview.getSettings().setJavaScriptEnabled(true); paymentWebview.loadUrl(url); paymentWebview.setFocusable(true); paymentWebview.setVisibility(View.VISIBLE); loaderView.setVisibility(View.VISIBLE); } // } } private void addMoneyToWallet(AutoFitEditText rechargeBox) { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "addMoneyUserWallet"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("fAmount", Utils.getText(rechargeBox)); parameters.put("UserType", Utils.app_type); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail == true) { if (dialog_add_money != null) { dialog_add_money.dismiss(); } String memberBalance = generalFunc.getJsonValue("MemberBalance", responseString); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(memberBalance)); generalFunc.storeData(Utils.USER_PROFILE_JSON, generalFunc.getJsonValue(Utils.message_str, responseString)); generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str_one, responseString))); list.clear(); getRecentTransction(false); } else { String message = generalFunc.getJsonValue(Utils.message_str, responseString); if (message.equalsIgnoreCase("LBL_NO_CARD_AVAIL_NOTE")) { final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_ADD_CARD")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { if (dialog_add_money != null) { dialog_add_money.dismiss(); } generateAlert.closeAlertBox(); Bundle bn = new Bundle(); new StartActProcess(getActContext()).startActForResult(CardPaymentActivity.class, bn, Utils.CARD_PAYMENT_REQ_CODE); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); } else { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } @Override public void onBackPressed() { if (paymentWebview.getVisibility() == View.VISIBLE) { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", "LBL_CANCEL_PAYMENT_PROCESS"), generalFunc.retrieveLangLBl("", "LBL_NO"), generalFunc.retrieveLangLBl("", "LBL_YES"), buttonId -> { if (buttonId == 1) { paymentWebview.setVisibility(View.GONE); paymentWebview.stopLoading(); loaderView.setVisibility(View.GONE); } }); return; } super.onBackPressed(); } public void closeLoader() { if (loading_wallet_history.getVisibility() == View.VISIBLE) { loading_wallet_history.setVisibility(View.GONE); } } public void generateErrorView() { closeLoader(); generalFunc.generateErrorView(errorView, "LBL_ERROR_TXT", "LBL_NO_INTERNET_TXT"); if (errorView.getVisibility() != View.VISIBLE) { errorView.setVisibility(View.VISIBLE); } errorView.setOnRetryListener(() -> getTransactionHistory(false)); } public void getTransactionHistory(final boolean isLoadMore) { if (errorView.getVisibility() == View.VISIBLE) { errorView.setVisibility(View.GONE); } if (loading_wallet_history.getVisibility() != View.VISIBLE && isLoadMore == false) { loading_wallet_history.setVisibility(View.VISIBLE); } final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "getTransactionHistory"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); //parameters.put("TimeZone", generalFunc.getTimezone()); if (isLoadMore == true) { parameters.put("page", next_page_str); } final ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); String LBL_BALANCE = generalFunc.getJsonValue("user_available_balance", responseString); ((MTextView) findViewById(R.id.yourBalTxt)).setText(generalFunc.retrieveLangLBl("", "LBL_USER_BALANCE")); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(LBL_BALANCE)); } else { if (isLoadMore == false) { generateErrorView(); } } mIsLoading = false; }); exeWebServer.execute(); } public Context getActContext() { return MyWalletActivity.this; } @Override protected void onResume() { super.onResume(); // getWalletBalDetails(); Logger.d(",",""); } @Override protected void onDestroy() { // store prev service id if (getIntent().hasExtra("iServiceId")) { generalFunc.storeData(Utils.iServiceId_KEY, getIntent().getStringExtra("iServiceId")); } super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == SEL_CARD) { getTransactionHistory(false); } else if (resultCode == RESULT_OK && requestCode == TRANSFER_MONEY) { list.clear(); getRecentTransction(false); // getWalletBalDetails(); } } public void getWalletBalDetails() { HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "GetMemberWalletBalance"); parameters.put("iUserId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setLoaderConfig(getActContext(), true, generalFunc); exeWebServer.setDataResponseListener(responseString -> { if (responseString != null && !responseString.equals("")) { closeLoader(); boolean isDataAvail = GeneralFunctions.checkDataAvail(Utils.action_str, responseString); if (isDataAvail) { try { String userProfileJson = generalFunc.retrieveValue(Utils.USER_PROFILE_JSON); JSONObject object = generalFunc.getJsonObject(userProfileJson); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("MemberBalance", responseString))); if (!generalFunc.getJsonValue("user_available_balance", userProfileJson).equalsIgnoreCase(generalFunc.getJsonValue("MemberBalance", responseString))) { generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); } } catch (Exception e) { } } } else { generalFunc.showError(); } }); exeWebServer.execute(); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isCheck) { UpdateUserWalletAdjustment(isCheck); } public class setOnClickList implements View.OnClickListener { @Override public void onClick(View view) { Utils.hideKeyboard(getActContext()); if (view.getId() == btn_type1.getId()) { new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); } switch (view.getId()) { case R.id.backImgView: onBackPressed(); break; case R.id.viewTransactionsTxt: new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); break; // case R.id.termsTxt: // Bundle bn = new Bundle(); // bn.putString("staticpage", "4"); // new StartActProcess(getActContext()).startActWithData(StaticPageActivity.class, bn); // break; case R.id.ic_back_arrow: goback(); break; // case R.id.addTransferBtnArea: // btn_type4.performClick(); // break; /*Go Pay view Click handling start*/ case R.id.viewTransactionsBtnArea: btn_type1.performClick(); break; case R.id.infoArea: animateDialog(infoArea); break; case R.id.resendOtpArea: if (!isClicked) { isClicked = true; isRegenerate = "Yes"; transferState = "ENTER_AMOUNT"; transferMoneyToWallet(); } break; case R.id.addMoneyArea: openAddMoneyDialog(); break; case R.id.transerArea: openTransferDialog(); break; case R.id.TransactionArea: new StartActProcess(getActContext()).startAct(MyWalletHistoryActivity.class); break; /*Go Pay view Click handling end*/ } } } public void getRecentTransction(final boolean isLoadMore) { if (errorView.getVisibility() == View.VISIBLE) { errorView.setVisibility(View.GONE); } if (loading_wallet_history.getVisibility() != View.VISIBLE && isLoadMore == false) { if (list.size() == 0) { loading_wallet_history.setVisibility(View.VISIBLE); } WalletContentArea.setVisibility(View.GONE); } final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("type", "getTransactionHistory"); parameters.put("iMemberId", generalFunc.getMemberId()); parameters.put("UserType", Utils.app_type); parameters.put("ListType", Utils.Wallet_all); if (isLoadMore == true) { parameters.put("page", next_page_str); } noTransactionTxt.setVisibility(View.GONE); final ExecuteWebServerUrl exeWebServer = new ExecuteWebServerUrl(getActContext(), parameters); exeWebServer.setDataResponseListener(responseString -> { noTransactionTxt.setVisibility(View.GONE); if (responseString != null && !responseString.equals("")) { closeLoader(); if (generalFunc.checkDataAvail(Utils.action_str, responseString) == true) { String nextPage = generalFunc.getJsonValue("NextPage", responseString); JSONArray arr_transhistory = generalFunc.getJsonArray(Utils.message_str, responseString); ((MTextView) findViewById(R.id.walletamountTxt)).setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("MemberBalance", responseString))); if (!generalFunc.getJsonValue("user_available_balance", userProfileJson).equalsIgnoreCase(generalFunc.getJsonValue("MemberBalance", responseString))) { generalFunc.storeData(Utils.ISWALLETBALNCECHANGE, "Yes"); } if (arr_transhistory != null && arr_transhistory.length() > 0) { for (int i = 0; i < arr_transhistory.length(); i++) { // for (int i = 0; i < 10; i++) { JSONObject obj_temp = generalFunc.getJsonObject(arr_transhistory, i); HashMap<String, String> map = new HashMap<String, String>(); map.put("iUserWalletId", generalFunc.getJsonValueStr("iUserWalletId", obj_temp)); map.put("iUserId", generalFunc.getJsonValueStr("iUserId", obj_temp)); map.put("eUserType", generalFunc.getJsonValueStr("eUserType", obj_temp)); map.put("eType", generalFunc.getJsonValueStr("eType", obj_temp)); map.put("iTripId", generalFunc.getJsonValueStr("iTripId", obj_temp)); map.put("eFor", generalFunc.getJsonValueStr("eFor", obj_temp)); String tDescription = generalFunc.getJsonValueStr("tDescription", obj_temp); map.put("tDescription", tDescription); map.put("tDescriptionConverted", generalFunc.convertNumberWithRTL(tDescription)); map.put("ePaymentStatus", generalFunc.getJsonValueStr("ePaymentStatus", obj_temp)); map.put("currentbal", generalFunc.getJsonValueStr("currentbal", obj_temp)); map.put("LBL_Status", generalFunc.retrieveLangLBl("", "LBL_Status")); map.put("LBL_TRIP_NO", generalFunc.retrieveLangLBl("", "LBL_TRIP_NO")); map.put("LBL_BALANCE_TYPE", generalFunc.retrieveLangLBl("", "LBL_BALANCE_TYPE")); map.put("LBL_DESCRIPTION", generalFunc.retrieveLangLBl("", "LBL_DESCRIPTION")); map.put("LBL_AMOUNT", generalFunc.retrieveLangLBl("", "LBL_AMOUNT")); String dDateOrig = generalFunc.getJsonValueStr("dDateOrig", obj_temp); map.put("dDateOrig", dDateOrig); map.put("listingFormattedDate", generalFunc.convertNumberWithRTL(generalFunc.getDateFormatedType(dDateOrig, Utils.OriginalDateFormate, CommonUtilities.OriginalDateFormate))); String iBalance = generalFunc.getJsonValueStr("iBalance", obj_temp); map.put("iBalance", iBalance); map.put("FormattediBalance", generalFunc.convertNumberWithRTL(iBalance)); list.add(map); } } if (!nextPage.equals("") && !nextPage.equals("0")) { next_page_str = nextPage; isNextPageAvailable = true; } else { removeNextPageConfig(); } wallethistoryRecyclerAdapter.notifyDataSetChanged(); } else { if (list.size() == 0) { removeNextPageConfig(); noTransactionTxt.setText(generalFunc.retrieveLangLBl("", generalFunc.getJsonValue(Utils.message_str, responseString))); noTransactionTxt.setVisibility(View.VISIBLE); } } wallethistoryRecyclerAdapter.notifyDataSetChanged(); } else { if (isLoadMore == false) { removeNextPageConfig(); generateErrorView(); } } mIsLoading = false; WalletContentArea.setVisibility(View.VISIBLE); }); if (!isLoadMore) { if (list.size() == 0) { exeWebServer.execute(); } } else { exeWebServer.execute(); } } public void removeNextPageConfig() { next_page_str = ""; isNextPageAvailable = false; mIsLoading = false; wallethistoryRecyclerAdapter.removeFooterView(); } Dialog dialog_add_money, dialog_transfer, dialog_sucess; MTextView otpInfoTxt; public void openTransferDialog() { dialog_transfer = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_transfer.setContentView(R.layout.design_transfer_money); /*Go Pay view initialization start*/ sendMoneyTxt = (MTextView) dialog_transfer.findViewById(R.id.sendMoneyTxt); resendOtpArea = (LinearLayout) dialog_transfer.findViewById(R.id.resendOtpArea); otpArea = (LinearLayout) dialog_transfer.findViewById(R.id.otpArea); moneyArea = (LinearLayout) dialog_transfer.findViewById(R.id.moneyArea); whomTxt = (MTextView) dialog_transfer.findViewById(R.id.whomTxt); transferMoneyTagTxt = (MTextView) dialog_transfer.findViewById(R.id.transferMoneyTagTxt); driverRadioBtn = (RadioButton) dialog_transfer.findViewById(R.id.driverRadioBtn); userRadioBtn = (RadioButton) dialog_transfer.findViewById(R.id.userRadioBtn); rg_whomType = (RadioGroup) dialog_transfer.findViewById(R.id.rg_whomType); detailBox = (MaterialEditText) dialog_transfer.findViewById(R.id.detailBox); verificationArea = (FrameLayout) dialog_transfer.findViewById(R.id.verificationArea); infoArea = (LinearLayout) dialog_transfer.findViewById(R.id.infoArea); otpverificationCodeBox = (MaterialEditText) dialog_transfer.findViewById(R.id.otpverificationCodeBox); moneyTitleTxt = (MTextView) dialog_transfer.findViewById(R.id.moneyTitleTxt); userNameTxt = (MTextView) dialog_transfer.findViewById(R.id.userNameTxt); toWhomTransferArea = (LinearLayout) dialog_transfer.findViewById(R.id.toWhomTransferArea); moneyDetailArea = (CardView) dialog_transfer.findViewById(R.id.moneyDetailArea); transferMoneyAddDetailArea = (LinearLayout) dialog_transfer.findViewById(R.id.transferMoneyAddDetailArea); toUserImgView = (SelectableRoundedImageView) dialog_transfer.findViewById(R.id.toUserImgView); btn_type3 = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_type3)).getChildView(); btn_type4 = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_type4)).getChildView(); btn_type4.setEnabled(false); btn_otp = ((MaterialRippleLayout) dialog_transfer.findViewById(R.id.btn_otp)).getChildView(); MTextView cancelTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelTxt); MTextView cancelTransTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelTransTxt); MTextView cancelOtpTxt = (MTextView) dialog_transfer.findViewById(R.id.cancelOtpTxt); MTextView addMoneyNote = (MTextView) dialog_transfer.findViewById(R.id.addMoneyNote); transferMoneyToWallet = (LinearLayout) dialog_transfer.findViewById(R.id.transferMoneyToWallet); autofitEditText = (AutoFitEditText) dialog_transfer.findViewById(R.id.autofitEditText); ImageView backTansImage = (ImageView) dialog_transfer.findViewById(R.id.backTansImage); otpInfoTxt = (MTextView) dialog_transfer.findViewById(R.id.otpInfoTxt); MTextView currencyTxt = (MTextView) dialog_transfer.findViewById(R.id.currencyTxt); if (generalFunc.isRTLmode()) { backTansImage.setRotation(180); } currencyTxt.setText(generalFunc.getJsonValue("vCurrencyDriver", userProfileJson)); cancelTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); cancelTransTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); cancelOtpTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); btn_type3.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_NEXT_TXT")); btn_otp.setText(generalFunc.retrieveLangLBl("", "LBL_BTN_SUBMIT_TXT")); MTextView resendOtpTxt = (MTextView) dialog_transfer.findViewById(R.id.resendOtpTxt); resendOtpTxt.setText(generalFunc.retrieveLangLBl("", "LBL_RESEND_OTP_TXT")); addMoneyNote.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_MSG")); ic_back_arrow = (ImageView) dialog_transfer.findViewById(R.id.ic_back_arrow); addTransferArea = (LinearLayout) dialog_transfer.findViewById(R.id.addTransferArea); ProfileImageArea = (LinearLayout) dialog_transfer.findViewById(R.id.ProfileImageArea); infoArea.setOnClickListener(new setOnClickList()); // dialog_transfer.findViewById(R.id.viewTransactionsBtnArea).setOnClickListener(new setOnClickList()); addTransferArea.setOnClickListener(new setOnClickList()); rechargeBox = (MaterialEditText) dialog_transfer.findViewById(R.id.rechargeBox); //rechargeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT"), generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT")); // rechargeBox.setInputType(InputType.TYPE_CLASS_NUMBER); autofitEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); autofitEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)}); rechargeBox.setBackgroundResource(android.R.color.transparent); rechargeBox.setHideUnderline(true); rechargeBox.setTextSize(getActContext().getResources().getDimension(R.dimen._18ssp)); autofitEditText.setText(defaultAmountVal); autofitEditText.setTextColor(getActContext().getResources().getColor(R.color.black)); rechargeBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); ImageView minusImageView = (ImageView) dialog_transfer.findViewById(R.id.minusImageView); ImageView addImageView = (ImageView) dialog_transfer.findViewById(R.id.addImageView); addImageView.setOnClickListener(view -> mangePluseView(autofitEditText)); minusImageView.setOnClickListener(view -> mangeMinusView(autofitEditText)); /*Go Pay Label Start*/ sendMoneyTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY")); whomTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_TO_WHOM")); transferMoneyTagTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY_TXT1")); otpInfoTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_WALLET_OTP_INFO_TXT")); otpInfoTxt.setVisibility(View.VISIBLE); String lblDriver = "LBL_DRIVER"; if (generalFunc.getJsonValue("APP_TYPE", userProfileJson).equalsIgnoreCase(Utils.CabGeneralTypeRide_Delivery_UberX) || generalFunc.getJsonValue("APP_TYPE", userProfileJson).equalsIgnoreCase(Utils.CabGeneralType_UberX)) { lblDriver = "LBL_PROVIDER"; } driverRadioBtn.setText(generalFunc.retrieveLangLBl("", lblDriver)); userRadioBtn.setText(generalFunc.retrieveLangLBl("", "LBL_RIDER")); detailBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_GO_PAY_EMAIL_OR_PHONE_TXT")); otpverificationCodeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_ENTER_GOPAY_VERIFICATION_CODE")); moneyTitleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSFER_MONEY_TXT")); error_email_str = generalFunc.retrieveLangLBl("", "LBL_FEILD_EMAIL_ERROR_TXT"); error_verification_code = generalFunc.retrieveLangLBl("", "LBL_VERIFICATION_CODE_INVALID"); btn_type4.setId(Utils.generateViewId()); /*Go Pay Label End*/ /*Go Pay view initialization end*/ /*Go Pay view Click handling Start*/ btn_type3.setOnClickListener(v -> { transferState = "Search"; if (rg_whomType.getCheckedRadioButtonId() != driverRadioBtn.getId() && rg_whomType.getCheckedRadioButtonId() != userRadioBtn.getId()) { generalFunc.showGeneralMessage("", generalFunc.retrieveLangLBl("", "LBL_SELECT_ANY_MEMBER_OPTION_TXT")); return; } boolean detailEntered = Utils.checkText(detailBox) ? true : Utils.setErrorFields(detailBox, required_str); if (detailEntered == false) { return; } String regexStr = "^[0-9]*$"; if (detailBox.getText().toString().trim().replace("+", "").matches(regexStr)) { if (detailEntered) { detailEntered = detailBox.length() >= 3 ? true : Utils.setErrorFields(detailBox, generalFunc.retrieveLangLBl("", "LBL_INVALID_MOBILE_NO")); } } else { detailEntered = Utils.checkText(detailBox) ? (generalFunc.isEmailValid(Utils.getText(detailBox)) ? true : Utils.setErrorFields(detailBox, error_email_str)) : Utils.setErrorFields(detailBox, required_str); } if (detailEntered == false) { return; } detailBoxVal = Utils.getText(detailBox); transferMoneyToWallet(); }); resendOtpArea.setOnClickListener(v -> { if (!isClicked) { isClicked = true; isRegenerate = "Yes"; transferState = "ENTER_AMOUNT"; transferMoneyToWallet(); } }); btn_type4.setOnClickListener(v -> { if (Utils.checkText(autofitEditText) == true && GeneralFunctions.parseDoubleValue(0, autofitEditText.getText().toString()) > 0) { } else { return; } Double moneyAdded = 0.0; if (Utils.checkText(autofitEditText) == true) { moneyAdded = generalFunc.parseDoubleValue(0, Utils.getText(autofitEditText)); } boolean addMoneyAmountEntered = Utils.checkText(autofitEditText) ? (moneyAdded > 0 ? true : Utils.setErrorFields(autofitEditText, error_money_str)) : Utils.setErrorFields(autofitEditText, required_str); if (addMoneyAmountEntered == false) { return; } final GenerateAlertBox generateAlert = new GenerateAlertBox(getActContext()); generateAlert.setContentMessage("", generalFunc.retrieveLangLBl("", "LBL_CONFIRM_TRANSFER_TO_WALLET_TXT") + " " + generalFunc.retrieveLangLBl("", "LBL_CONFIRM_TRANSFER_TO_WALLET_TXT1") + " " + username); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_YES")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_NO")); generateAlert.setBtnClickList(btn_id -> { if (btn_id == 1) { transferMoneyToWallet(); } else { generateAlert.closeAlertBox(); } }); generateAlert.showAlertBox(); }); btn_otp.setOnClickListener(v -> { boolean isCodeEntered = Utils.checkText(otpverificationCodeBox) ? ((verificationCode.equalsIgnoreCase(Utils.getText(otpverificationCodeBox))) ? true : Utils.setErrorFields(otpverificationCodeBox, error_verification_code)) : Utils.setErrorFields(otpverificationCodeBox, required_str); if (isCodeEntered == false) { return; } transferMoneyToWallet(); }); autofitEditText.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) { manageButton(btn_type4, autofitEditText); } @Override public void afterTextChanged(Editable s) { if (autofitEditText.getText().length() == 1) { if (autofitEditText.getText().toString().contains(".")) { autofitEditText.setText("0."); autofitEditText.setSelection(autofitEditText.length()); } } } }); /*Go Pay view Click handling End*/ cancelTxt.setOnClickListener(view -> dialog_transfer.dismiss()); cancelTransTxt.setOnClickListener(view -> { // rechargeBox.setText("0.0"); // transferMoneyToWallet.setVisibility(View.VISIBLE); // addTransferArea.setVisibility(View.GONE); // ProfileImageArea.setVisibility(View.GONE); // transferState = "Search"; dialog_transfer.dismiss(); //goback(); }); backTansImage.setOnClickListener(view -> { if (otpArea.getVisibility() == View.VISIBLE) { moneyArea.setVisibility(View.VISIBLE); otpArea.setVisibility(View.GONE); transferState = "ENTER_AMOUNT"; } else { autofitEditText.setText(defaultAmountVal); transferMoneyToWallet.setVisibility(View.VISIBLE); addTransferArea.setVisibility(View.GONE); ProfileImageArea.setVisibility(View.GONE); transferState = "Search"; } }); cancelOtpTxt.setOnClickListener(view -> { // moneyArea.setVisibility(View.VISIBLE); // otpArea.setVisibility(View.GONE); // transferState = "ENTER_AMOUNT"; //goback(); dialog_transfer.dismiss(); }); dialog_transfer.setCanceledOnTouchOutside(true); Window window = dialog_transfer.getWindow(); window.setGravity(Gravity.BOTTOM); window.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); dialog_transfer.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); if (generalFunc.isRTLmode()) { dialog_transfer.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } dialog_transfer.show(); } MaterialEditText rechargeBox; AutoFitEditText autofitEditText; String defaultAmountVal = "0.00"; public void openAddMoneyDialog() { dialog_add_money = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_add_money.setContentView(R.layout.add_money_layout); MTextView titleTxt = (MTextView) dialog_add_money.findViewById(R.id.titleTxt); MTextView addMoneyNote = (MTextView) dialog_add_money.findViewById(R.id.addMoneyNote); ImageView minusImageView = (ImageView) dialog_add_money.findViewById(R.id.minusImageView); ImageView addImageView = (ImageView) dialog_add_money.findViewById(R.id.addImageView); MTextView addMoneybtn1 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn1); MTextView addMoneybtn2 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn2); MTextView addMoneybtn3 = (MTextView) dialog_add_money.findViewById(R.id.addMoneybtn3); MTextView cancelTxt = (MTextView) dialog_add_money.findViewById(R.id.cancelTxt); MTextView currencyTxt = (MTextView) dialog_add_money.findViewById(R.id.currencyTxt); autofitEditText = (AutoFitEditText) dialog_add_money.findViewById(R.id.autofitEditText); rechargeBox = (MaterialEditText) dialog_add_money.findViewById(R.id.rechargeBox); //rechargeBox.setBothText(generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT"), generalFunc.retrieveLangLBl("", "LBL_RECHARGE_AMOUNT_TXT")); // rechargeBox.setInputType(InputType.TYPE_CLASS_NUMBER); autofitEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); currencyTxt.setText(generalFunc.getJsonValue("vCurrencyDriver", userProfileJson)); autofitEditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)}); rechargeBox.setBackgroundResource(android.R.color.transparent); rechargeBox.setHideUnderline(true); rechargeBox.setTextSize(getActContext().getResources().getDimension(R.dimen._18ssp)); autofitEditText.setText(defaultAmountVal); rechargeBox.setTextColor(getActContext().getResources().getColor(R.color.black)); rechargeBox.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY")); addMoneyNote.setText(generalFunc.retrieveLangLBl("", "LBL_ADD_MONEY_MSG")); addMoneybtn1.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_1", userProfileJson))); addMoneybtn2.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_2", userProfileJson))); addMoneybtn3.setText(generalFunc.convertNumberWithRTL(generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_3", userProfileJson))); MButton btn_type2 = ((MaterialRippleLayout) dialog_add_money.findViewById(R.id.btn_type2)).getChildView(); btn_type2.setEnabled(false); btn_type2.setText(generalFunc.retrieveLangLBl("", "LBL_DONE")); cancelTxt.setText(generalFunc.retrieveLangLBl("", "LBL_CANCEL_TXT")); autofitEditText.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) { manageButton(btn_type2, autofitEditText); } @Override public void afterTextChanged(Editable s) { if (autofitEditText.getText().length() == 1) { if (autofitEditText.getText().toString().contains(".")) { autofitEditText.setText("0."); autofitEditText.setSelection(autofitEditText.length()); } } } }); btn_type2.setOnClickListener(view -> manageButtonView(autofitEditText)); cancelTxt.setOnClickListener(view -> dialog_add_money.dismiss()); addImageView.setOnClickListener(view -> mangePluseView(autofitEditText)); minusImageView.setOnClickListener(view -> mangeMinusView(autofitEditText)); addMoneybtn1.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_1", userProfileJson))))); }); addMoneybtn2.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_2", userProfileJson))))); }); addMoneybtn3.setOnClickListener(v -> { autofitEditText.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.00, generalFunc.getJsonValue("WALLET_FIXED_AMOUNT_3", userProfileJson))))); }); //dialog_add_money.setCanceledOnTouchOutside(true); Window window = dialog_add_money.getWindow(); window.setGravity(Gravity.BOTTOM); window.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); dialog_add_money.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); if (generalFunc.isRTLmode()) { dialog_add_money.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } dialog_add_money.show(); } public void manageButton(MButton btn, AutoFitEditText editText) { if (Utils.checkText(editText)) { if (generalFunc.parseDoubleValue(0, Utils.getText(editText)) > 0) { btn.setEnabled(true); } else { btn.setEnabled(false); } } else { btn.setEnabled(false); } } public void openSucessDialog() { dialog_sucess = new Dialog(getActContext(), R.style.ImageSourceDialogStyle); dialog_sucess.setContentView(R.layout.sucess_layout); MTextView titleTxt = (MTextView) dialog_sucess.findViewById(R.id.titleTxt); MTextView msgTxt = (MTextView) dialog_sucess.findViewById(R.id.msgTxt); MTextView priceTxt = (MTextView) dialog_sucess.findViewById(R.id.priceTxt); MTextView nametxt = (MTextView) dialog_sucess.findViewById(R.id.nametxt); MTextView transDateTxt = (MTextView) dialog_sucess.findViewById(R.id.transDateTxt); MTextView transDateValTxt = (MTextView) dialog_sucess.findViewById(R.id.transDateValTxt); SelectableRoundedImageView UserImgView = (SelectableRoundedImageView) dialog_sucess.findViewById(R.id.UserImgView); transDateTxt.setText(generalFunc.retrieveLangLBl("", "LBL_TRANSACTION_DONE")); transDateValTxt.setText(generalFunc.convertNumberWithRTL(transactionDate)); msgTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SEND_MONEY_TO") + " " + username); titleTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SUCCESSFULLY")); nametxt.setText(username); priceTxt.setText(amount); Picasso.get().load(userImage).placeholder(R.mipmap.ic_no_pic_user).into(UserImgView); MButton btn_type2 = ((MaterialRippleLayout) dialog_sucess.findViewById(R.id.btn_type2)).getChildView(); btn_type2.setText(generalFunc.retrieveLangLBl("", "LBL_DONE")); btn_type2.setOnClickListener(view -> { removeValues(true); //getWalletBalDetails(); list.clear(); getRecentTransction(false); dialog_sucess.dismiss(); }); dialog_sucess.show(); } public void manageButtonView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true && GeneralFunctions.parseDoubleValue(0, rechargeBox.getText().toString()) > 0) { checkValues(rechargeBox); rechargeBox.setText(defaultAmountVal); } } public void mangeMinusView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true && GeneralFunctions.parseDoubleValue(0, rechargeBox.getText().toString()) > 0) { rechargeBox.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.0, rechargeBox.getText().toString()) - 1))); } else { rechargeBox.setText(defaultAmountVal); } } public void mangePluseView(AutoFitEditText rechargeBox) { if (Utils.checkText(rechargeBox) == true) { rechargeBox.setText(String.format("%.2f", (double) (GeneralFunctions.parseDoubleValue(0.0, rechargeBox.getText().toString()) + 1))); } else { rechargeBox.setText("1.00"); } } }
75,287
0.619629
0.616972
1,806
40.6866
39.047695
267
false
false
0
0
0
0
0
0
0.714286
false
false
9
cab30e9258f955f41af2a20cca5155d7cfecf7da
26,560,077,816,122
279bffecb84102ab7a91726607a5e4c1d18e961f
/personalcenter/personalcenter-component/src/main/java/com/qcloud/component/personalcenter/model/query/MySignInRecordQuery.java
21fa8d07727d4f84bc62e5ecf2a3daf2e6888c32
[]
no_license
ChiRains/forest
https://github.com/ChiRains/forest
8b71de51c477f66a134d9b515b58039a8c94c2ee
cf0b41ff83e4cee281078afe338bba792de05052
refs/heads/master
2021-01-19T07:13:19.597000
2016-08-18T01:35:54
2016-08-18T01:35:54
65,869,894
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qcloud.component.personalcenter.model.query; public class MySignInRecordQuery { public MySignInRecordQuery(){ } }
UTF-8
Java
140
java
MySignInRecordQuery.java
Java
[]
null
[]
package com.qcloud.component.personalcenter.model.query; public class MySignInRecordQuery { public MySignInRecordQuery(){ } }
140
0.742857
0.742857
8
15.5
20.236107
56
false
false
0
0
0
0
0
0
0.5
false
false
9
4063374301ee1e8ed0dfd757368c59df2e595a0b
26,560,077,813,567
994404ccc26cd13d28e76e6a36e0e461f6c99b8e
/common/src/main/java/com/github/raduciumag/shapeshift/model/server/ServerType.java
fb2943728493dc7f5f75deb24e6b89a2a3f0d76d
[ "MIT" ]
permissive
RaduCiumag/shapeshift
https://github.com/RaduCiumag/shapeshift
a31ff08ddd068ac35c85f32fb9a70d70e95abe9f
d745aea91761936e92d8b42ee02a8ffc096dba08
refs/heads/master
2020-03-03T13:08:35.006000
2016-06-26T21:53:59
2016-06-26T21:53:59
50,536,182
0
0
null
false
2016-06-26T21:53:59
2016-01-27T20:39:02
2016-03-03T09:40:22
2016-06-26T21:53:59
448
0
0
0
Java
null
null
package com.github.raduciumag.shapeshift.model.server; public enum ServerType { HTTP }
UTF-8
Java
93
java
ServerType.java
Java
[ { "context": "package com.github.raduciumag.shapeshift.model.server;\n\npublic enum ServerType ", "end": 29, "score": 0.998343288898468, "start": 19, "tag": "USERNAME", "value": "raduciumag" } ]
null
[]
package com.github.raduciumag.shapeshift.model.server; public enum ServerType { HTTP }
93
0.763441
0.763441
6
14.5
19.559738
54
false
false
0
0
0
0
0
0
0.166667
false
false
9
cea42d23c2f50bb75d235387cbfc9340326c25fd
3,899,830,373,267
ea32accfc36b56c1e784d4ed39de2e172981c56e
/src/main/java/com/escape/common/MailAdaptor.java
4ddd65a861ed77609fd74d89621e35c48ba9d183
[]
no_license
acerian31/natures
https://github.com/acerian31/natures
9789fd8d52bb6a21cf7b7e6cde4e3c95f20d72cf
cd109e6fa028b48a1467d6fb577a2a47b04a0ad8
refs/heads/master
2022-12-26T19:23:17.673000
2020-02-28T05:25:06
2020-02-28T05:25:06
243,464,949
0
0
null
false
2022-12-16T10:00:55
2020-02-27T08:09:12
2020-02-28T05:25:09
2022-12-16T10:00:52
5,874
0
0
6
Java
false
false
package com.escape.common; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.multipart.MultipartFile; import com.escape.batch.SendZCTask; /** * Project Name : KTH API Store * Developer : JongSeong Park * Create Date : 2012. 10. 29. * 2012. 10. 29./Famz : created * * @author (주)famz communication (www.famz.co.kr) * @number 02-784-0972 * @version 1.0 * KTH메일 서버를 통하여 메일을 전송 */ public class MailAdaptor { static Log log = LogFactory.getLog(MailAdaptor.class); public static int sendMail( String from, String to, String subject, String content) throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Mozilla/4.0"); // String sUrl = "http://mail.als.kthcorp.com:8082/1/email/outbound/request"; String sUrl = "https://mailapi.dev.kthcorp.com:8443/1/email/outbound/request"; PostMethod method = new PostMethod(sUrl); method.addParameter("from", from); method.addParameter("to", to); method.addParameter("Subject", subject); method.addParameter("Contents", content); method.setRequestHeader("Authorization", "Basic YXBpZ2lzOjU4NzJmOWQ2LTI1MjgtNDU0OC1iMGY0LTM1Nzc5OTRkYTQ1MQ=="); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); StringBuffer sb = new StringBuffer(); BufferedReader br = null; int rCode = 0; try { rCode = client.executeMethod(method); if (rCode == HttpStatus.SC_NOT_IMPLEMENTED) { method.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String line; while ((line = br.readLine()) != null){ sb.append(line); } } method.releaseConnection(); br.close(); } catch (Exception e) { e.printStackTrace(); System.out.println(rCode + "::" + e.toString()); } if (rCode == 200 || rCode == 201) { log.info("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); }else{//200외의 결과값 log.info("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); } return rCode; } public static void main(String[] args){ // try { // sendMail("awatcher35@naver.com","galmang2015@gmail.com","테스트","테스트 내용",null); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } String content = SendZCTask.makeContent("이방원");//makeContent("이방원"); try { MailAdaptor.sendMail("awatcher35@naver.com","galmang2015@gmail.com","한국의 신앙인들에게"+new Date(),content,null); } catch (IOException e) { e.printStackTrace(); } } //메일에 파일 전송 추가 public static int sendMail( String from, String to, String subject, String content, MultipartFile file) throws IOException { int rCode = 0; String host = "smtp.naver.com"; String port = "465"; Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.trust", host); final String username = "awatcher35"; //네이버 아이디를 입력해주세요. @nave.com은 입력하지 마시구요. final String password = "yustian2006"; //네이버 이메일 비밀번호를 입력해주세요. Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { String un=username; String pw=password; protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(un, pw); } }); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(content, "text/html;charset=UTF-8"); multipart.addBodyPart(bodyPart); message.setContent(multipart); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); if (file != null && file.getSize() > 0) { MimeBodyPart bodyPartFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(convertFile(file)); bodyPartFile.setDataHandler(new DataHandler(fds)); bodyPartFile.setFileName(MimeUtility.encodeText(fds.getName(), "KSC5601", "B")); multipart.addBodyPart(bodyPartFile); } Transport.send(message); rCode = 200; } catch (AddressException e) { e.printStackTrace(); rCode = 300; } catch (MessagingException e) { e.printStackTrace(); rCode = 300; } if (rCode == 200 || rCode == 201) { log.debug("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); System.out.println("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); }else{//200외의 결과값 log.debug("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); System.out.println("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); } return rCode; } public static File convertFile(MultipartFile file) { File convFile = new File(file.getOriginalFilename()); try { file.transferTo(convFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return convFile; } }
UTF-8
Java
6,540
java
MailAdaptor.java
Java
[ { "context": "Project Name : KTH API Store\n * Developer : JongSeong Park\n * Create Date : 2012. 10. 29.\n * 2012. 10. 29", "end": 1081, "score": 0.9998162984848022, "start": 1067, "tag": "NAME", "value": "JongSeong Park" }, { "context": "etRequestHeader(\"Authorization\",...
null
[]
package com.escape.common; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.multipart.MultipartFile; import com.escape.batch.SendZCTask; /** * Project Name : KTH API Store * Developer : <NAME> * Create Date : 2012. 10. 29. * 2012. 10. 29./Famz : created * * @author (주)famz communication (www.famz.co.kr) * @number 02-784-0972 * @version 1.0 * KTH메일 서버를 통하여 메일을 전송 */ public class MailAdaptor { static Log log = LogFactory.getLog(MailAdaptor.class); public static int sendMail( String from, String to, String subject, String content) throws IOException { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Mozilla/4.0"); // String sUrl = "http://mail.als.kthcorp.com:8082/1/email/outbound/request"; String sUrl = "https://mailapi.dev.kthcorp.com:8443/1/email/outbound/request"; PostMethod method = new PostMethod(sUrl); method.addParameter("from", from); method.addParameter("to", to); method.addParameter("Subject", subject); method.addParameter("Contents", content); method.setRequestHeader("Authorization", "Basic YXBpZ2lzOjU4NzJmOWQ2LTI1MjgtNDU0OC1iMGY0LTM1Nzc5OTRkYTQ1MQ=="); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); StringBuffer sb = new StringBuffer(); BufferedReader br = null; int rCode = 0; try { rCode = client.executeMethod(method); if (rCode == HttpStatus.SC_NOT_IMPLEMENTED) { method.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String line; while ((line = br.readLine()) != null){ sb.append(line); } } method.releaseConnection(); br.close(); } catch (Exception e) { e.printStackTrace(); System.out.println(rCode + "::" + e.toString()); } if (rCode == 200 || rCode == 201) { log.info("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); }else{//200외의 결과값 log.info("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); } return rCode; } public static void main(String[] args){ // try { // sendMail("<EMAIL>","<EMAIL>","테스트","테스트 내용",null); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } String content = SendZCTask.makeContent("이방원");//makeContent("이방원"); try { MailAdaptor.sendMail("<EMAIL>","<EMAIL>","한국의 신앙인들에게"+new Date(),content,null); } catch (IOException e) { e.printStackTrace(); } } //메일에 파일 전송 추가 public static int sendMail( String from, String to, String subject, String content, MultipartFile file) throws IOException { int rCode = 0; String host = "smtp.naver.com"; String port = "465"; Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.trust", host); final String username = "awatcher35"; //네이버 아이디를 입력해주세요. <EMAIL>은 입력하지 마시구요. final String password = "<PASSWORD>"; //네이버 이메일 비밀번호를 입력해주세요. Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { String un=username; String pw=password; protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(un, pw); } }); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.setSubject(subject); Multipart multipart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(content, "text/html;charset=UTF-8"); multipart.addBodyPart(bodyPart); message.setContent(multipart); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); if (file != null && file.getSize() > 0) { MimeBodyPart bodyPartFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(convertFile(file)); bodyPartFile.setDataHandler(new DataHandler(fds)); bodyPartFile.setFileName(MimeUtility.encodeText(fds.getName(), "KSC5601", "B")); multipart.addBodyPart(bodyPartFile); } Transport.send(message); rCode = 200; } catch (AddressException e) { e.printStackTrace(); rCode = 300; } catch (MessagingException e) { e.printStackTrace(); rCode = 300; } if (rCode == 200 || rCode == 201) { log.debug("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); System.out.println("[from : " + from + ", to : " + to + "] 메일 발송이 완료되었습니다."); }else{//200외의 결과값 log.debug("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); System.out.println("[from : " + from + ", to : " + to + "] 메일 발송이 실패되었습니다."); } return rCode; } public static File convertFile(MultipartFile file) { File convFile = new File(file.getOriginalFilename()); try { file.transferTo(convFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return convFile; } }
6,475
0.670802
0.653722
190
31.663158
25.858364
113
false
false
0
0
0
0
0
0
2.21579
false
false
9
b928efd5bf57cd1964d6af558f93c43c8fab5950
26,061,861,579,276
ea9667c045c4f6433e9392feff29e53e93f6a2e8
/src/GUI_Table/mkiTable.java
7bcae014585bb70c5b5db0d6eb933c5dd835c54f
[]
no_license
Schnillz/CI
https://github.com/Schnillz/CI
8d9bc2d44e3704b7560ad1b92dca6ded114ee062
7dbc9c3bd8d646dbdc835d88a0d8e6dc7b74c92a
refs/heads/master
2021-01-11T10:54:22.326000
2016-12-11T18:45:56
2016-12-11T18:45:56
76,183,544
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GUI_Table; import java.awt.Color; import java.awt.Component; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import Controller.Controller; import GUI.GUI; import mKIebay_team.Auktion; import mKIebay_team.Benutzer; import mKIebay_team.MKIebay; import mKIebay_team.Status; public class mkiTable extends JTable { private static final long serialVersionUID = 1L; private Status[] rowStatus; private final int letzteSpalte = 6; private int sizeAuktionen; private TableCellRenderer defaultRenderer; private mkiTableButtonCE buttonCE; private mkiTableTextfieldCE textfieldCE; private ArrayList<mkiTableButtonCE> buttonCEList; private ArrayList<mkiTableTextfieldCE> textfieldCEList; private Controller controller; private boolean eigene = false; private MKIebay ebay; private Benutzer benutzer; private mkiTableModel tableModel; public mkiTable(ArrayList<Auktion> auktionen, Benutzer benutzer, Controller controller, MKIebay ebay, boolean eigene) { super(new mkiTableModel(auktionen, benutzer, ebay, eigene)); this.setController(controller); this.setBenutzer(benutzer); this.setEbay(ebay); this.eigene = eigene; this.setTableModel(); prepareComponents(auktionen, benutzer, this.eigene); } public void setController(Controller controller2) { this.controller = controller2; } private void setBenutzer(Benutzer benutzer) { if (benutzer != null) this.benutzer = benutzer; else GUI.meldung("GUI Fehler", 2); } public Benutzer getBenutzer(){ return benutzer; } private void setEbay(MKIebay ebay){ if(ebay != null) this.ebay = ebay; else GUI.meldung("GUI Fehler", 2); } public MKIebay getEbay(){ return ebay; } private void setTableModel(){ if (this.getModel() != null) this.tableModel = (mkiTableModel) this.getModel(); else GUI.meldung("GUI Fehler", 2); } public mkiTableModel getTableModel(){ return tableModel; } public int getLetzteSpalte() { return letzteSpalte; } public Status[] getRowStatus() { return rowStatus; } public ArrayList<mkiTableButtonCE> getButtonCEList() { return buttonCEList; } public ArrayList<mkiTableTextfieldCE> getTextfieldCEList() { return textfieldCEList; } // Nur Zellen in vorletzter Spalte sind beschreibbar falls Status=aktiv @Override public boolean isCellEditable(int row, int column) { boolean editable = false; if ((column == letzteSpalte - 1) && rowStatus[row].equals(Status.aktiv) && ebay.getAuktion(tableModel.getAuktionsID(row)).getAnbieter() == benutzer) editable = true; return editable; } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); JComponent jc = (JComponent) c; // Tabelle stylen if (!isRowSelected(row)) jc.setBackground(Color.decode("#cccccc")); // Spalte gelb einfŐrben falls Benutzer geboten if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.aktiv) && ebay.getAuktion(tableModel.getAuktionsID(row)).hatGeboten(benutzer)){ jc.setBackground(Color.decode("#E8E574")); } // Spalte grčn einfŐrben falls Status = aktiv else if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.aktiv)) { jc.setBackground(Color.decode("#9CD397")); } // Spalte rot einfŐrben falls Status = beendet else if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.beendet)) { jc.setBackground(Color.decode("#e2a8a8")); } return c; } @Override public TableCellEditor getCellEditor(int zeile, int spalte) { if (letzteSpalte - 1 == convertColumnIndexToModel(spalte) && rowStatus[zeile].equals(Status.aktiv)) { return buttonCEList.get(zeile); } else { return super.getCellEditor(zeile, spalte); } } // Holt sich den Status aus der ArrayList und speichert diese extra ab private void getStatus(ArrayList<Auktion> auktionen) { rowStatus = new Status[auktionen.size()]; int zaehler = 0; for (Auktion a : auktionen) { rowStatus[zaehler] = a.getStatus(); zaehler++; } } // Hilfsmethode zur Vorbereitung der Komponenten der Tabelle aller Auktionen private void prepareComponents(ArrayList<Auktion> auktionen,Benutzer benutzer, boolean eigene) { this.getStatus(auktionen); this.setRowHeight(20); this.getTableHeader().setReorderingAllowed(false); this.sizeAuktionen = auktionen.size(); defaultRenderer = this.getDefaultRenderer(JButton.class); this.setDefaultRenderer(JButton.class, new mkiTableCellRenderer(defaultRenderer)); buttonCEList = new ArrayList<mkiTableButtonCE>(); textfieldCEList = new ArrayList<mkiTableTextfieldCE>(); for (int i = 0; i < sizeAuktionen; i++) { if (eigene == false) { JButton jb = new JButton("Bieten"); jb.addActionListener(controller.new TableActionListenerBieten( i, this)); buttonCE = new mkiTableButtonCE(jb); buttonCEList.add(buttonCE); textfieldCE = new mkiTableTextfieldCE(); textfieldCEList.add(textfieldCE); } if (eigene == true) { JButton jb = new JButton("Abbrechen"); jb.addActionListener(controller.new TableActionListenerAbbrechen( i, this)); buttonCE = new mkiTableButtonCE(jb); buttonCEList.add(buttonCE); } } } }
IBM852
Java
5,510
java
mkiTable.java
Java
[]
null
[]
package GUI_Table; import java.awt.Color; import java.awt.Component; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import Controller.Controller; import GUI.GUI; import mKIebay_team.Auktion; import mKIebay_team.Benutzer; import mKIebay_team.MKIebay; import mKIebay_team.Status; public class mkiTable extends JTable { private static final long serialVersionUID = 1L; private Status[] rowStatus; private final int letzteSpalte = 6; private int sizeAuktionen; private TableCellRenderer defaultRenderer; private mkiTableButtonCE buttonCE; private mkiTableTextfieldCE textfieldCE; private ArrayList<mkiTableButtonCE> buttonCEList; private ArrayList<mkiTableTextfieldCE> textfieldCEList; private Controller controller; private boolean eigene = false; private MKIebay ebay; private Benutzer benutzer; private mkiTableModel tableModel; public mkiTable(ArrayList<Auktion> auktionen, Benutzer benutzer, Controller controller, MKIebay ebay, boolean eigene) { super(new mkiTableModel(auktionen, benutzer, ebay, eigene)); this.setController(controller); this.setBenutzer(benutzer); this.setEbay(ebay); this.eigene = eigene; this.setTableModel(); prepareComponents(auktionen, benutzer, this.eigene); } public void setController(Controller controller2) { this.controller = controller2; } private void setBenutzer(Benutzer benutzer) { if (benutzer != null) this.benutzer = benutzer; else GUI.meldung("GUI Fehler", 2); } public Benutzer getBenutzer(){ return benutzer; } private void setEbay(MKIebay ebay){ if(ebay != null) this.ebay = ebay; else GUI.meldung("GUI Fehler", 2); } public MKIebay getEbay(){ return ebay; } private void setTableModel(){ if (this.getModel() != null) this.tableModel = (mkiTableModel) this.getModel(); else GUI.meldung("GUI Fehler", 2); } public mkiTableModel getTableModel(){ return tableModel; } public int getLetzteSpalte() { return letzteSpalte; } public Status[] getRowStatus() { return rowStatus; } public ArrayList<mkiTableButtonCE> getButtonCEList() { return buttonCEList; } public ArrayList<mkiTableTextfieldCE> getTextfieldCEList() { return textfieldCEList; } // Nur Zellen in vorletzter Spalte sind beschreibbar falls Status=aktiv @Override public boolean isCellEditable(int row, int column) { boolean editable = false; if ((column == letzteSpalte - 1) && rowStatus[row].equals(Status.aktiv) && ebay.getAuktion(tableModel.getAuktionsID(row)).getAnbieter() == benutzer) editable = true; return editable; } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); JComponent jc = (JComponent) c; // Tabelle stylen if (!isRowSelected(row)) jc.setBackground(Color.decode("#cccccc")); // Spalte gelb einfŐrben falls Benutzer geboten if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.aktiv) && ebay.getAuktion(tableModel.getAuktionsID(row)).hatGeboten(benutzer)){ jc.setBackground(Color.decode("#E8E574")); } // Spalte grčn einfŐrben falls Status = aktiv else if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.aktiv)) { jc.setBackground(Color.decode("#9CD397")); } // Spalte rot einfŐrben falls Status = beendet else if (column < letzteSpalte - 1 && !isRowSelected(row) && rowStatus != null && rowStatus[row].equals(Status.beendet)) { jc.setBackground(Color.decode("#e2a8a8")); } return c; } @Override public TableCellEditor getCellEditor(int zeile, int spalte) { if (letzteSpalte - 1 == convertColumnIndexToModel(spalte) && rowStatus[zeile].equals(Status.aktiv)) { return buttonCEList.get(zeile); } else { return super.getCellEditor(zeile, spalte); } } // Holt sich den Status aus der ArrayList und speichert diese extra ab private void getStatus(ArrayList<Auktion> auktionen) { rowStatus = new Status[auktionen.size()]; int zaehler = 0; for (Auktion a : auktionen) { rowStatus[zaehler] = a.getStatus(); zaehler++; } } // Hilfsmethode zur Vorbereitung der Komponenten der Tabelle aller Auktionen private void prepareComponents(ArrayList<Auktion> auktionen,Benutzer benutzer, boolean eigene) { this.getStatus(auktionen); this.setRowHeight(20); this.getTableHeader().setReorderingAllowed(false); this.sizeAuktionen = auktionen.size(); defaultRenderer = this.getDefaultRenderer(JButton.class); this.setDefaultRenderer(JButton.class, new mkiTableCellRenderer(defaultRenderer)); buttonCEList = new ArrayList<mkiTableButtonCE>(); textfieldCEList = new ArrayList<mkiTableTextfieldCE>(); for (int i = 0; i < sizeAuktionen; i++) { if (eigene == false) { JButton jb = new JButton("Bieten"); jb.addActionListener(controller.new TableActionListenerBieten( i, this)); buttonCE = new mkiTableButtonCE(jb); buttonCEList.add(buttonCE); textfieldCE = new mkiTableTextfieldCE(); textfieldCEList.add(textfieldCE); } if (eigene == true) { JButton jb = new JButton("Abbrechen"); jb.addActionListener(controller.new TableActionListenerAbbrechen( i, this)); buttonCE = new mkiTableButtonCE(jb); buttonCEList.add(buttonCE); } } } }
5,510
0.734835
0.729931
192
27.677084
27.496778
150
false
false
0
0
0
0
0
0
2.026042
false
false
9
4c969d357cc1b3017962eec86383b4c2afe19fc4
14,499,809,616,429
ec9bf57a07b7b06134ec7a21407a11f69cc644f7
/src/bit.java
37420542d16a85a063f5a25ee3b61904d58c3252
[]
no_license
jzarca01/com.ubercab
https://github.com/jzarca01/com.ubercab
f95c12cab7a28f05e8f1d1a9d8a12a5ac7fbf4b1
e6b454fb0ad547287ae4e71e59d6b9482369647a
refs/heads/master
2020-06-21T04:37:43.723000
2016-07-19T16:30:34
2016-07-19T16:30:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.InvalidObjectException; import java.io.ObjectInputStream; abstract class bit<E> extends bjb<E> { private void readObject(ObjectInputStream paramObjectInputStream) { throw new InvalidObjectException("Use SerializedForm"); } abstract biy<E> a(); public boolean contains(Object paramObject) { return a().contains(paramObject); } public boolean isEmpty() { return a().isEmpty(); } public int size() { return a().size(); } Object writeReplace() { return new biu(a()); } } /* Location: * Qualified Name: bit * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
657
java
bit.java
Java
[]
null
[]
import java.io.InvalidObjectException; import java.io.ObjectInputStream; abstract class bit<E> extends bjb<E> { private void readObject(ObjectInputStream paramObjectInputStream) { throw new InvalidObjectException("Use SerializedForm"); } abstract biy<E> a(); public boolean contains(Object paramObject) { return a().contains(paramObject); } public boolean isEmpty() { return a().isEmpty(); } public int size() { return a().size(); } Object writeReplace() { return new biu(a()); } } /* Location: * Qualified Name: bit * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
657
0.645358
0.634703
39
15.871795
16.939075
67
false
false
0
0
0
0
0
0
0.205128
false
false
9
4e2d5098c0b90bc925bd23fcffdd4b72eec6875f
32,358,283,633,193
5df6ac6e738555a28c31199a195c6aaab7b3b720
/h03/src/VerplaatsbareBal/VerplaatsbarebalPaneel.java
0bb81e2e5efe6efd43b0ebdd97d83b1cdca80ac8
[]
no_license
jmartis/DeBasis
https://github.com/jmartis/DeBasis
19545ea9dcc923b4bab8bb9d3fec3142a10618c6
1e6fd868dbc72e38c22a705c832cab71b1905de8
refs/heads/master
2016-08-05T12:19:47.401000
2015-09-06T14:47:54
2015-09-06T14:47:54
13,930,475
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package VerplaatsbareBal; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; public class VerplaatsbarebalPaneel extends JPanel implements ActionListener { private JButton naarLinks; private JButton naarRechts; int horizontalePlaats = 150; int VERTICALE_PLAATS = 120; int BALDIAMETER = 150; public VerplaatsbarebalPaneel() { naarLinks = new JButton("Links"); naarLinks.addActionListener(this); naarRechts = new JButton("Rechts"); naarRechts.addActionListener(this); this.add(naarLinks); this.add(naarRechts); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.ORANGE); g.fillOval(horizontalePlaats, VERTICALE_PLAATS, BALDIAMETER, BALDIAMETER); g.setColor(Color.BLACK); g.drawOval(horizontalePlaats, VERTICALE_PLAATS, BALDIAMETER, BALDIAMETER); g.drawOval(horizontalePlaats + BALDIAMETER / 4, VERTICALE_PLAATS, BALDIAMETER / 2, BALDIAMETER); } public void actionPerformed(ActionEvent e) { int VERPLAATSING = 10; if (e.getSource() == naarLinks) { horizontalePlaats = horizontalePlaats - VERPLAATSING; } else { horizontalePlaats = horizontalePlaats + VERPLAATSING; } repaint(); } }
UTF-8
Java
1,299
java
VerplaatsbarebalPaneel.java
Java
[]
null
[]
package VerplaatsbareBal; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; public class VerplaatsbarebalPaneel extends JPanel implements ActionListener { private JButton naarLinks; private JButton naarRechts; int horizontalePlaats = 150; int VERTICALE_PLAATS = 120; int BALDIAMETER = 150; public VerplaatsbarebalPaneel() { naarLinks = new JButton("Links"); naarLinks.addActionListener(this); naarRechts = new JButton("Rechts"); naarRechts.addActionListener(this); this.add(naarLinks); this.add(naarRechts); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.ORANGE); g.fillOval(horizontalePlaats, VERTICALE_PLAATS, BALDIAMETER, BALDIAMETER); g.setColor(Color.BLACK); g.drawOval(horizontalePlaats, VERTICALE_PLAATS, BALDIAMETER, BALDIAMETER); g.drawOval(horizontalePlaats + BALDIAMETER / 4, VERTICALE_PLAATS, BALDIAMETER / 2, BALDIAMETER); } public void actionPerformed(ActionEvent e) { int VERPLAATSING = 10; if (e.getSource() == naarLinks) { horizontalePlaats = horizontalePlaats - VERPLAATSING; } else { horizontalePlaats = horizontalePlaats + VERPLAATSING; } repaint(); } }
1,299
0.762125
0.752117
46
27.23913
22.9841
98
false
false
0
0
0
0
0
0
1.913043
false
false
9
6e06708cda2e359b679f9042b1c79fed5f4af328
5,153,960,790,032
3b8e60c5f79d794bab1fb91eb53e3002d6115bc6
/Chat/src/com/example/chat/MainActivity.java
48540060657dab44de7a99d4fe4626de4532da08
[]
no_license
moderateepheezy/Workspace3
https://github.com/moderateepheezy/Workspace3
46e770b9fc05da83dcf171bb365084471793e518
69823d343bf2013a90bdfb0d00fe2d2144e23ea2
refs/heads/master
2020-06-02T10:30:01.197000
2014-11-08T17:07:10
2014-11-08T17:07:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.telephony.TelephonyManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { static Context context; final static String localHost="10.0.2.2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public String send_ClientMessage; public int emulator_instance; private SimpleDateFormat df; ArrayList<String> as; ArrayAdapter<String> a; public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); ListView ls = (ListView)rootView.findViewById(R.id.listView); TelephonyManager tel = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() -4); emulator_instance = Integer.parseInt(portStr); as = new ArrayList<String>(); a = new ArrayAdapter<>(getActivity(), R.layout.testlistview, as); ls.setAdapter(a); createServer(); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); return rootView; } private void createServer() { new Thread(new Runnable() { @Override public void run() { try{ ServerSocket s = new ServerSocket(10000); while(true){ Socket ss = s.accept(); String msg_ServerSide = null; BufferedReader br = new BufferedReader(new InputStreamReader(ss.getInputStream())); while((msg_ServerSide = br.readLine())!=null){ System.out.println(); if(!msg_ServerSide.isEmpty()){ new displayMessage().execute(msg_ServerSide); } } br.close(); ss.close(); } } catch(IOException e){ e.printStackTrace(); } } }).start(); } class displayMessage extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub return params[0]; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); String time = df.format(Calendar.getInstance().getTime()); String time_now = time.substring(11, 16); a.add(result + "\t" + "\t" + time_now); Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show(); } } public void sendMessage(View v){ EditText ed = (EditText)v.findViewById(R.id.btn_Send); send_ClientMessage = ed.getText().toString(); sendServer(); ed.setText(null); } private void sendServer(){ new Thread(new Runnable() { public void run() { Socket s=null; try { if(emulator_instance == 5554) { s=new Socket(localHost,11112); } else if(emulator_instance == 5556) { s=new Socket(localHost,11108); } sendandUpdate(s); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } private void sendandUpdate(Socket s) throws IOException { PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println(send_ClientMessage); pw.close(); s.close(); } } }
UTF-8
Java
5,072
java
MainActivity.java
Java
[ { "context": " Context context;\n\tfinal static String localHost=\"10.0.2.2\";\n\n\t@Override\n\tprotected void onCreate(Bundle sav", "end": 975, "score": 0.9997377395629883, "start": 967, "tag": "IP_ADDRESS", "value": "10.0.2.2" } ]
null
[]
package com.example.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.telephony.TelephonyManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { static Context context; final static String localHost="10.0.2.2"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public String send_ClientMessage; public int emulator_instance; private SimpleDateFormat df; ArrayList<String> as; ArrayAdapter<String> a; public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); ListView ls = (ListView)rootView.findViewById(R.id.listView); TelephonyManager tel = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() -4); emulator_instance = Integer.parseInt(portStr); as = new ArrayList<String>(); a = new ArrayAdapter<>(getActivity(), R.layout.testlistview, as); ls.setAdapter(a); createServer(); df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); return rootView; } private void createServer() { new Thread(new Runnable() { @Override public void run() { try{ ServerSocket s = new ServerSocket(10000); while(true){ Socket ss = s.accept(); String msg_ServerSide = null; BufferedReader br = new BufferedReader(new InputStreamReader(ss.getInputStream())); while((msg_ServerSide = br.readLine())!=null){ System.out.println(); if(!msg_ServerSide.isEmpty()){ new displayMessage().execute(msg_ServerSide); } } br.close(); ss.close(); } } catch(IOException e){ e.printStackTrace(); } } }).start(); } class displayMessage extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub return params[0]; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); String time = df.format(Calendar.getInstance().getTime()); String time_now = time.substring(11, 16); a.add(result + "\t" + "\t" + time_now); Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show(); } } public void sendMessage(View v){ EditText ed = (EditText)v.findViewById(R.id.btn_Send); send_ClientMessage = ed.getText().toString(); sendServer(); ed.setText(null); } private void sendServer(){ new Thread(new Runnable() { public void run() { Socket s=null; try { if(emulator_instance == 5554) { s=new Socket(localHost,11112); } else if(emulator_instance == 5556) { s=new Socket(localHost,11108); } sendandUpdate(s); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } private void sendandUpdate(Socket s) throws IOException { PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println(send_ClientMessage); pw.close(); s.close(); } } }
5,072
0.690852
0.68336
185
26.416216
21.134697
96
false
false
0
0
0
0
0
0
3.297297
false
false
9
ba39c935c9210a96ec1aa1cbfa5b4271d3981a02
15,496,242,035,636
dd461a1d0aa9077bc06f0b4db0af3ed1aa1807cc
/dubbo-samples-triple/src/main/java/org/apache/dubbo/sample/tri/util/GrpcStreamObserverAdapter.java
9cd5e17271f6a520e394f47dbd22b0fd3d5f04ad
[ "Apache-2.0" ]
permissive
tzjavadmg/dubbo-samples
https://github.com/tzjavadmg/dubbo-samples
d4b6f242448c41b38364215861f7d56333ee79b3
09dc583a9c3a7a267b3155448438e41e790b6356
refs/heads/master
2022-11-04T06:57:56.076000
2022-10-19T09:29:24
2022-10-19T09:29:24
193,428,593
0
0
Apache-2.0
true
2019-06-24T03:37:11
2019-06-24T03:37:10
2019-06-24T03:37:02
2019-06-24T03:14:18
1,766
0
0
0
null
false
false
package org.apache.dubbo.sample.tri.util; import io.grpc.stub.StreamObserver; public class GrpcStreamObserverAdapter<T> implements StreamObserver<T> { private final org.apache.dubbo.common.stream.StreamObserver<T> delegate; public GrpcStreamObserverAdapter(org.apache.dubbo.common.stream.StreamObserver<T> delegate) { this.delegate = delegate; } @Override public void onNext(T data) { delegate.onNext(data); } @Override public void onError(Throwable throwable) { delegate.onError(throwable); } @Override public void onCompleted() { delegate.onCompleted(); } }
UTF-8
Java
648
java
GrpcStreamObserverAdapter.java
Java
[]
null
[]
package org.apache.dubbo.sample.tri.util; import io.grpc.stub.StreamObserver; public class GrpcStreamObserverAdapter<T> implements StreamObserver<T> { private final org.apache.dubbo.common.stream.StreamObserver<T> delegate; public GrpcStreamObserverAdapter(org.apache.dubbo.common.stream.StreamObserver<T> delegate) { this.delegate = delegate; } @Override public void onNext(T data) { delegate.onNext(data); } @Override public void onError(Throwable throwable) { delegate.onError(throwable); } @Override public void onCompleted() { delegate.onCompleted(); } }
648
0.692901
0.692901
28
22.142857
25.705355
97
false
false
0
0
0
0
0
0
0.25
false
false
9
cc69afc5bfbf20acf8c0e3fdd400f5ce4bfc6e49
29,944,512,024,227
9dc0c6286a40f13b4e9269a5b5ed5e3bf18ab8b0
/MiBand4Editor/src/display/TopalignedLabel.java
5a63fc712587f367c5b7ba997e2e52b83583b63d
[]
no_license
MonsterDruide1/MiBand4-WatchfaceEditor
https://github.com/MonsterDruide1/MiBand4-WatchfaceEditor
9ae1eb61de924a45a224e02f297190686dcefec1
33da4ea1109b758b3ea74fb46c6c5d0a6a24a772
refs/heads/master
2020-07-09T13:19:21.054000
2019-08-30T17:19:28
2019-08-30T17:19:28
203,978,431
23
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package display; import java.awt.Component; import javax.swing.JLabel; public class TopalignedLabel extends JLabel { private static final long serialVersionUID = 1L; public TopalignedLabel(JLabel image) { super(image.getIcon()); } @Override public Component.BaselineResizeBehavior getBaselineResizeBehavior() { return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } @Override public int getBaseline(int width, int height) { return 0; } }
UTF-8
Java
469
java
TopalignedLabel.java
Java
[]
null
[]
package display; import java.awt.Component; import javax.swing.JLabel; public class TopalignedLabel extends JLabel { private static final long serialVersionUID = 1L; public TopalignedLabel(JLabel image) { super(image.getIcon()); } @Override public Component.BaselineResizeBehavior getBaselineResizeBehavior() { return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } @Override public int getBaseline(int width, int height) { return 0; } }
469
0.765458
0.761194
24
18.541666
21.592783
70
false
false
0
0
0
0
0
0
1
false
false
9
81de4d6084b48bc968a2a8e50f96ff3cb611b46a
29,944,512,022,880
15a5f28c8541d02d67c7580d372220abd390456f
/chartview/src/main/java/com/vachel/chartview/SelectPopup.java
451707ff2fbe50aeffb5d3a5e4cffbb088a0b696
[]
no_license
Purple666/StockChart-1
https://github.com/Purple666/StockChart-1
8e07cfd0150cdb49a5a98ca5f6eccbfab6066c02
c776e577622465100654bcc9f0404c31b1e87487
refs/heads/master
2023-06-05T07:33:59.185000
2020-05-12T01:46:59
2020-05-12T01:46:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vachel.chartview; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.vachel.chartview.util.Constant; import com.vachel.chartview.util.ResourceUtils; import com.vachel.chartview.util.Utils; import java.util.ArrayList; /** * 指标类型选择弹窗 */ public class SelectPopup extends PopupWindow implements View.OnClickListener { private ChartPopupListener mChartPopupListener; private ArrayList<TextView> mViews = new ArrayList<>(); private String[] mArguments; private LinearLayout mRootView; private double mMeasureHeight = 0; private View mAnchor; private int mXoff; private int mYoff; public SelectPopup(Context context) { super(context); } public SelectPopup(Context context, String[] arguments) { this(context); init(context, arguments); } private void init(Context context, String[] arguments) { mArguments = arguments; Resources resources = context.getResources(); int offsetX = resources.getDimensionPixelSize(R.dimen.popup_select_horizontal); int offsetY = resources.getDimensionPixelSize(R.dimen.popup_select_vertical); mRootView = new LinearLayout(context); mRootView.setVisibility(View.INVISIBLE); mRootView.setGravity(Gravity.CENTER); mRootView.setOrientation(LinearLayout.VERTICAL); boolean isBlackTheme = ResourceUtils.getTheme().equals(Constant.THEME_BLACK); mRootView.setBackground(resources.getDrawable(isBlackTheme ? R.drawable.black_popup_bg : R.drawable.white_popup_bg)); mRootView.setPadding(0, offsetY, 0, offsetY); ColorStateList colorStateList = resources.getColorStateList(isBlackTheme ? R.color.black_pul_popup_text_color : R.color.white_pul_popup_text_color); for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; TextView textView = new TextView(context); textView.setText(arg); textView.setPadding(offsetX, offsetY, offsetX ,offsetY); textView.setTextSize(Constant.POPUP_TEXT_SIZE); textView.setGravity(Gravity.CENTER); textView.setTextColor(colorStateList); textView.setTag(arg); mRootView.addView(textView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mViews.add(textView); textView.setOnClickListener(this); } setClippingEnabled(false); setContentView(mRootView); setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); setBackgroundDrawable(new ColorDrawable()); setTouchable(true); setOutsideTouchable(true); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { if (mChartPopupListener != null) { mChartPopupListener.onDismiss(); } } }); mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); // popupWindow 可能会超出屏幕, 先不显示rooView, 待测出popupWindow的高度后,重新show。 if (mMeasureHeight == 0) { mMeasureHeight = mRootView.getMeasuredHeight(); dismiss(); showAsDropDown(mAnchor, mXoff, mYoff); } } }); } private int getTypeByViewTag(Object tag) { for (int i = 0; i < mArguments.length; i++) { if (tag.equals(mArguments[i])) { return i; } } return 0; } private TextView getViewByType(int type) { return mViews.get(type); } public void setChartPopupListener(ChartPopupListener listener) { mChartPopupListener = listener; } /** * * @param type * @param isM1 表示当前为分时线 不需要某些指标 */ public void setSelectItem(int type, boolean isM1) { TextView targetView = getViewByType(type); for (TextView view: mViews) { boolean equals = targetView.equals(view); view.setSelected(equals); view.setClickable(!isM1 || equals); } } @Override public void onClick(View v) { if (mChartPopupListener != null) { int type = getTypeByViewTag(v.getTag()); mChartPopupListener.onItemClick(type); } dismiss(); } public interface ChartPopupListener { void onItemClick(int type); void onDismiss(); } @Override public void showAsDropDown(View anchor, int xoff, int yoff) { if (mMeasureHeight != 0) { // 根据popup高度调整应该显示的位置 int[] outs = new int[2]; anchor.getLocationOnScreen(outs); int height = anchor.getHeight(); int screenHeight = Utils.getScreenHeight(mRootView.getContext()); if (outs[1] + height + mMeasureHeight> screenHeight) { yoff = (int) (screenHeight - mMeasureHeight - outs[1] - height); } if (mRootView.getVisibility() == View.INVISIBLE) { mRootView.setVisibility(View.VISIBLE); } } else { mAnchor = anchor; mXoff = xoff; mYoff = yoff; } super.showAsDropDown(anchor, xoff, yoff); anchor.setSelected(true); } }
UTF-8
Java
6,071
java
SelectPopup.java
Java
[]
null
[]
package com.vachel.chartview; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.vachel.chartview.util.Constant; import com.vachel.chartview.util.ResourceUtils; import com.vachel.chartview.util.Utils; import java.util.ArrayList; /** * 指标类型选择弹窗 */ public class SelectPopup extends PopupWindow implements View.OnClickListener { private ChartPopupListener mChartPopupListener; private ArrayList<TextView> mViews = new ArrayList<>(); private String[] mArguments; private LinearLayout mRootView; private double mMeasureHeight = 0; private View mAnchor; private int mXoff; private int mYoff; public SelectPopup(Context context) { super(context); } public SelectPopup(Context context, String[] arguments) { this(context); init(context, arguments); } private void init(Context context, String[] arguments) { mArguments = arguments; Resources resources = context.getResources(); int offsetX = resources.getDimensionPixelSize(R.dimen.popup_select_horizontal); int offsetY = resources.getDimensionPixelSize(R.dimen.popup_select_vertical); mRootView = new LinearLayout(context); mRootView.setVisibility(View.INVISIBLE); mRootView.setGravity(Gravity.CENTER); mRootView.setOrientation(LinearLayout.VERTICAL); boolean isBlackTheme = ResourceUtils.getTheme().equals(Constant.THEME_BLACK); mRootView.setBackground(resources.getDrawable(isBlackTheme ? R.drawable.black_popup_bg : R.drawable.white_popup_bg)); mRootView.setPadding(0, offsetY, 0, offsetY); ColorStateList colorStateList = resources.getColorStateList(isBlackTheme ? R.color.black_pul_popup_text_color : R.color.white_pul_popup_text_color); for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; TextView textView = new TextView(context); textView.setText(arg); textView.setPadding(offsetX, offsetY, offsetX ,offsetY); textView.setTextSize(Constant.POPUP_TEXT_SIZE); textView.setGravity(Gravity.CENTER); textView.setTextColor(colorStateList); textView.setTag(arg); mRootView.addView(textView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mViews.add(textView); textView.setOnClickListener(this); } setClippingEnabled(false); setContentView(mRootView); setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); setBackgroundDrawable(new ColorDrawable()); setTouchable(true); setOutsideTouchable(true); setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { if (mChartPopupListener != null) { mChartPopupListener.onDismiss(); } } }); mRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); // popupWindow 可能会超出屏幕, 先不显示rooView, 待测出popupWindow的高度后,重新show。 if (mMeasureHeight == 0) { mMeasureHeight = mRootView.getMeasuredHeight(); dismiss(); showAsDropDown(mAnchor, mXoff, mYoff); } } }); } private int getTypeByViewTag(Object tag) { for (int i = 0; i < mArguments.length; i++) { if (tag.equals(mArguments[i])) { return i; } } return 0; } private TextView getViewByType(int type) { return mViews.get(type); } public void setChartPopupListener(ChartPopupListener listener) { mChartPopupListener = listener; } /** * * @param type * @param isM1 表示当前为分时线 不需要某些指标 */ public void setSelectItem(int type, boolean isM1) { TextView targetView = getViewByType(type); for (TextView view: mViews) { boolean equals = targetView.equals(view); view.setSelected(equals); view.setClickable(!isM1 || equals); } } @Override public void onClick(View v) { if (mChartPopupListener != null) { int type = getTypeByViewTag(v.getTag()); mChartPopupListener.onItemClick(type); } dismiss(); } public interface ChartPopupListener { void onItemClick(int type); void onDismiss(); } @Override public void showAsDropDown(View anchor, int xoff, int yoff) { if (mMeasureHeight != 0) { // 根据popup高度调整应该显示的位置 int[] outs = new int[2]; anchor.getLocationOnScreen(outs); int height = anchor.getHeight(); int screenHeight = Utils.getScreenHeight(mRootView.getContext()); if (outs[1] + height + mMeasureHeight> screenHeight) { yoff = (int) (screenHeight - mMeasureHeight - outs[1] - height); } if (mRootView.getVisibility() == View.INVISIBLE) { mRootView.setVisibility(View.VISIBLE); } } else { mAnchor = anchor; mXoff = xoff; mYoff = yoff; } super.showAsDropDown(anchor, xoff, yoff); anchor.setSelected(true); } }
6,071
0.632286
0.629934
171
33.812866
27.258564
156
false
false
0
0
0
0
0
0
0.660819
false
false
9
84a272251fbaa2197c82f189bcae3b042ff712e9
14,946,486,239,307
eafec203c2c3e3b99c5486f93931c13f6ac4b072
/src/blind75/string/LongestSubstringWithoutRepeatingChar.java
c0a2076a1d24419618c21e730d47cc1b9a4b8c3a
[]
no_license
adasari/algopractice
https://github.com/adasari/algopractice
ef000124b8f21a286b3f4d10d8d6f97f763ac566
bfc644da6897614d262b2b2cfcd7bc10862cfbb9
refs/heads/master
2023-04-11T15:27:12.924000
2021-04-29T14:03:36
2021-04-29T14:03:36
362,836,560
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package blind75.string; import java.util.HashSet; // 3. Longest Substring Without Repeating Characters public class LongestSubstringWithoutRepeatingChar { public static void main(String[] args) { System.out.println(new LongestSubstringWithoutRepeatingChar().lengthOfLongestSubstring("pwwkew")); } // 3. Longest Substring Without Repeating Characters public int lengthOfLongestSubstring(String s) { int i =0; int max = Integer.MIN_VALUE; HashSet<Character> set = new HashSet<Character>(); for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (!set.contains(c)) { set.add(c); max = Math.max(max, set.size()); } else { while (i < j) { if (s.charAt(i) == c) { i++; break; } set.remove(s.charAt(i)); i++; } } } return max; } }
UTF-8
Java
834
java
LongestSubstringWithoutRepeatingChar.java
Java
[]
null
[]
package blind75.string; import java.util.HashSet; // 3. Longest Substring Without Repeating Characters public class LongestSubstringWithoutRepeatingChar { public static void main(String[] args) { System.out.println(new LongestSubstringWithoutRepeatingChar().lengthOfLongestSubstring("pwwkew")); } // 3. Longest Substring Without Repeating Characters public int lengthOfLongestSubstring(String s) { int i =0; int max = Integer.MIN_VALUE; HashSet<Character> set = new HashSet<Character>(); for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (!set.contains(c)) { set.add(c); max = Math.max(max, set.size()); } else { while (i < j) { if (s.charAt(i) == c) { i++; break; } set.remove(s.charAt(i)); i++; } } } return max; } }
834
0.622302
0.615108
40
19.85
21.40625
100
false
false
0
0
0
0
0
0
2.725
false
false
15
a73a158615c1e4c49041653d9c21537939190621
10,565,619,603,505
a18ed7fd45936f9b12a9df7036c7285b075ccedc
/src/main/Pgroup.java
5268beb7e7a785cd2f6828f74fb96a9ca94fee1f
[]
no_license
sgyoun99/dbprak
https://github.com/sgyoun99/dbprak
c220739e0ac215503d1363c9cd12731657777bcc
57a9012d7bb324ef1f08c847bbe6d3967bc3c53d
refs/heads/master
2023-08-07T21:41:39.771000
2021-09-29T08:42:19
2021-09-29T08:42:19
370,748,333
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; /** * enum for product group * */ public enum Pgroup { Book, Music_CD, DVD; /** * To determine if the pgroup is correct. * @param pgroup pgroup * @return correctness */ public static boolean isValueOfPgroup(String pgroup) { for (Pgroup e : values()) { if (e.toString().equals(pgroup)) { return true; } } return false; } }
UTF-8
Java
402
java
Pgroup.java
Java
[]
null
[]
package main; /** * enum for product group * */ public enum Pgroup { Book, Music_CD, DVD; /** * To determine if the pgroup is correct. * @param pgroup pgroup * @return correctness */ public static boolean isValueOfPgroup(String pgroup) { for (Pgroup e : values()) { if (e.toString().equals(pgroup)) { return true; } } return false; } }
402
0.574627
0.574627
26
14.461538
14.972362
55
false
false
0
0
0
0
0
0
0.846154
false
false
15
d54c8168e136a5eea7a88e2eccc8806280080451
25,683,904,490,692
f9b6c819cee4154e0e5b30a7b1e84fffbd71a37e
/src/com/feyfey/method/DownloadFileUrl.java
f4cbc7d5868225b223ac528c552f62df03cd6229
[]
no_license
AugusZhu/JavaTools
https://github.com/AugusZhu/JavaTools
d64065d8bf6ee0c5ca67582078c981f8d8441ba0
0ef020c877855cfe88e8faf8fff7007f4b967e61
refs/heads/master
2021-10-21T20:35:54.610000
2019-03-06T07:27:58
2019-03-06T07:27:58
173,101,413
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.feyfey.method; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Calendar; import java.util.Date; /** * Created by wangwei on 2017/12/1. 用于通过url下载pdf到本地 */ public class DownloadFileUrl { /** * @param urlPath * 下载路径 * @param downloadDir * 下载存放目录 */ public static void downloadFile(String urlPath, String downloadDir, String fileName) { File file = null; try { // 统一资源 URL url = new URL(urlPath); // 连接类的父类,抽象类 URLConnection urlConnection = url.openConnection(); // http的连接类 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; // 设定请求的方法,默认是GET httpURLConnection.setRequestMethod("GET"); // 设置字符编码 httpURLConnection.setRequestProperty("Charset", "UTF-8"); // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 httpURLConnection.connect(); // 文件大小 int fileLength = httpURLConnection.getContentLength(); // 文件 System.out.println("file length---->" + fileLength); URLConnection con = url.openConnection(); BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream()); String path = downloadDir + File.separatorChar + fileName; file = new File(path); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file); int size = 0; int len = 0; byte[] buf = new byte[1024]; while ((size = bin.read(buf)) != -1) { len += size; out.write(buf, 0, size); // 打印下载百分比 // System.out.println("下载了-------> " + len * 100 / fileLength + // "%\n"); } bin.close(); out.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @param path * 原文件夹 * @param historyPath * 备份文件夹 * @param checkDays * 超过多少天把文件转存到备份文件夹 */ public static void transferFolderFile(String path, String historyPath, int checkDays) { try { File file = new File(path); if (file.exists()) { File[] files = file.listFiles(); if (files.length == 0) { System.out.println("文件夹是空的!"); return; } else { for (File file2 : files) { if (file2.isDirectory()) { System.out.println("文件夹:" + file2.getAbsolutePath()); transferFolderFile(file2.getAbsolutePath(), historyPath, checkDays); } else { System.out.println("文件:" + file2.getAbsolutePath()); Calendar cal = Calendar.getInstance(); long time = file2.lastModified(); cal.setTimeInMillis(time); Date currentTime = new Date(); int days = (int) ((currentTime.getTime() - cal.getTime().getTime()) / (1000 * 3600 * 24)); System.out.println("文件:" + file2.getAbsolutePath() + "距离现在" + days + "天"); if (checkDays <= days) { transferFile(path, historyPath, file2.getName()); } } } } } else { System.out.println("文件不存在!"); } } catch (Exception e) { e.printStackTrace(); } } public static void transferFile(String path, String historyPath, String fileName) { try { File afile = new File(path + "\\" + fileName); if (afile.renameTo(new File(historyPath + "\\" + fileName))) { System.out.println("File is moved successful!"); } else { System.out.println("File is failed to move!"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // 下载文件测试 downloadFile( "http://a.hiphotos.baidu.com/image/h%3D300/sign=0237380e12d5ad6eb5f962eab1ca39a3/8718367adab44aedfe5fbd2eba1c8701a08bfbe3.jpg", "F:\\test1", "test.jpg"); // 文件转移测试 transferFolderFile("F:\\test1", "F:\\test2", 20); } }
GB18030
Java
4,252
java
DownloadFileUrl.java
Java
[ { "context": "alendar;\nimport java.util.Date;\n\n/**\n * Created by wangwei on 2017/12/1. 用于通过url下载pdf到本地\n */\npublic class Do", "end": 377, "score": 0.9993410110473633, "start": 370, "tag": "USERNAME", "value": "wangwei" } ]
null
[]
package com.feyfey.method; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Calendar; import java.util.Date; /** * Created by wangwei on 2017/12/1. 用于通过url下载pdf到本地 */ public class DownloadFileUrl { /** * @param urlPath * 下载路径 * @param downloadDir * 下载存放目录 */ public static void downloadFile(String urlPath, String downloadDir, String fileName) { File file = null; try { // 统一资源 URL url = new URL(urlPath); // 连接类的父类,抽象类 URLConnection urlConnection = url.openConnection(); // http的连接类 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; // 设定请求的方法,默认是GET httpURLConnection.setRequestMethod("GET"); // 设置字符编码 httpURLConnection.setRequestProperty("Charset", "UTF-8"); // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 httpURLConnection.connect(); // 文件大小 int fileLength = httpURLConnection.getContentLength(); // 文件 System.out.println("file length---->" + fileLength); URLConnection con = url.openConnection(); BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream()); String path = downloadDir + File.separatorChar + fileName; file = new File(path); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file); int size = 0; int len = 0; byte[] buf = new byte[1024]; while ((size = bin.read(buf)) != -1) { len += size; out.write(buf, 0, size); // 打印下载百分比 // System.out.println("下载了-------> " + len * 100 / fileLength + // "%\n"); } bin.close(); out.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @param path * 原文件夹 * @param historyPath * 备份文件夹 * @param checkDays * 超过多少天把文件转存到备份文件夹 */ public static void transferFolderFile(String path, String historyPath, int checkDays) { try { File file = new File(path); if (file.exists()) { File[] files = file.listFiles(); if (files.length == 0) { System.out.println("文件夹是空的!"); return; } else { for (File file2 : files) { if (file2.isDirectory()) { System.out.println("文件夹:" + file2.getAbsolutePath()); transferFolderFile(file2.getAbsolutePath(), historyPath, checkDays); } else { System.out.println("文件:" + file2.getAbsolutePath()); Calendar cal = Calendar.getInstance(); long time = file2.lastModified(); cal.setTimeInMillis(time); Date currentTime = new Date(); int days = (int) ((currentTime.getTime() - cal.getTime().getTime()) / (1000 * 3600 * 24)); System.out.println("文件:" + file2.getAbsolutePath() + "距离现在" + days + "天"); if (checkDays <= days) { transferFile(path, historyPath, file2.getName()); } } } } } else { System.out.println("文件不存在!"); } } catch (Exception e) { e.printStackTrace(); } } public static void transferFile(String path, String historyPath, String fileName) { try { File afile = new File(path + "\\" + fileName); if (afile.renameTo(new File(historyPath + "\\" + fileName))) { System.out.println("File is moved successful!"); } else { System.out.println("File is failed to move!"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // 下载文件测试 downloadFile( "http://a.hiphotos.baidu.com/image/h%3D300/sign=0237380e12d5ad6eb5f962eab1ca39a3/8718367adab44aedfe5fbd2eba1c8701a08bfbe3.jpg", "F:\\test1", "test.jpg"); // 文件转移测试 transferFolderFile("F:\\test1", "F:\\test2", 20); } }
4,252
0.639228
0.617632
144
26.333334
23.980896
131
false
false
0
0
0
0
84
0.021341
3.034722
false
false
15
6c58469f21457a6fc6d13fd7bff3f3e681f096ca
14,456,859,977,554
7dd8998b8838c87d6252f9922d4cc9278db47a3f
/app/src/main/java/com/shark/baseproject/util/SystemUtil.java
49aa92001d25eba13bfc660d9b79369594850503
[]
no_license
Shark0/AndroidBaseProject
https://github.com/Shark0/AndroidBaseProject
bc38a766f3eb6ecfd1d6945942fdd4b0b5d8f164
1f523a938ef8e61d2fdf12a380ffe47fd7f4d335
refs/heads/master
2020-05-22T01:25:16.111000
2018-08-30T01:39:29
2018-08-30T01:39:29
65,170,229
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shark.baseproject.util; import android.app.ActivityManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Build; import android.os.PowerManager; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.shark.base.util.StringUtil; import com.shark.baseproject.manager.ApplicationManager; import java.io.IOException; import java.net.NetworkInterface; import java.util.Collections; import java.util.List; import java.util.UUID; /** * Created by adye on 2015/4/30. */ public class SystemUtil { public static boolean isAppRunning(Context context, String packageName) { ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> processInfoList = activityManager.getRunningAppProcesses(); for (int i = 0; i < processInfoList.size(); i++) { if (processInfoList.get(i).processName.equals(packageName)) { return true; } } return false; } public static boolean isAppOnForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { return false; } for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equalsIgnoreCase(context.getPackageName()) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; } public static boolean isPowerScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { isScreenOn = pm.isInteractive(); } else { isScreenOn = pm.isScreenOn(); } return isScreenOn; } public static String generateUniqueId() { String uniqueId = ApplicationManager.getInstance().getUniqueId(); if (StringUtil.isEmpty(uniqueId)) { uniqueId = generateMacAddress(); if (StringUtil.isEmpty(uniqueId) || "02:00:00:00:00:00".equalsIgnoreCase(uniqueId)) { try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ApplicationManager.getInstance().getContext()); uniqueId = adInfo.getId(); } catch (IOException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } } ApplicationManager.getInstance().setUniqueId(uniqueId); } return uniqueId; } public static String generateMacAddress() { String macAddress = ""; if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) { WifiManager wifiManager = (WifiManager) ApplicationManager.getInstance().getContext().getSystemService(Context.WIFI_SERVICE); WifiInfo info; if (wifiManager != null) { info = wifiManager.getConnectionInfo(); if (info != null) { macAddress = info.getMacAddress(); } } } else { macAddress = generateMacAddressFromSdk23(); } return macAddress; } public static String generateMacAddressFromSdk23() { try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : all) { if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue; byte[] bytes = networkInterface.getHardwareAddress(); if (bytes == null) { return "02:00:00:00:00:00"; } StringBuilder result = new StringBuilder(); for (byte macAddressByte : bytes) { result.append(Integer.toHexString(macAddressByte & 0xFF) + ":"); } if (result.length() > 0) { result.deleteCharAt(result.length() - 1); } return result.toString(); } } catch (Exception e) { e.printStackTrace(); } return "02:00:00:00:00:00"; } public static void requestGoogleCloudMessageId(Context context, String senderId) { if (isGooglePlayServicesAvailable(context)) { String registerId = ApplicationManager.getInstance().getGcmRegisterId(); if (StringUtil.isEmpty(registerId)) { registerGcmIdInBackground(context, senderId); } } } private static void registerGcmIdInBackground(final Context context, final String senderId) { new AsyncTask() { @Override protected Object doInBackground(Object[] params) { String msg = ""; try { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String registerId = gcm.register(senderId); ApplicationManager.getInstance().setGcmRegisterId(registerId); } catch (IOException e) { e.printStackTrace(); } return msg; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); //TODO send gcm id to server - Shark.M.Lin } }.executeOnExecutor(null, null, null); } public static boolean isGooglePlayServicesAvailable(Context context) { return GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS; } public static boolean isRunningOnEmulator() { return Build.BRAND.equalsIgnoreCase("generic"); } public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectivityManager.getActiveNetworkInfo(); return info != null && info.isAvailable(); } }
UTF-8
Java
7,393
java
SystemUtil.java
Java
[ { "context": "il.List;\nimport java.util.UUID;\n\n/**\n * Created by adye on 2015/4/30.\n */\npublic class SystemUtil {\n\n\n ", "end": 985, "score": 0.9752128720283508, "start": 981, "tag": "USERNAME", "value": "adye" }, { "context": "o);\n //TODO send gcm id to ser...
null
[]
package com.shark.baseproject.util; import android.app.ActivityManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Build; import android.os.PowerManager; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.shark.base.util.StringUtil; import com.shark.baseproject.manager.ApplicationManager; import java.io.IOException; import java.net.NetworkInterface; import java.util.Collections; import java.util.List; import java.util.UUID; /** * Created by adye on 2015/4/30. */ public class SystemUtil { public static boolean isAppRunning(Context context, String packageName) { ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> processInfoList = activityManager.getRunningAppProcesses(); for (int i = 0; i < processInfoList.size(); i++) { if (processInfoList.get(i).processName.equals(packageName)) { return true; } } return false; } public static boolean isAppOnForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { return false; } for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equalsIgnoreCase(context.getPackageName()) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true; } } return false; } public static boolean isPowerScreenOn(Context context) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); boolean isScreenOn; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) { isScreenOn = pm.isInteractive(); } else { isScreenOn = pm.isScreenOn(); } return isScreenOn; } public static String generateUniqueId() { String uniqueId = ApplicationManager.getInstance().getUniqueId(); if (StringUtil.isEmpty(uniqueId)) { uniqueId = generateMacAddress(); if (StringUtil.isEmpty(uniqueId) || "02:00:00:00:00:00".equalsIgnoreCase(uniqueId)) { try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ApplicationManager.getInstance().getContext()); uniqueId = adInfo.getId(); } catch (IOException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); uniqueId = UUID.randomUUID().toString(); } } ApplicationManager.getInstance().setUniqueId(uniqueId); } return uniqueId; } public static String generateMacAddress() { String macAddress = ""; if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) { WifiManager wifiManager = (WifiManager) ApplicationManager.getInstance().getContext().getSystemService(Context.WIFI_SERVICE); WifiInfo info; if (wifiManager != null) { info = wifiManager.getConnectionInfo(); if (info != null) { macAddress = info.getMacAddress(); } } } else { macAddress = generateMacAddressFromSdk23(); } return macAddress; } public static String generateMacAddressFromSdk23() { try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : all) { if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue; byte[] bytes = networkInterface.getHardwareAddress(); if (bytes == null) { return "02:00:00:00:00:00"; } StringBuilder result = new StringBuilder(); for (byte macAddressByte : bytes) { result.append(Integer.toHexString(macAddressByte & 0xFF) + ":"); } if (result.length() > 0) { result.deleteCharAt(result.length() - 1); } return result.toString(); } } catch (Exception e) { e.printStackTrace(); } return "02:00:00:00:00:00"; } public static void requestGoogleCloudMessageId(Context context, String senderId) { if (isGooglePlayServicesAvailable(context)) { String registerId = ApplicationManager.getInstance().getGcmRegisterId(); if (StringUtil.isEmpty(registerId)) { registerGcmIdInBackground(context, senderId); } } } private static void registerGcmIdInBackground(final Context context, final String senderId) { new AsyncTask() { @Override protected Object doInBackground(Object[] params) { String msg = ""; try { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String registerId = gcm.register(senderId); ApplicationManager.getInstance().setGcmRegisterId(registerId); } catch (IOException e) { e.printStackTrace(); } return msg; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); //TODO send gcm id to server - Shark.M.Lin } }.executeOnExecutor(null, null, null); } public static boolean isGooglePlayServicesAvailable(Context context) { return GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS; } public static boolean isRunningOnEmulator() { return Build.BRAND.equalsIgnoreCase("generic"); } public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectivityManager.getActiveNetworkInfo(); return info != null && info.isAvailable(); } }
7,393
0.62708
0.620046
184
39.179348
31.082733
142
false
false
0
0
0
0
0
0
0.494565
false
false
15
179384a390e534c7f7ae8cf01d257568631fd558
33,844,342,298,497
347d22bc8bb6c752a9df1cf769ee54efc081155a
/src/model/Magazine.java
556b1332bbc0b2676b9cffe07783c57824312959
[]
no_license
carlost1504/seguimiento-15
https://github.com/carlost1504/seguimiento-15
1d6b91e08a0c735ea3c2e1133e58c43b2f71aa21
979c24fd7faff5871642f883d908e3a2e16af7f9
refs/heads/main
2023-01-14T17:42:26.388000
2020-11-22T20:00:55
2020-11-22T20:00:55
315,120,810
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class Magazine extends Literature implements Salable { private final static double TAX_MAGAZINE = 0.05; private int week; public Magazine(int id, int basePrice, String title, boolean sale, int numberPages, int week) { super(id,basePrice,title,sale,numberPages); this.week = week; } public int getWeek() { return week; } public void setWeak(int week) { this.week = week; } @Override public String description() { String info = super.description()+"\nSemana: "+getWeek()+"\nPrecio total de venta: "+salePrice()+"\n"; return info; } @Override public double getTax() { double result = getBasePrice() * TAX_MAGAZINE; return result; } @Override public double salePrice() { double result = getBasePrice() + getTax(); return result; } }
UTF-8
Java
905
java
Magazine.java
Java
[]
null
[]
package model; public class Magazine extends Literature implements Salable { private final static double TAX_MAGAZINE = 0.05; private int week; public Magazine(int id, int basePrice, String title, boolean sale, int numberPages, int week) { super(id,basePrice,title,sale,numberPages); this.week = week; } public int getWeek() { return week; } public void setWeak(int week) { this.week = week; } @Override public String description() { String info = super.description()+"\nSemana: "+getWeek()+"\nPrecio total de venta: "+salePrice()+"\n"; return info; } @Override public double getTax() { double result = getBasePrice() * TAX_MAGAZINE; return result; } @Override public double salePrice() { double result = getBasePrice() + getTax(); return result; } }
905
0.61326
0.609945
36
24.138889
26.041796
110
false
false
0
0
0
0
0
0
0.611111
false
false
15
3d321c3bbe500cab6101d16f0ef191b9566cce3c
34,170,759,823,690
56e9ed4fb19345d5d20b742931bb9694bca8750f
/src/main/java/io/github.graphqly.reflector/metadata/strategy/query/AbstractResolverBuilder.java
78218a9dcaa8a6d7d6c3c301fc47d541ebe981ef
[]
no_license
graphqly/graphql-reflector
https://github.com/graphqly/graphql-reflector
371ac5d3a1334f51e06246b528a10676f669e4d1
4866469aceb1b7f7bc90c63dde2574146739a5cf
refs/heads/master
2023-06-24T08:20:19.550000
2023-06-15T14:31:23
2023-06-15T14:31:23
237,756,575
0
0
null
false
2023-06-15T14:31:24
2020-02-02T10:52:00
2022-01-05T04:51:16
2023-06-15T14:31:23
301
0
0
1
Java
false
false
package io.github.graphqly.reflector.metadata.strategy.query; import io.github.graphqly.reflector.metadata.TypedElement; import io.github.graphqly.reflector.metadata.exceptions.TypeMappingException; import io.github.graphqly.reflector.util.ClassUtils; import io.leangen.geantyref.GenericTypeReflector; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BinaryOperator; import java.util.function.Predicate; /** The base class for all built-in {@code ResolverBuilder}s */ @SuppressWarnings("WeakerAccess") public abstract class AbstractResolverBuilder implements ResolverBuilder { protected OperationInfoGenerator operationInfoGenerator; protected ResolverArgumentBuilder argumentBuilder; protected BinaryOperator<TypedElement> propertyElementReducer; protected List<Predicate<Member>> filters = new ArrayList<>(); public static TypedElement mergePropertyElements(TypedElement field, TypedElement getter) { return new TypedElement( GenericTypeReflector.mergeAnnotations(field.getJavaType(), getter.getJavaType()), field.getElement(), getter.getElement()); } public AbstractResolverBuilder withOperationInfoGenerator( OperationInfoGenerator operationInfoGenerator) { this.operationInfoGenerator = operationInfoGenerator; return this; } public AbstractResolverBuilder withResolverArgumentBuilder( ResolverArgumentBuilder argumentBuilder) { this.argumentBuilder = argumentBuilder; return this; } public AbstractResolverBuilder withPropertyElementReducer( BinaryOperator<TypedElement> propertyElementReducer) { this.propertyElementReducer = propertyElementReducer; return this; } @SafeVarargs public final AbstractResolverBuilder withFilters(Predicate<Member>... filters) { Collections.addAll(this.filters, filters); return this; } public AbstractResolverBuilder withDefaultFilters() { return withFilters(REAL_ONLY); } protected List<Predicate<Member>> getFilters() { return filters.isEmpty() ? Collections.singletonList(ACCEPT_ALL) : filters; } protected AnnotatedType getFieldType(Field field, ResolverBuilderParams params) { try { return params .getTypeTransformer() .transform(ClassUtils.getFieldType(field, params.getBeanType())); } catch (TypeMappingException e) { throw new TypeMappingException(field, params.getBeanType(), e); } } protected AnnotatedType getReturnType(Method method, ResolverBuilderParams params) { try { return params .getTypeTransformer() .transform(ClassUtils.getReturnType(method, params.getBeanType())); } catch (TypeMappingException e) { throw new TypeMappingException(method, params.getBeanType(), e); } } }
UTF-8
Java
2,961
java
AbstractResolverBuilder.java
Java
[]
null
[]
package io.github.graphqly.reflector.metadata.strategy.query; import io.github.graphqly.reflector.metadata.TypedElement; import io.github.graphqly.reflector.metadata.exceptions.TypeMappingException; import io.github.graphqly.reflector.util.ClassUtils; import io.leangen.geantyref.GenericTypeReflector; import java.lang.reflect.AnnotatedType; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BinaryOperator; import java.util.function.Predicate; /** The base class for all built-in {@code ResolverBuilder}s */ @SuppressWarnings("WeakerAccess") public abstract class AbstractResolverBuilder implements ResolverBuilder { protected OperationInfoGenerator operationInfoGenerator; protected ResolverArgumentBuilder argumentBuilder; protected BinaryOperator<TypedElement> propertyElementReducer; protected List<Predicate<Member>> filters = new ArrayList<>(); public static TypedElement mergePropertyElements(TypedElement field, TypedElement getter) { return new TypedElement( GenericTypeReflector.mergeAnnotations(field.getJavaType(), getter.getJavaType()), field.getElement(), getter.getElement()); } public AbstractResolverBuilder withOperationInfoGenerator( OperationInfoGenerator operationInfoGenerator) { this.operationInfoGenerator = operationInfoGenerator; return this; } public AbstractResolverBuilder withResolverArgumentBuilder( ResolverArgumentBuilder argumentBuilder) { this.argumentBuilder = argumentBuilder; return this; } public AbstractResolverBuilder withPropertyElementReducer( BinaryOperator<TypedElement> propertyElementReducer) { this.propertyElementReducer = propertyElementReducer; return this; } @SafeVarargs public final AbstractResolverBuilder withFilters(Predicate<Member>... filters) { Collections.addAll(this.filters, filters); return this; } public AbstractResolverBuilder withDefaultFilters() { return withFilters(REAL_ONLY); } protected List<Predicate<Member>> getFilters() { return filters.isEmpty() ? Collections.singletonList(ACCEPT_ALL) : filters; } protected AnnotatedType getFieldType(Field field, ResolverBuilderParams params) { try { return params .getTypeTransformer() .transform(ClassUtils.getFieldType(field, params.getBeanType())); } catch (TypeMappingException e) { throw new TypeMappingException(field, params.getBeanType(), e); } } protected AnnotatedType getReturnType(Method method, ResolverBuilderParams params) { try { return params .getTypeTransformer() .transform(ClassUtils.getReturnType(method, params.getBeanType())); } catch (TypeMappingException e) { throw new TypeMappingException(method, params.getBeanType(), e); } } }
2,961
0.768997
0.768997
85
33.835293
27.967144
93
false
false
0
0
0
0
0
0
0.541176
false
false
15
12abbef0cf2123b09ac46b862aa1d7b182825304
7,679,401,576,497
560663532d7f2c8df38495c8f488df000a5cdcc4
/Selinium/src/TestNG/Flipkart.java
e2a1856c190a597aed13d98538f1dfe16f73f8e3
[]
no_license
hariprasathj387/Selenium_Advance_Tutorials
https://github.com/hariprasathj387/Selenium_Advance_Tutorials
9c76b0e7f647798298200f25d31c56e570233efc
2b0121600fff1001c907e4f11f13691938d6c55e
refs/heads/main
2023-06-12T02:15:47.905000
2021-07-04T17:16:00
2021-07-04T17:16:00
382,907,454
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package TestNG; //import java.awt.List; //import org.checkerframework.checker.lock.qual.GuardedByUnknown; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import com.sun.org.apache.xerces.internal.impl.xpath.XPath; import com.sun.tools.javac.util.List; public class Flipkart { // driver in enitire class WebDriver driver; String url = "https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwj779fFtqDxAhX8yzgGHSmCD9IQPAgI"; @BeforeSuite void driverSetup() { System.setProperty("webdriver.chrome.driver", "C:program Files\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); //driver.manage().window().maximize(); } @Test(priority = 0) void webSiteSetup() { driver.get(url); String urlString = driver.getCurrentUrl(); System.out.println(urlString); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("flipkart", Keys.ENTER); WebElement flipkartpagElement = driver .findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div/div/div/div[1]/a/h3")); flipkartpagElement.click(); } @Test(priority = 1) void loginpage() { Actions sendEsc = new Actions(driver); Actions closeActions = sendEsc.sendKeys(Keys.ESCAPE); closeActions.build().perform(); } @Test(priority = 2) void flipkartPage() { WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("pocom2", Keys.ENTER); Actions page = new Actions(driver); for (int i = 0; i < 2; i++) { page.sendKeys(Keys.PAGE_DOWN).build().perform(); } } @Test(priority = 3) void comparrison() { java.util.List<WebElement> products = driver.findElements(By.xpath("//div[@class=\"_1YokD2 _3Mn1Gg\"][2]")); System.out.println(products.size()); for(WebElement names:products) { } } @AfterSuite void driverClose() { // driver.close(); } }
UTF-8
Java
2,242
java
Flipkart.java
Java
[ { "context": "ement(By.name(\"q\"));\r\n\t\tsearchElement.sendKeys(\"pocom2\", Keys.ENTER);\r\n\t\tActions page = new Actions(driv", "end": 1773, "score": 0.44262248277664185, "start": 1769, "tag": "PASSWORD", "value": "com2" } ]
null
[]
package TestNG; //import java.awt.List; //import org.checkerframework.checker.lock.qual.GuardedByUnknown; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import com.sun.org.apache.xerces.internal.impl.xpath.XPath; import com.sun.tools.javac.util.List; public class Flipkart { // driver in enitire class WebDriver driver; String url = "https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwj779fFtqDxAhX8yzgGHSmCD9IQPAgI"; @BeforeSuite void driverSetup() { System.setProperty("webdriver.chrome.driver", "C:program Files\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); //driver.manage().window().maximize(); } @Test(priority = 0) void webSiteSetup() { driver.get(url); String urlString = driver.getCurrentUrl(); System.out.println(urlString); WebElement searchBox = driver.findElement(By.name("q")); searchBox.sendKeys("flipkart", Keys.ENTER); WebElement flipkartpagElement = driver .findElement(By.xpath("//*[@id=\"rso\"]/div[1]/div/div/div/div/div/div/div[1]/a/h3")); flipkartpagElement.click(); } @Test(priority = 1) void loginpage() { Actions sendEsc = new Actions(driver); Actions closeActions = sendEsc.sendKeys(Keys.ESCAPE); closeActions.build().perform(); } @Test(priority = 2) void flipkartPage() { WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("po<PASSWORD>", Keys.ENTER); Actions page = new Actions(driver); for (int i = 0; i < 2; i++) { page.sendKeys(Keys.PAGE_DOWN).build().perform(); } } @Test(priority = 3) void comparrison() { java.util.List<WebElement> products = driver.findElements(By.xpath("//div[@class=\"_1YokD2 _3Mn1Gg\"][2]")); System.out.println(products.size()); for(WebElement names:products) { } } @AfterSuite void driverClose() { // driver.close(); } }
2,248
0.702498
0.693131
75
27.893333
24.699568
110
false
false
0
0
0
0
0
0
1.586667
false
false
15
58663fc2c800082989ae516e7c1f280ab75ae914
8,796,093,068,288
053ff5fca60d29d70d62d0ca58b1130a38b9dc66
/bundles/org.palladiosimulator.pcm.modified/src/org/palladiosimulator/pcm/repository/DataType.java
2cb80672e5fe4d031673a2d29f1619ef6036615f
[]
no_license
vitruv-tools/Vitruv-Applications-PCMJavaAdditionals
https://github.com/vitruv-tools/Vitruv-Applications-PCMJavaAdditionals
d616ac31fc3a65947ec5f65ace3bef67f7ef0cd1
9bb3453041222ce719dc4457813ad773eb755258
refs/heads/master
2023-02-18T22:25:37.872000
2021-01-21T07:57:33
2021-01-21T07:57:33
74,758,487
0
1
null
false
2020-12-04T15:47:23
2016-11-25T12:55:49
2019-09-12T10:21:50
2020-12-04T15:47:23
44,259
0
3
1
Java
false
false
/** * Copyright 2005-2009 by SDQ, IPD, University of Karlsruhe, Germany */ package org.palladiosimulator.pcm.repository; import org.eclipse.emf.cdo.CDOObject; /** * <!-- begin-user-doc --> A representation of the model object '<em><b>Data Type</b></em>'. <!-- * end-user-doc --> * * <!-- begin-model-doc --> This entity represents a data type that can be stored in a repository * and used for specification and modeling of interface signatures. <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.palladiosimulator.pcm.repository.DataType#getRepository__DataType * <em>Repository Data Type</em>}</li> * </ul> * * @see org.palladiosimulator.pcm.repository.RepositoryPackage#getDataType() * @model abstract="true" * @extends CDOObject * @generated */ public interface DataType extends CDOObject { /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ String copyright = "Copyright 2005-2015 by palladiosimulator.org"; /** * Returns the value of the '<em><b>Repository Data Type</b></em>' container reference. It is * bidirectional and its opposite is ' * {@link org.palladiosimulator.pcm.repository.Repository#getDataTypes__Repository * <em>Data Types Repository</em>}'. <!-- begin-user-doc --> <!-- end-user-doc --> <!-- * begin-model-doc --> This property specifies the repository to which this data type belongs. * <!-- end-model-doc --> * * @return the value of the '<em>Repository Data Type</em>' container reference. * @see #setRepository__DataType(Repository) * @see org.palladiosimulator.pcm.repository.RepositoryPackage#getDataType_Repository__DataType() * @see org.palladiosimulator.pcm.repository.Repository#getDataTypes__Repository * @model opposite="dataTypes__Repository" required="true" transient="false" * @generated */ Repository getRepository__DataType(); /** * Sets the value of the ' * {@link org.palladiosimulator.pcm.repository.DataType#getRepository__DataType * <em>Repository Data Type</em>}' container reference. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @param value * the new value of the '<em>Repository Data Type</em>' container reference. * @see #getRepository__DataType() * @generated */ void setRepository__DataType(Repository value); } // DataType
UTF-8
Java
2,459
java
DataType.java
Java
[]
null
[]
/** * Copyright 2005-2009 by SDQ, IPD, University of Karlsruhe, Germany */ package org.palladiosimulator.pcm.repository; import org.eclipse.emf.cdo.CDOObject; /** * <!-- begin-user-doc --> A representation of the model object '<em><b>Data Type</b></em>'. <!-- * end-user-doc --> * * <!-- begin-model-doc --> This entity represents a data type that can be stored in a repository * and used for specification and modeling of interface signatures. <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.palladiosimulator.pcm.repository.DataType#getRepository__DataType * <em>Repository Data Type</em>}</li> * </ul> * * @see org.palladiosimulator.pcm.repository.RepositoryPackage#getDataType() * @model abstract="true" * @extends CDOObject * @generated */ public interface DataType extends CDOObject { /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ String copyright = "Copyright 2005-2015 by palladiosimulator.org"; /** * Returns the value of the '<em><b>Repository Data Type</b></em>' container reference. It is * bidirectional and its opposite is ' * {@link org.palladiosimulator.pcm.repository.Repository#getDataTypes__Repository * <em>Data Types Repository</em>}'. <!-- begin-user-doc --> <!-- end-user-doc --> <!-- * begin-model-doc --> This property specifies the repository to which this data type belongs. * <!-- end-model-doc --> * * @return the value of the '<em>Repository Data Type</em>' container reference. * @see #setRepository__DataType(Repository) * @see org.palladiosimulator.pcm.repository.RepositoryPackage#getDataType_Repository__DataType() * @see org.palladiosimulator.pcm.repository.Repository#getDataTypes__Repository * @model opposite="dataTypes__Repository" required="true" transient="false" * @generated */ Repository getRepository__DataType(); /** * Sets the value of the ' * {@link org.palladiosimulator.pcm.repository.DataType#getRepository__DataType * <em>Repository Data Type</em>}' container reference. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @param value * the new value of the '<em>Repository Data Type</em>' container reference. * @see #getRepository__DataType() * @generated */ void setRepository__DataType(Repository value); } // DataType
2,459
0.655958
0.649451
67
35.701492
34.321575
101
false
false
0
0
0
0
0
0
0.119403
false
false
15
ad34476432333111f8af03613a80b57d8dcef433
32,598,801,810,452
de843bcd76ed5709e6770653f0c4a23d36fc79d2
/app/src/main/java/com/huivip/gpsspeedwidget/service/AutoWidgetFloatingService.java
7e3a3430d5abb236dc6f4e73a94416070ca48c00
[ "MIT" ]
permissive
laihui0207/GPSSpeedWidget
https://github.com/laihui0207/GPSSpeedWidget
871f80a16bd06d37d4ec17f1efa61139fb7cfc15
6d43b69d27540dbefd108d6ff35cdd2fbde785b9
refs/heads/master
2023-05-26T16:33:04.124000
2021-07-24T17:30:35
2021-07-24T17:30:35
107,372,764
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huivip.gpsspeedwidget.service; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.app.Service; import android.appwidget.AppWidgetHost; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.huivip.gpsspeedwidget.BuildConfig; import com.huivip.gpsspeedwidget.Constant; import com.huivip.gpsspeedwidget.GpsUtil; import com.huivip.gpsspeedwidget.R; import com.huivip.gpsspeedwidget.utils.CrashHandler; import com.huivip.gpsspeedwidget.utils.PrefUtils; import java.util.Timer; import java.util.TimerTask; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; /** * Created by laisun on 28/02/2018. */ public class AutoWidgetFloatingService extends Service { public static final String EXTRA_CLOSE = "com.huivip.gpsspeedwidget.EXTRA_CLOSE"; public static final String DRIVE_WAY = "com.huivip.gpssppeedWidget.drive_way"; private WindowManager mWindowManager; private View mFloatingView; GpsUtil gpsUtil; @BindView(R.id.autoDriveWayView) LinearLayout driveWayView; @BindView(R.id.imageView_autoNvi_close) ImageView closeImage; @BindView(R.id.imageView_autoNvi_move) ImageView moveImage; AppWidgetHost appWidgetHost; TimerTask locationScanTask; Timer locationTimer = new Timer(); Handler handler = new Handler(); private ServiceConnection mServiceConnection; RoadLineService.RoadLineBinder roadLineBinder; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { if (intent.getBooleanExtra(EXTRA_CLOSE, false) /*|| !AppSettings.get().isShowAmapWidgetContent()*/ /*|| gpsUtil.getAutoNaviStatus()!=Constant.Navi_Status_Started*/) { onStop(); stopSelf(); return super.onStartCommand(intent, flags, startId); } } return Service.START_REDELIVER_INTENT; } private void onStop() { if (this.locationTimer != null) { locationTimer.cancel(); locationTimer.purge(); } if (mFloatingView != null && mWindowManager != null) { mWindowManager.removeView(mFloatingView); } } private void showPluginContent() { if(roadLineBinder!=null){ View view=roadLineBinder.getWidgetView(); if(driveWayView.getChildCount()>0) { driveWayView.removeAllViews(); } if(view!=null){ if(view.getParent()!=null) { ((ViewGroup) view.getParent()).removeView(view); } driveWayView.addView(view); } } } @Override public void onCreate() { if (!PrefUtils.isEnableDrawOverFeature(getApplicationContext())) { Toast.makeText(getApplicationContext(), "需要打开GPS插件的悬浮窗口权限", Toast.LENGTH_LONG).show(); try { openSettings(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, BuildConfig.APPLICATION_ID); } catch (ActivityNotFoundException ignored) { } return; } appWidgetHost = new AppWidgetHost(getApplicationContext(), Constant.APP_WIDGET_HOST_ID); gpsUtil = GpsUtil.getInstance(getApplicationContext()); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); LayoutInflater inflater = LayoutInflater.from(this); mFloatingView = inflater.inflate(R.layout.floating_auto_widget, null); WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, getWindowType(), WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.START; // params.alpha = 0.9f;//PrefUtils.getOpacity(getApplicationContext()) / 100.0F; ButterKnife.bind(this, mFloatingView); mWindowManager.addView(mFloatingView, params); driveWayView.setOnTouchListener(new FloatingOnTouchListener()); /* if(driveWayView!=null) { Drawable backgroundDrawable = driveWayView.getBackground(); backgroundDrawable.setAlpha(50); }*/ initMonitorPosition(); mServiceConnection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { roadLineBinder= (RoadLineService.RoadLineBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } }; getApplicationContext().bindService(new Intent(getApplicationContext(), RoadLineService.class), mServiceConnection, Context.BIND_AUTO_CREATE); this.locationScanTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { showPluginContent(); } }); } }; this.locationTimer.schedule(this.locationScanTask, 0L, 1000L); CrashHandler.getInstance().init(getApplicationContext()); //moveImage.setOnTouchListener(new FloatingOnTouchListener()); // EventBus.getDefault().register(this); super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); /*if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); }*/ } @OnClick(value = {R.id.imageView_autoNvi_close}) public void onCloseEvent(View view) { onStop(); stopSelf(); } private int getWindowType() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_PHONE; } private void openSettings(String settingsAction, String packageName) { Intent intent = new Intent(settingsAction); intent.setFlags(FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent); } private void initMonitorPosition() { if (mFloatingView == null) { return; } mFloatingView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); String[] split = PrefUtils.getDriveWayFloatingLocation(getApplicationContext()).split(","); boolean left = Boolean.parseBoolean(split[0]); float yRatio = Float.parseFloat(split[1]); /*if (PrefUtils.isNaviFloattingAutoSolt(getApplicationContext()) && !PrefUtils.isEnableNaviFloatingFixed(getApplicationContext())) { Point screenSize = new Point(); mWindowManager.getDefaultDisplay().getSize(screenSize); params.x = left ? 0 : screenSize.x - mFloatingView.getWidth(); params.y = (int) (yRatio * screenSize.y + 0.5f); } else {*/ String[] xy = PrefUtils.getDriveWayFloatingSolidLocation(getApplicationContext()).split(","); params.x = (int) Float.parseFloat(xy[0]); params.y = (int) Float.parseFloat(xy[1]); /* }*/ try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } mFloatingView.setVisibility(View.VISIBLE); mFloatingView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } /* private void animateViewToSideSlot() { Point screenSize = new Point(); mWindowManager.getDefaultDisplay().getSize(screenSize); WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); int endX; if (params.x + mFloatingView.getWidth() / 2 >= screenSize.x / 2) { endX = screenSize.x - mFloatingView.getWidth(); } else { endX = 0; } PrefUtils.setDriveWayFloatingLocation(getApplicationContext(), (float) params.y / screenSize.y, endX == 0); ValueAnimator valueAnimator = ValueAnimator.ofInt(params.x, endX) .setDuration(300); valueAnimator.setInterpolator(new LinearOutSlowInInterpolator()); valueAnimator.addUpdateListener(animation -> { WindowManager.LayoutParams params1 = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); params1.x = (int) animation.getAnimatedValue(); try { mWindowManager.updateViewLayout(mFloatingView, params1); } catch (IllegalArgumentException ignore) { } }); valueAnimator.start(); }*/ private class FloatingOnTouchListener implements View.OnTouchListener { private float mInitialTouchX; private float mInitialTouchY; private int mInitialX; private int mInitialY; private long mStartClickTime; private boolean mIsClick; private AnimatorSet fadeAnimator; private float initialAlpha; private ValueAnimator fadeOut; private ValueAnimator fadeIn; public FloatingOnTouchListener() { final WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); fadeOut = ValueAnimator.ofFloat(params.alpha, 0.1F); fadeOut.setInterpolator(new FastOutSlowInInterpolator()); fadeOut.setDuration(100); fadeOut.addUpdateListener(valueAnimator -> { params.alpha = (float) valueAnimator.getAnimatedValue(); try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } }); fadeIn = fadeOut.clone(); fadeIn.setFloatValues(0.5F, params.alpha); fadeIn.setStartDelay(5000); } @Override public boolean onTouch(View v, MotionEvent event) { final WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mInitialTouchX = event.getRawX(); mInitialTouchY = event.getRawY(); mInitialX = params.x; mInitialY = params.y; mStartClickTime = System.currentTimeMillis(); mIsClick = true; return true; case MotionEvent.ACTION_MOVE: float dX = event.getRawX() - mInitialTouchX; float dY = event.getRawY() - mInitialTouchY; if ((mIsClick && (Math.abs(dX) > 10 || Math.abs(dY) > 10)) || System.currentTimeMillis() - mStartClickTime > ViewConfiguration.getLongPressTimeout()) { mIsClick = false; } if (!mIsClick) { params.x = (int) (dX + mInitialX); params.y = (int) (dY + mInitialY); try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } } return true; case MotionEvent.ACTION_UP: if (mIsClick && System.currentTimeMillis() - mStartClickTime <= ViewConfiguration.getLongPressTimeout()) { if (fadeAnimator != null && fadeAnimator.isStarted()) { fadeAnimator.cancel(); params.alpha = initialAlpha; try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } } else { initialAlpha = params.alpha; fadeAnimator = new AnimatorSet(); fadeAnimator.play(fadeOut).before(fadeIn); fadeAnimator.start(); } } else { PrefUtils.setDriveWayFloatingSolidLocation(getApplicationContext(), params.x, params.y); } return true; } return false; } } }
UTF-8
Java
14,132
java
AutoWidgetFloatingService.java
Java
[ { "context": ".Intent.FLAG_ACTIVITY_NEW_TASK;\n\n/**\n * Created by laisun on 28/02/2018.\n */\n\npublic class AutoWidgetFloati", "end": 1535, "score": 0.9996537566184998, "start": 1529, "tag": "USERNAME", "value": "laisun" } ]
null
[]
package com.huivip.gpsspeedwidget.service; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.app.Service; import android.appwidget.AppWidgetHost; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.view.animation.FastOutSlowInInterpolator; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.huivip.gpsspeedwidget.BuildConfig; import com.huivip.gpsspeedwidget.Constant; import com.huivip.gpsspeedwidget.GpsUtil; import com.huivip.gpsspeedwidget.R; import com.huivip.gpsspeedwidget.utils.CrashHandler; import com.huivip.gpsspeedwidget.utils.PrefUtils; import java.util.Timer; import java.util.TimerTask; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; /** * Created by laisun on 28/02/2018. */ public class AutoWidgetFloatingService extends Service { public static final String EXTRA_CLOSE = "com.huivip.gpsspeedwidget.EXTRA_CLOSE"; public static final String DRIVE_WAY = "com.huivip.gpssppeedWidget.drive_way"; private WindowManager mWindowManager; private View mFloatingView; GpsUtil gpsUtil; @BindView(R.id.autoDriveWayView) LinearLayout driveWayView; @BindView(R.id.imageView_autoNvi_close) ImageView closeImage; @BindView(R.id.imageView_autoNvi_move) ImageView moveImage; AppWidgetHost appWidgetHost; TimerTask locationScanTask; Timer locationTimer = new Timer(); Handler handler = new Handler(); private ServiceConnection mServiceConnection; RoadLineService.RoadLineBinder roadLineBinder; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { if (intent.getBooleanExtra(EXTRA_CLOSE, false) /*|| !AppSettings.get().isShowAmapWidgetContent()*/ /*|| gpsUtil.getAutoNaviStatus()!=Constant.Navi_Status_Started*/) { onStop(); stopSelf(); return super.onStartCommand(intent, flags, startId); } } return Service.START_REDELIVER_INTENT; } private void onStop() { if (this.locationTimer != null) { locationTimer.cancel(); locationTimer.purge(); } if (mFloatingView != null && mWindowManager != null) { mWindowManager.removeView(mFloatingView); } } private void showPluginContent() { if(roadLineBinder!=null){ View view=roadLineBinder.getWidgetView(); if(driveWayView.getChildCount()>0) { driveWayView.removeAllViews(); } if(view!=null){ if(view.getParent()!=null) { ((ViewGroup) view.getParent()).removeView(view); } driveWayView.addView(view); } } } @Override public void onCreate() { if (!PrefUtils.isEnableDrawOverFeature(getApplicationContext())) { Toast.makeText(getApplicationContext(), "需要打开GPS插件的悬浮窗口权限", Toast.LENGTH_LONG).show(); try { openSettings(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, BuildConfig.APPLICATION_ID); } catch (ActivityNotFoundException ignored) { } return; } appWidgetHost = new AppWidgetHost(getApplicationContext(), Constant.APP_WIDGET_HOST_ID); gpsUtil = GpsUtil.getInstance(getApplicationContext()); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); LayoutInflater inflater = LayoutInflater.from(this); mFloatingView = inflater.inflate(R.layout.floating_auto_widget, null); WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, getWindowType(), WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.START; // params.alpha = 0.9f;//PrefUtils.getOpacity(getApplicationContext()) / 100.0F; ButterKnife.bind(this, mFloatingView); mWindowManager.addView(mFloatingView, params); driveWayView.setOnTouchListener(new FloatingOnTouchListener()); /* if(driveWayView!=null) { Drawable backgroundDrawable = driveWayView.getBackground(); backgroundDrawable.setAlpha(50); }*/ initMonitorPosition(); mServiceConnection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { roadLineBinder= (RoadLineService.RoadLineBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } }; getApplicationContext().bindService(new Intent(getApplicationContext(), RoadLineService.class), mServiceConnection, Context.BIND_AUTO_CREATE); this.locationScanTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { showPluginContent(); } }); } }; this.locationTimer.schedule(this.locationScanTask, 0L, 1000L); CrashHandler.getInstance().init(getApplicationContext()); //moveImage.setOnTouchListener(new FloatingOnTouchListener()); // EventBus.getDefault().register(this); super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); /*if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); }*/ } @OnClick(value = {R.id.imageView_autoNvi_close}) public void onCloseEvent(View view) { onStop(); stopSelf(); } private int getWindowType() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_PHONE; } private void openSettings(String settingsAction, String packageName) { Intent intent = new Intent(settingsAction); intent.setFlags(FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("package:" + packageName)); startActivity(intent); } private void initMonitorPosition() { if (mFloatingView == null) { return; } mFloatingView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); String[] split = PrefUtils.getDriveWayFloatingLocation(getApplicationContext()).split(","); boolean left = Boolean.parseBoolean(split[0]); float yRatio = Float.parseFloat(split[1]); /*if (PrefUtils.isNaviFloattingAutoSolt(getApplicationContext()) && !PrefUtils.isEnableNaviFloatingFixed(getApplicationContext())) { Point screenSize = new Point(); mWindowManager.getDefaultDisplay().getSize(screenSize); params.x = left ? 0 : screenSize.x - mFloatingView.getWidth(); params.y = (int) (yRatio * screenSize.y + 0.5f); } else {*/ String[] xy = PrefUtils.getDriveWayFloatingSolidLocation(getApplicationContext()).split(","); params.x = (int) Float.parseFloat(xy[0]); params.y = (int) Float.parseFloat(xy[1]); /* }*/ try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } mFloatingView.setVisibility(View.VISIBLE); mFloatingView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } /* private void animateViewToSideSlot() { Point screenSize = new Point(); mWindowManager.getDefaultDisplay().getSize(screenSize); WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); int endX; if (params.x + mFloatingView.getWidth() / 2 >= screenSize.x / 2) { endX = screenSize.x - mFloatingView.getWidth(); } else { endX = 0; } PrefUtils.setDriveWayFloatingLocation(getApplicationContext(), (float) params.y / screenSize.y, endX == 0); ValueAnimator valueAnimator = ValueAnimator.ofInt(params.x, endX) .setDuration(300); valueAnimator.setInterpolator(new LinearOutSlowInInterpolator()); valueAnimator.addUpdateListener(animation -> { WindowManager.LayoutParams params1 = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); params1.x = (int) animation.getAnimatedValue(); try { mWindowManager.updateViewLayout(mFloatingView, params1); } catch (IllegalArgumentException ignore) { } }); valueAnimator.start(); }*/ private class FloatingOnTouchListener implements View.OnTouchListener { private float mInitialTouchX; private float mInitialTouchY; private int mInitialX; private int mInitialY; private long mStartClickTime; private boolean mIsClick; private AnimatorSet fadeAnimator; private float initialAlpha; private ValueAnimator fadeOut; private ValueAnimator fadeIn; public FloatingOnTouchListener() { final WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); fadeOut = ValueAnimator.ofFloat(params.alpha, 0.1F); fadeOut.setInterpolator(new FastOutSlowInInterpolator()); fadeOut.setDuration(100); fadeOut.addUpdateListener(valueAnimator -> { params.alpha = (float) valueAnimator.getAnimatedValue(); try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } }); fadeIn = fadeOut.clone(); fadeIn.setFloatValues(0.5F, params.alpha); fadeIn.setStartDelay(5000); } @Override public boolean onTouch(View v, MotionEvent event) { final WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFloatingView.getLayoutParams(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mInitialTouchX = event.getRawX(); mInitialTouchY = event.getRawY(); mInitialX = params.x; mInitialY = params.y; mStartClickTime = System.currentTimeMillis(); mIsClick = true; return true; case MotionEvent.ACTION_MOVE: float dX = event.getRawX() - mInitialTouchX; float dY = event.getRawY() - mInitialTouchY; if ((mIsClick && (Math.abs(dX) > 10 || Math.abs(dY) > 10)) || System.currentTimeMillis() - mStartClickTime > ViewConfiguration.getLongPressTimeout()) { mIsClick = false; } if (!mIsClick) { params.x = (int) (dX + mInitialX); params.y = (int) (dY + mInitialY); try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } } return true; case MotionEvent.ACTION_UP: if (mIsClick && System.currentTimeMillis() - mStartClickTime <= ViewConfiguration.getLongPressTimeout()) { if (fadeAnimator != null && fadeAnimator.isStarted()) { fadeAnimator.cancel(); params.alpha = initialAlpha; try { mWindowManager.updateViewLayout(mFloatingView, params); } catch (IllegalArgumentException ignore) { } } else { initialAlpha = params.alpha; fadeAnimator = new AnimatorSet(); fadeAnimator.play(fadeOut).before(fadeIn); fadeAnimator.start(); } } else { PrefUtils.setDriveWayFloatingSolidLocation(getApplicationContext(), params.x, params.y); } return true; } return false; } } }
14,132
0.607826
0.603927
353
38.960339
29.022577
150
false
false
0
0
0
0
0
0
0.643059
false
false
15
69f213d37fd264a54fddc34c15621b10e53c5f18
29,738,353,598,427
42fc76accc986e906bb0b241d00a3da7f36e3e52
/src/main/java/uk/ac/ed/epcc/webapp/model/history/LinkHistorySQLFilter.java
a629a299cf5d59e652f7e407b186bf088b9a1bbd
[ "Apache-2.0" ]
permissive
spbooth/SAFE-WEBAPP
https://github.com/spbooth/SAFE-WEBAPP
44ec39963432762ae5e90319d944d8dea1803219
0de7e84a664e904b8577fb6b8ed57144740c2841
refs/heads/master
2023-07-08T22:22:48.048000
2023-06-22T07:59:22
2023-06-22T07:59:22
47,343,535
3
0
NOASSERTION
false
2023-02-22T13:33:54
2015-12-03T16:10:41
2022-08-08T11:07:35
2023-02-22T13:33:19
127,793
3
0
1
Java
false
false
//| Copyright - The University of Edinburgh 2011 | //| | //| 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 uk.ac.ed.epcc.webapp.model.history; import uk.ac.ed.epcc.webapp.Indexed; import uk.ac.ed.epcc.webapp.exceptions.ConsistencyError; import uk.ac.ed.epcc.webapp.model.data.*; /** SQLFilter for LinkHistory objects. * * Note that if * History table does not actually contain the Link fields then * the selection will use a join. * * @author spb * @param <L> * @param <R> * @param <T> * @param <H> * @param <M> * */ public class LinkHistorySQLFilter<L extends Indexed, R extends Indexed, T extends IndexedLinkManager.Link<L,R>, H extends DataObject & History<T>, M extends DataObjectFactory<H> & LinkHistoryHandler<L, R, T>> extends DataObjectSQLAndFilter<M,H>{ /** * */ private final M linkHistoryManager; public LinkHistorySQLFilter( M linkHistoryManager, L left, R right) { super(linkHistoryManager); this.linkHistoryManager = linkHistoryManager; if( left != null && right != null){ // should use normal HistoryFilter with peer id. throw new ConsistencyError("Both links specified for LinkHistoryFilter"); } // need to select something String left_field=linkHistoryManager.getLinkManager().getLeftField(); String right_field=linkHistoryManager.getLinkManager().getRightField(); boolean has_left_field = linkHistoryManager.canLeftJoin(); boolean has_right_field = linkHistoryManager.canRightJoin(); if( left != null ){ if(has_left_field){ addFilter(new ReferenceFilter<>(this.linkHistoryManager,left_field,left)); }else{ // join with parent addFilter(((DataObjectFactory<H>)linkHistoryManager).getRemoteSQLFilter(linkHistoryManager.getLinkManager(), linkHistoryManager.getPeerName(), new ReferenceFilter<>(linkHistoryManager.getLinkManager(), left_field,left))); } }else if( right != null){ if(has_right_field && right != null){ addFilter(new ReferenceFilter<>(this.linkHistoryManager,right_field,right)); }else{ // join with parent addFilter(((DataObjectFactory<H>)linkHistoryManager).getRemoteSQLFilter(linkHistoryManager.getLinkManager(), linkHistoryManager.getPeerName(), new ReferenceFilter<>(linkHistoryManager.getLinkManager(), right_field,right))); } } } }
UTF-8
Java
3,230
java
LinkHistorySQLFilter.java
Java
[ { "context": "n\n * the selection will use a join.\n * \n * @author spb\n * @param <L> \n * @param <R> \n * @param <T> \n * @", "end": 1373, "score": 0.9995521306991577, "start": 1370, "tag": "USERNAME", "value": "spb" } ]
null
[]
//| Copyright - The University of Edinburgh 2011 | //| | //| 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 uk.ac.ed.epcc.webapp.model.history; import uk.ac.ed.epcc.webapp.Indexed; import uk.ac.ed.epcc.webapp.exceptions.ConsistencyError; import uk.ac.ed.epcc.webapp.model.data.*; /** SQLFilter for LinkHistory objects. * * Note that if * History table does not actually contain the Link fields then * the selection will use a join. * * @author spb * @param <L> * @param <R> * @param <T> * @param <H> * @param <M> * */ public class LinkHistorySQLFilter<L extends Indexed, R extends Indexed, T extends IndexedLinkManager.Link<L,R>, H extends DataObject & History<T>, M extends DataObjectFactory<H> & LinkHistoryHandler<L, R, T>> extends DataObjectSQLAndFilter<M,H>{ /** * */ private final M linkHistoryManager; public LinkHistorySQLFilter( M linkHistoryManager, L left, R right) { super(linkHistoryManager); this.linkHistoryManager = linkHistoryManager; if( left != null && right != null){ // should use normal HistoryFilter with peer id. throw new ConsistencyError("Both links specified for LinkHistoryFilter"); } // need to select something String left_field=linkHistoryManager.getLinkManager().getLeftField(); String right_field=linkHistoryManager.getLinkManager().getRightField(); boolean has_left_field = linkHistoryManager.canLeftJoin(); boolean has_right_field = linkHistoryManager.canRightJoin(); if( left != null ){ if(has_left_field){ addFilter(new ReferenceFilter<>(this.linkHistoryManager,left_field,left)); }else{ // join with parent addFilter(((DataObjectFactory<H>)linkHistoryManager).getRemoteSQLFilter(linkHistoryManager.getLinkManager(), linkHistoryManager.getPeerName(), new ReferenceFilter<>(linkHistoryManager.getLinkManager(), left_field,left))); } }else if( right != null){ if(has_right_field && right != null){ addFilter(new ReferenceFilter<>(this.linkHistoryManager,right_field,right)); }else{ // join with parent addFilter(((DataObjectFactory<H>)linkHistoryManager).getRemoteSQLFilter(linkHistoryManager.getLinkManager(), linkHistoryManager.getPeerName(), new ReferenceFilter<>(linkHistoryManager.getLinkManager(), right_field,right))); } } } }
3,230
0.636532
0.634056
83
37.927711
31.928679
112
false
false
0
0
0
0
0
0
2.096385
false
false
15
0a434e4578c9c19476e0caacf2663df8f06dc062
5,918,464,983,478
7bd3af8d387a5227c5d7c26d2892097d9fbdfc02
/sources/com/google/android/gms/ads/internal/js/zzi.java
c309d2acdd2f80149655dae009eee69179379756
[]
no_license
Sanjida-urme/Bangladesh_Stock_Exchang
https://github.com/Sanjida-urme/Bangladesh_Stock_Exchang
445919408454db50358d1b8513b4847a7ec633ac
bd293ebcf6a9b6e7abe2515005db4c60a94bda2a
refs/heads/master
2020-05-18T14:02:30.475000
2019-05-01T17:59:34
2019-05-01T17:59:34
184,456,836
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.ads.internal.js; import org.json.JSONObject; final class zzi implements Runnable { private /* synthetic */ String zzbzd; private /* synthetic */ JSONObject zzbze; private /* synthetic */ zzg zzbzf; zzi(zzg zzg, String str, JSONObject jSONObject) { this.zzbzf = zzg; this.zzbzd = str; this.zzbze = jSONObject; } public final void run() { this.zzbzf.zzbwq.zzb(this.zzbzd, this.zzbze); } }
UTF-8
Java
482
java
zzi.java
Java
[]
null
[]
package com.google.android.gms.ads.internal.js; import org.json.JSONObject; final class zzi implements Runnable { private /* synthetic */ String zzbzd; private /* synthetic */ JSONObject zzbze; private /* synthetic */ zzg zzbzf; zzi(zzg zzg, String str, JSONObject jSONObject) { this.zzbzf = zzg; this.zzbzd = str; this.zzbze = jSONObject; } public final void run() { this.zzbzf.zzbwq.zzb(this.zzbzd, this.zzbze); } }
482
0.641079
0.641079
19
24.368422
19.137207
53
false
false
0
0
0
0
0
0
0.631579
false
false
15
96099fc7067158574d1ad0b95aba6554e0f7b63e
35,450,660,076,789
4e5cd6ae4e8f7036237bca646c7e6699a6349723
/app/src/main/java/com/example/pokemonwithnerdapplication/network/PokemonApiService.java
86de307fa2edbf52470120da2333acac6b46c544
[]
no_license
medmjs/PkemonDaggerHilt
https://github.com/medmjs/PkemonDaggerHilt
e92a51e41ee849bbe52ab8209adc878b20155130
9ca3a35f974a1e117819bde3bf4db4b57feb1022
refs/heads/master
2023-07-18T14:39:22.901000
2021-09-05T14:28:33
2021-09-05T14:28:33
403,328,952
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.pokemonwithnerdapplication.network; import com.example.pokemonwithnerdapplication.model.PokemonResponse; import io.reactivex.rxjava3.core.Observable; import retrofit2.http.GET; public interface PokemonApiService { @GET("pokemon") public Observable<PokemonResponse> getPokemon(); }
UTF-8
Java
313
java
PokemonApiService.java
Java
[]
null
[]
package com.example.pokemonwithnerdapplication.network; import com.example.pokemonwithnerdapplication.model.PokemonResponse; import io.reactivex.rxjava3.core.Observable; import retrofit2.http.GET; public interface PokemonApiService { @GET("pokemon") public Observable<PokemonResponse> getPokemon(); }
313
0.814696
0.808307
12
25.083334
24.277761
68
false
false
0
0
0
0
0
0
0.416667
false
false
15
055dd4f60285a79fe1095cee20e63769e5d69e19
19,997,367,776,789
a7336b168cf30725c1cc628a01fc817b4a0e1165
/hw12-1191240863/src/main/java/hr/fer/zemris/java/custom/scripting/parser/SmartScriptParser.java
eb094ee0da42e2d6501360ba20c1441c2c643f67
[]
no_license
biljazovic/java_course
https://github.com/biljazovic/java_course
c76b813434bfd008b99f6ce661dd5748e0932bc4
ff0b8f6a20dab50505c8a66618e879a51bc6e6ab
refs/heads/master
2022-12-09T03:48:57.281000
2020-01-03T12:55:19
2020-01-03T12:55:19
189,896,276
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hr.fer.zemris.java.custom.scripting.parser; import java.util.ArrayList; import java.util.List; import java.util.Stack; import hr.fer.zemris.java.custom.scripting.elems.ElementConstantDouble; import hr.fer.zemris.java.custom.scripting.elems.ElementConstantInteger; import hr.fer.zemris.java.custom.scripting.elems.ElementFunction; import hr.fer.zemris.java.custom.scripting.elems.ElementOperator; import hr.fer.zemris.java.custom.scripting.elems.ElementString; import hr.fer.zemris.java.custom.scripting.elems.ElementVariable; import hr.fer.zemris.java.custom.scripting.lexer.LexerException; import hr.fer.zemris.java.custom.scripting.lexer.LexerState; import hr.fer.zemris.java.custom.scripting.lexer.SmartScriptLexer; import hr.fer.zemris.java.custom.scripting.lexer.Token; import hr.fer.zemris.java.custom.scripting.lexer.TokenType; import hr.fer.zemris.java.custom.scripting.nodes.DocumentNode; import hr.fer.zemris.java.custom.scripting.nodes.EchoNode; import hr.fer.zemris.java.custom.scripting.nodes.ForLoopNode; import hr.fer.zemris.java.custom.scripting.nodes.Node; import hr.fer.zemris.java.custom.scripting.nodes.TextNode; /** * This class parses given text and makes tree-like structure with root in {@link #documentNode}. * It makes use of {@link SmartScriptLexer} to tokenize given text. * * <p> There are three possible nodes besides documentNode: EchoNode, ForLoopNode and TextNode. * ForLoopNode is generated when a tag named FOR is encountered. Then every Node till matching END * tag is added as a child of that ForLoopNode. * * <p>EchoNode is generated when a tag named = is encountered. * * <p>TextNode is generated from text outside of tags. * * Example text and tree this parser produces: * <pre>====================================================== * This is text. * {$ FOR i 1 2 $} * Inside for loop! * {$ = 1 "1.2" 1.2 * $}{$END$} * Outside! * ====================================================== * DocumentNode * |- TextNode (...) * |- ForLoopNode (i, 1, 2) * |- TextNode (...) * |- EchoNode (1, "1.2", 1.2, *) * |- TextNode (...) * ====================================================== </pre> * * Throws {@link SmartScriptParserException} if given text can't be parsed. * * @see SmartScriptLexer * * @author Bruno Iljazović */ public class SmartScriptParser { /** stakc of nodes */ private Stack<Object> stack; /** lexer used for tokenizing the input string */ private SmartScriptLexer lexer; /** The text that is parsed */ private String documentBody; /** Root of the structure of nodes */ private DocumentNode documentNode; /** * Instantiates a new smart script parser text given as String argument. * * @param documentBody the text to be parsed. */ public SmartScriptParser(String documentBody) { this.documentBody = documentBody; parse(); } /** * Gets the document node which contains information about whole tree structure. * * @return the document node */ public DocumentNode getDocumentNode() { return documentNode; } /** * Wrapper for {@link SmartScriptLexer#nextToken} method * @return next token * @throws SmartScriptParserException if a {@link LexerException} occurred */ private Token getToken() { try { return lexer.nextToken(); } catch(LexerException ex) { throw new SmartScriptParserException(ex); } } /** * Parses the text stored in {@link #documentBody}. Parser manages states of the lexer. * * * @throws SmartScriptParserException if the text can't be parsed. */ private void parse() { stack = new Stack<>(); documentNode = new DocumentNode(); stack.push(documentNode); lexer = new SmartScriptLexer(documentBody); lexer.setState(LexerState.TEXT); Token token; //array of Element-s for ForLoopNode and EchoNode List<Object> elements = new ArrayList<>(); String tagName = ""; do { token = getToken(); if (token.getType() == TokenType.TEXT) { if (lexer.getState() == LexerState.STRING) { elements.add(new ElementString((String) token.getValue())); } else { //TEXT state addNode(new TextNode((String) token.getValue()), false); } } else if (token.getType() == TokenType.TAG_START) { lexer.setState(LexerState.TAG); tagName = getTagName(); elements.clear(); } else if (token.getType() == TokenType.TAG_END) { if (tagName.equals("FOR")) { try { addNode(new ForLoopNode(elements.toArray()), true); } catch (IllegalArgumentException ex) { throw new SmartScriptParserException(ex); } } else if (tagName.equals("=")) { addNode(new EchoNode(elements.toArray()), false); } lexer.setState(LexerState.TEXT); } else if (token.getType() == TokenType.SYMBOL) { if (isOperator((char) token.getValue())) { elements.add(new ElementOperator(token.getValue().toString())); } else if (token.getValue() == Character.valueOf('"')) { if (lexer.getState() == LexerState.STRING) { lexer.setState(LexerState.TAG); } else { lexer.setState(LexerState.STRING); } } else if (token.getValue() == Character.valueOf('@')) { elements.add(new ElementFunction(getFunctionName())); } else { throw new SmartScriptParserException("Invalid operator inside the tag. Was " + token.getValue().toString() + "."); } } else if (token.getType() == TokenType.VARIABLE) { elements.add(new ElementVariable((String) token.getValue())); } else if (token.getType() == TokenType.DOUBLE_NUMBER) { elements.add(new ElementConstantDouble(((Double) token.getValue()).doubleValue())); } else if (token.getType() == TokenType.INT_NUMBER) { elements.add(new ElementConstantInteger(((Integer) token.getValue()).intValue())); } } while (token.getType() != TokenType.EOF); if (lexer.getState() == LexerState.TAG) { throw new SmartScriptParserException("A tag wasn't closeed with $}. Invalid document."); } else if (lexer.getState() == LexerState.STRING) { throw new SmartScriptParserException( "A string inside tag wasn't closed. Invalid document."); } if (stack.size() != 1) { throw new SmartScriptParserException("A FOR tag wasn't matched with END tag."); } } /** * Returns function name if it's the next token of the lexer. * * @return function name * @throws SmartScriptParserException if the next token isn't valid function name */ private String getFunctionName() { Token token = getToken(); if (token.getType() == TokenType.VARIABLE) { return (String) token.getValue(); } throw new SmartScriptParserException( "After @ symbol must come valid function name. Instead it was " + token.getType().toString() + " \"" + token.getValue().toString() + "\"."); } /** * Returns tag name if it's the next token of the lexer. * * @return tag name * @throws SmartScriptParserException * if the next token isn't valid tag name or if the end tag is in * invalid position */ private String getTagName() { Token token = getToken(); if (token.getType() == TokenType.SYMBOL && token.getValue() == Character.valueOf('=') || token.getType() == TokenType.VARIABLE) { String tagNameTemp = token.getValue().toString().toUpperCase(); if (tagNameTemp.equals("FOR") || tagNameTemp.equals("=")) { return tagNameTemp; } if (tagNameTemp.equals("END")) { stack.pop(); if (stack.isEmpty()) { throw new SmartScriptParserException( "There are too many END tags, or they are on invalid positions."); } return tagNameTemp; } throw new SmartScriptParserException("Unknown tag name. Was " + tagNameTemp + "."); } throw new SmartScriptParserException("First element in a tag must be name of the tag."); } /** * Adds the given node as a child to the node currently on top of the stack. * Pushes new node on the stack if needed. * * @param newNode node to be added * @param pushToStack true if new node should be pushed on the stack */ private void addNode(Node newNode, boolean pushToStack) { ((Node) stack.peek()).addChildNode(newNode); if (pushToStack) { stack.push(newNode); } } /** * Checks if the given character is valid operator, i.e. if it is '+', '-', '/', * '^' or '*'. * * @param ch candidate character * @return true iff the given character is an operator. */ private boolean isOperator(char ch) { return "+-*/^".indexOf(ch) != -1; } }
UTF-8
Java
8,523
java
SmartScriptParser.java
Java
[ { "context": "arsed.\n * \n * @see SmartScriptLexer\n * \n * @author Bruno Iljazović\n */\npublic class SmartScriptParser {\n\n\t/** stakc ", "end": 2335, "score": 0.9998622536659241, "start": 2320, "tag": "NAME", "value": "Bruno Iljazović" } ]
null
[]
package hr.fer.zemris.java.custom.scripting.parser; import java.util.ArrayList; import java.util.List; import java.util.Stack; import hr.fer.zemris.java.custom.scripting.elems.ElementConstantDouble; import hr.fer.zemris.java.custom.scripting.elems.ElementConstantInteger; import hr.fer.zemris.java.custom.scripting.elems.ElementFunction; import hr.fer.zemris.java.custom.scripting.elems.ElementOperator; import hr.fer.zemris.java.custom.scripting.elems.ElementString; import hr.fer.zemris.java.custom.scripting.elems.ElementVariable; import hr.fer.zemris.java.custom.scripting.lexer.LexerException; import hr.fer.zemris.java.custom.scripting.lexer.LexerState; import hr.fer.zemris.java.custom.scripting.lexer.SmartScriptLexer; import hr.fer.zemris.java.custom.scripting.lexer.Token; import hr.fer.zemris.java.custom.scripting.lexer.TokenType; import hr.fer.zemris.java.custom.scripting.nodes.DocumentNode; import hr.fer.zemris.java.custom.scripting.nodes.EchoNode; import hr.fer.zemris.java.custom.scripting.nodes.ForLoopNode; import hr.fer.zemris.java.custom.scripting.nodes.Node; import hr.fer.zemris.java.custom.scripting.nodes.TextNode; /** * This class parses given text and makes tree-like structure with root in {@link #documentNode}. * It makes use of {@link SmartScriptLexer} to tokenize given text. * * <p> There are three possible nodes besides documentNode: EchoNode, ForLoopNode and TextNode. * ForLoopNode is generated when a tag named FOR is encountered. Then every Node till matching END * tag is added as a child of that ForLoopNode. * * <p>EchoNode is generated when a tag named = is encountered. * * <p>TextNode is generated from text outside of tags. * * Example text and tree this parser produces: * <pre>====================================================== * This is text. * {$ FOR i 1 2 $} * Inside for loop! * {$ = 1 "1.2" 1.2 * $}{$END$} * Outside! * ====================================================== * DocumentNode * |- TextNode (...) * |- ForLoopNode (i, 1, 2) * |- TextNode (...) * |- EchoNode (1, "1.2", 1.2, *) * |- TextNode (...) * ====================================================== </pre> * * Throws {@link SmartScriptParserException} if given text can't be parsed. * * @see SmartScriptLexer * * @author <NAME> */ public class SmartScriptParser { /** stakc of nodes */ private Stack<Object> stack; /** lexer used for tokenizing the input string */ private SmartScriptLexer lexer; /** The text that is parsed */ private String documentBody; /** Root of the structure of nodes */ private DocumentNode documentNode; /** * Instantiates a new smart script parser text given as String argument. * * @param documentBody the text to be parsed. */ public SmartScriptParser(String documentBody) { this.documentBody = documentBody; parse(); } /** * Gets the document node which contains information about whole tree structure. * * @return the document node */ public DocumentNode getDocumentNode() { return documentNode; } /** * Wrapper for {@link SmartScriptLexer#nextToken} method * @return next token * @throws SmartScriptParserException if a {@link LexerException} occurred */ private Token getToken() { try { return lexer.nextToken(); } catch(LexerException ex) { throw new SmartScriptParserException(ex); } } /** * Parses the text stored in {@link #documentBody}. Parser manages states of the lexer. * * * @throws SmartScriptParserException if the text can't be parsed. */ private void parse() { stack = new Stack<>(); documentNode = new DocumentNode(); stack.push(documentNode); lexer = new SmartScriptLexer(documentBody); lexer.setState(LexerState.TEXT); Token token; //array of Element-s for ForLoopNode and EchoNode List<Object> elements = new ArrayList<>(); String tagName = ""; do { token = getToken(); if (token.getType() == TokenType.TEXT) { if (lexer.getState() == LexerState.STRING) { elements.add(new ElementString((String) token.getValue())); } else { //TEXT state addNode(new TextNode((String) token.getValue()), false); } } else if (token.getType() == TokenType.TAG_START) { lexer.setState(LexerState.TAG); tagName = getTagName(); elements.clear(); } else if (token.getType() == TokenType.TAG_END) { if (tagName.equals("FOR")) { try { addNode(new ForLoopNode(elements.toArray()), true); } catch (IllegalArgumentException ex) { throw new SmartScriptParserException(ex); } } else if (tagName.equals("=")) { addNode(new EchoNode(elements.toArray()), false); } lexer.setState(LexerState.TEXT); } else if (token.getType() == TokenType.SYMBOL) { if (isOperator((char) token.getValue())) { elements.add(new ElementOperator(token.getValue().toString())); } else if (token.getValue() == Character.valueOf('"')) { if (lexer.getState() == LexerState.STRING) { lexer.setState(LexerState.TAG); } else { lexer.setState(LexerState.STRING); } } else if (token.getValue() == Character.valueOf('@')) { elements.add(new ElementFunction(getFunctionName())); } else { throw new SmartScriptParserException("Invalid operator inside the tag. Was " + token.getValue().toString() + "."); } } else if (token.getType() == TokenType.VARIABLE) { elements.add(new ElementVariable((String) token.getValue())); } else if (token.getType() == TokenType.DOUBLE_NUMBER) { elements.add(new ElementConstantDouble(((Double) token.getValue()).doubleValue())); } else if (token.getType() == TokenType.INT_NUMBER) { elements.add(new ElementConstantInteger(((Integer) token.getValue()).intValue())); } } while (token.getType() != TokenType.EOF); if (lexer.getState() == LexerState.TAG) { throw new SmartScriptParserException("A tag wasn't closeed with $}. Invalid document."); } else if (lexer.getState() == LexerState.STRING) { throw new SmartScriptParserException( "A string inside tag wasn't closed. Invalid document."); } if (stack.size() != 1) { throw new SmartScriptParserException("A FOR tag wasn't matched with END tag."); } } /** * Returns function name if it's the next token of the lexer. * * @return function name * @throws SmartScriptParserException if the next token isn't valid function name */ private String getFunctionName() { Token token = getToken(); if (token.getType() == TokenType.VARIABLE) { return (String) token.getValue(); } throw new SmartScriptParserException( "After @ symbol must come valid function name. Instead it was " + token.getType().toString() + " \"" + token.getValue().toString() + "\"."); } /** * Returns tag name if it's the next token of the lexer. * * @return tag name * @throws SmartScriptParserException * if the next token isn't valid tag name or if the end tag is in * invalid position */ private String getTagName() { Token token = getToken(); if (token.getType() == TokenType.SYMBOL && token.getValue() == Character.valueOf('=') || token.getType() == TokenType.VARIABLE) { String tagNameTemp = token.getValue().toString().toUpperCase(); if (tagNameTemp.equals("FOR") || tagNameTemp.equals("=")) { return tagNameTemp; } if (tagNameTemp.equals("END")) { stack.pop(); if (stack.isEmpty()) { throw new SmartScriptParserException( "There are too many END tags, or they are on invalid positions."); } return tagNameTemp; } throw new SmartScriptParserException("Unknown tag name. Was " + tagNameTemp + "."); } throw new SmartScriptParserException("First element in a tag must be name of the tag."); } /** * Adds the given node as a child to the node currently on top of the stack. * Pushes new node on the stack if needed. * * @param newNode node to be added * @param pushToStack true if new node should be pushed on the stack */ private void addNode(Node newNode, boolean pushToStack) { ((Node) stack.peek()).addChildNode(newNode); if (pushToStack) { stack.push(newNode); } } /** * Checks if the given character is valid operator, i.e. if it is '+', '-', '/', * '^' or '*'. * * @param ch candidate character * @return true iff the given character is an operator. */ private boolean isOperator(char ch) { return "+-*/^".indexOf(ch) != -1; } }
8,513
0.665923
0.664046
260
31.776922
26.991955
99
false
false
0
0
0
0
0
0
2.092308
false
false
15
8d880a9925d3725e03ca8bf6fe227b8c759a08b8
31,490,700,252,619
470291f3685d64e418c4bc478f35393ff6081e03
/app/src/main/java/com/tstl/kesouk/Fragments/Gift_Fragments.java
2f3242885f249c32e62ec4873c0eaaabdd7a1ef8
[]
no_license
LakshminPrasanna/kesouk-android-app
https://github.com/LakshminPrasanna/kesouk-android-app
1f9741ddfb05d6d7f414b2f219286a57394f437d
37d57eea95d7164799df13861e12c4c49149efa4
refs/heads/master
2020-03-25T17:04:30.738000
2018-05-02T12:24:11
2018-05-02T12:24:11
143,962,784
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tstl.kesouk.Fragments; /** * Created by user on 22-Feb-18. */ import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tstl.kesouk.R; public class Gift_Fragments extends Fragment { public Gift_Fragments() { // Required empty public constructor } public static Gift_Fragments newInstance(String param1, String param2) { Gift_Fragments fragment = new Gift_Fragments(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_gift, container, false); } }
UTF-8
Java
1,033
java
Gift_Fragments.java
Java
[ { "context": "kage com.tstl.kesouk.Fragments;\n\n/**\n * Created by user on 22-Feb-18.\n */\n\n\nimport android.os.Bundle;\nimp", "end": 58, "score": 0.7567992210388184, "start": 54, "tag": "USERNAME", "value": "user" } ]
null
[]
package com.tstl.kesouk.Fragments; /** * Created by user on 22-Feb-18. */ import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.tstl.kesouk.R; public class Gift_Fragments extends Fragment { public Gift_Fragments() { // Required empty public constructor } public static Gift_Fragments newInstance(String param1, String param2) { Gift_Fragments fragment = new Gift_Fragments(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_gift, container, false); } }
1,033
0.682478
0.675702
42
23.595238
23.214384
76
false
false
0
0
0
0
0
0
0.428571
false
false
15
10822f826ca2bfb3b3415e3775f86d61575b125a
10,402,410,858,841
9cd32d1dc69122899ae788b671d13298d8fa5d27
/src/main/java/ru/innopolis/homework11/InvokerDAOCourse.java
23ef637cb5ffc1b2477bf7d16911148bbd1d06dd
[]
no_license
RuslanBuryatia03/HomeWork
https://github.com/RuslanBuryatia03/HomeWork
409a59e0abebc972171037d43f4dea4929ec31d8
41bc0e73b20956d5a42f2de493228381572faa3e
refs/heads/master
2020-04-17T00:32:21.720000
2019-02-13T12:25:53
2019-02-13T12:25:53
166,053,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.innopolis.homework11; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.innopolis.homework11.dao.CourseDAO; import ru.innopolis.homework11.dao.CourseDAOImpl; import ru.innopolis.homework11.entity.Course; import ru.innopolis.homework11.entity.Person; import ru.innopolis.homework11.entity.Subject; import java.sql.Connection; import java.sql.SQLException; /** * Класс для работы с таблицей Course * через DAO * * @author KhankhasaevRV * @since 2019.02.06 */ public class InvokerDAOCourse { private final CourseDAO dao; private final Logger LOGGER = LoggerFactory.getLogger(InvokerDAOCourse.class); private final Connection connection; InvokerDAOCourse(Connection connection) { this.dao = new CourseDAOImpl(connection); this.connection = connection; } public void invokeCourseDemo() throws SQLException { InvokerDAOSubject invokerDAOSubject = new InvokerDAOSubject(connection); InvokerDAOPerson invokerDAOPerson = new InvokerDAOPerson(connection); LOGGER.trace("Запись в таблицу Course - одной записи Person соответствует несколько записей Subject"); linkToCourse( invokerDAOPerson.getPersonById(13).get(), invokerDAOSubject.getSubjectById(13).get(), invokerDAOSubject.getSubjectById(14).get()); LOGGER.trace("Вставлена запись в таблицу Course - одной записи Person соответствует несколько записей Subject"); LOGGER.trace("Запись в таблицу Course - одной записи Subject соответствует несколько записей Person"); linkToCourse( invokerDAOSubject.getSubjectById(15).get(), invokerDAOPerson.getPersonById(14).get(), invokerDAOPerson.getPersonById(15).get()); LOGGER.trace("Вставлена запись в таблицу Course - одной записи Subject соответствует несколько записей Person"); LOGGER.trace("Получение записи из таблицы Course"); Course course = getCourse(6, 7); System.out.println(course); } /** * Производит вставку записей в таблицу Course * * @param person объект, по которому необходимо сделать соответствие с массивом subject * @param subject массив, по которому необходимо сделать соответствие * @return количество вставленных записей в таблицу Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private int linkToCourse(Person person, Subject... subject) throws SQLException { return dao.linkToCourse(person, subject); } /** * Производит вставку записей в таблицу Course * * @param subject объект, по которому необходимо сделать соответствие с массивом person * @param person массив, по которому необходимо сделать соответствие * @return количество вставленных записей в таблицу Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private int linkToCourse(Subject subject, Person... person) throws SQLException { return dao.linkToCourse(subject, person); } /** * Возвращает объект Course по заданным person_id, subject_id * * @param person_id внешний ключ на таблицу Person * @param subject_id внешний ключ на таблицу Subject * @return объект Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private Course getCourse(int person_id, int subject_id) throws SQLException { return dao.getCourse(person_id, subject_id); } }
UTF-8
Java
4,331
java
InvokerDAOCourse.java
Java
[ { "context": "аботы с таблицей Course\n * через DAO\n *\n * @author KhankhasaevRV\n * @since 2019.02.06\n */\npublic class InvokerDA", "end": 467, "score": 0.6611429452896118, "start": 456, "tag": "NAME", "value": "Khankhasaev" }, { "context": "ицей Course\n * через DAO\n *\n * @auth...
null
[]
package ru.innopolis.homework11; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.innopolis.homework11.dao.CourseDAO; import ru.innopolis.homework11.dao.CourseDAOImpl; import ru.innopolis.homework11.entity.Course; import ru.innopolis.homework11.entity.Person; import ru.innopolis.homework11.entity.Subject; import java.sql.Connection; import java.sql.SQLException; /** * Класс для работы с таблицей Course * через DAO * * @author KhankhasaevRV * @since 2019.02.06 */ public class InvokerDAOCourse { private final CourseDAO dao; private final Logger LOGGER = LoggerFactory.getLogger(InvokerDAOCourse.class); private final Connection connection; InvokerDAOCourse(Connection connection) { this.dao = new CourseDAOImpl(connection); this.connection = connection; } public void invokeCourseDemo() throws SQLException { InvokerDAOSubject invokerDAOSubject = new InvokerDAOSubject(connection); InvokerDAOPerson invokerDAOPerson = new InvokerDAOPerson(connection); LOGGER.trace("Запись в таблицу Course - одной записи Person соответствует несколько записей Subject"); linkToCourse( invokerDAOPerson.getPersonById(13).get(), invokerDAOSubject.getSubjectById(13).get(), invokerDAOSubject.getSubjectById(14).get()); LOGGER.trace("Вставлена запись в таблицу Course - одной записи Person соответствует несколько записей Subject"); LOGGER.trace("Запись в таблицу Course - одной записи Subject соответствует несколько записей Person"); linkToCourse( invokerDAOSubject.getSubjectById(15).get(), invokerDAOPerson.getPersonById(14).get(), invokerDAOPerson.getPersonById(15).get()); LOGGER.trace("Вставлена запись в таблицу Course - одной записи Subject соответствует несколько записей Person"); LOGGER.trace("Получение записи из таблицы Course"); Course course = getCourse(6, 7); System.out.println(course); } /** * Производит вставку записей в таблицу Course * * @param person объект, по которому необходимо сделать соответствие с массивом subject * @param subject массив, по которому необходимо сделать соответствие * @return количество вставленных записей в таблицу Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private int linkToCourse(Person person, Subject... subject) throws SQLException { return dao.linkToCourse(person, subject); } /** * Производит вставку записей в таблицу Course * * @param subject объект, по которому необходимо сделать соответствие с массивом person * @param person массив, по которому необходимо сделать соответствие * @return количество вставленных записей в таблицу Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private int linkToCourse(Subject subject, Person... person) throws SQLException { return dao.linkToCourse(subject, person); } /** * Возвращает объект Course по заданным person_id, subject_id * * @param person_id внешний ключ на таблицу Person * @param subject_id внешний ключ на таблицу Subject * @return объект Course * @throws SQLException ошибка на уровне СУБД или другая ошибка */ private Course getCourse(int person_id, int subject_id) throws SQLException { return dao.getCourse(person_id, subject_id); } }
4,331
0.707627
0.697458
95
36.157894
32.318584
121
false
false
0
0
0
0
0
0
0.473684
false
false
15
698e9b81a80d58d08c3e7c02c6f2e203e8a2ebff
34,789,235,116,470
a591a8f85061dbe9d3275b8727d2e93416c0ea36
/engine/src/main/java/com/jfms/engine/service/biz/remote/api/OnlineMessageRepository.java
7b660298cb0489799ed34c1fef2676cc7a767e27
[]
no_license
mahbodkh/jfms
https://github.com/mahbodkh/jfms
4e1acf89dc0097523a61637e91c8f258fcf2f39b
dd23edf0954f2c0d7183c2350a2cda09aebaff7b
refs/heads/master
2020-03-18T11:53:23.175000
2018-05-21T04:23:37
2018-05-21T04:23:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jfms.engine.service.biz.remote.api; public interface OnlineMessageRepository<E> { void sendMessage(String channel, String message); void setMessageListener(E messageListener); }
UTF-8
Java
199
java
OnlineMessageRepository.java
Java
[]
null
[]
package com.jfms.engine.service.biz.remote.api; public interface OnlineMessageRepository<E> { void sendMessage(String channel, String message); void setMessageListener(E messageListener); }
199
0.788945
0.788945
6
32.166668
22.527143
53
false
false
0
0
0
0
0
0
0.666667
false
false
15
8c307688e8f1315b0637c357ab32d60e14a48dcb
1,795,296,398,606
6eca1a694633794bd6a93b76f83461290d717de8
/android/AliyunVideoCommon/src/main/java/com/aliyun/svideo/common/utils/LanguageUtils.java
8cdff70013100b17759ae12cb8955ae83efa68ed
[ "MIT" ]
permissive
aliyun/AliRTC-UserCase-VoiceCallSolution_1To1
https://github.com/aliyun/AliRTC-UserCase-VoiceCallSolution_1To1
d1d995562416eba84b694a06bd48f502a1871a44
467166c0f9d4ec620dd1928f00401502720a3de5
refs/heads/master
2023-03-13T00:58:33.645000
2020-12-04T06:46:25
2020-12-04T06:46:25
270,880,435
4
3
MIT
false
2022-06-17T03:13:29
2020-06-09T02:06:49
2020-12-08T08:14:14
2022-06-17T03:13:28
70,476
4
3
3
Java
false
false
package com.aliyun.svideo.common.utils; import android.content.Context; import android.util.Log; import java.util.Locale; /** * @author cross_ly DATE 2019/08/05 * <p>描述:系统语言工具类 */ public class LanguageUtils { private static final String TAG = "LanguageUtils"; /** * 判断当前语言是否是简体中文 * @return boolean */ public static boolean isCHEN(Context context) { Locale locale = context.getResources().getConfiguration().locale; //语言中文 boolean isZH = "zh".equals(locale.getLanguage().toLowerCase()); Log.d(TAG, "当前系统语言 : " + locale.getLanguage() + " ,当前地区 :" + locale.getCountry()); return isZH ; } }
UTF-8
Java
740
java
LanguageUtils.java
Java
[ { "context": "til.Log;\n\nimport java.util.Locale;\n\n/**\n * @author cross_ly DATE 2019/08/05\n * <p>描述:系统语言工具类\n */\npublic class", "end": 148, "score": 0.9995300769805908, "start": 140, "tag": "USERNAME", "value": "cross_ly" } ]
null
[]
package com.aliyun.svideo.common.utils; import android.content.Context; import android.util.Log; import java.util.Locale; /** * @author cross_ly DATE 2019/08/05 * <p>描述:系统语言工具类 */ public class LanguageUtils { private static final String TAG = "LanguageUtils"; /** * 判断当前语言是否是简体中文 * @return boolean */ public static boolean isCHEN(Context context) { Locale locale = context.getResources().getConfiguration().locale; //语言中文 boolean isZH = "zh".equals(locale.getLanguage().toLowerCase()); Log.d(TAG, "当前系统语言 : " + locale.getLanguage() + " ,当前地区 :" + locale.getCountry()); return isZH ; } }
740
0.642643
0.630631
27
23.666666
24.665165
90
false
false
0
0
0
0
0
0
0.407407
false
false
15
e81d7cff609e5ea085455ba56b85c38034fef6ae
4,415,226,449,893
bb45ca5f028b841ca0a08ffef60cedc40090f2c1
/app/src/main/java/hlx/ui/itemadapter/resource/SubjectListAdapter.java
890bf4e78891867d3058d6a52ca47bb8cea220ae
[]
no_license
tik5213/myWorldBox
https://github.com/tik5213/myWorldBox
0d248bcc13e23de5a58efd5c10abca4596f4e442
b0bde3017211cc10584b93e81cf8d3f929bc0a45
refs/heads/master
2020-04-12T19:52:17.559000
2017-08-14T05:49:03
2017-08-14T05:49:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hlx.ui.itemadapter.resource; import android.content.Context; import android.support.v4.util.SparseArrayCompat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.MCWorld.framework.R; import com.MCWorld.framework.base.image.PaintView; import com.MCWorld.framework.base.log.HLog; import com.MCWorld.framework.base.utils.UtilsFunction; import com.MCWorld.r; import com.MCWorld.t; import com.simple.colorful.b; import com.simple.colorful.d; import com.simple.colorful.setter.j; import java.util.ArrayList; import java.util.List; public class SubjectListAdapter extends BaseAdapter implements b { private static final SparseArrayCompat<String> bYK = new SparseArrayCompat(); private static final SparseArrayCompat<String> bYL = new SparseArrayCompat(); private boolean aTm = true; private List<hlx.module.resources.d.a> aab = new ArrayList(); private int axr; private Context context; private LayoutInflater mInflater; public static class a { PaintView bYN; TextView bYO; LinearLayout bYP; } public List<hlx.module.resources.d.a> getData() { return this.aab; } public void setDayMode(boolean dayMode) { this.aTm = dayMode; } static { bYK.put(1, "map_subject"); bYK.put(2, "js_subject"); bYK.put(3, "skin_subject"); bYK.put(4, "wood_subject"); bYL.put(1, hlx.data.tongji.a.bMw); bYL.put(2, hlx.data.tongji.a.bMx); bYL.put(3, hlx.data.tongji.a.bMz); bYL.put(4, hlx.data.tongji.a.bMy); } public SubjectListAdapter(Context context, int resType) { this.mInflater = LayoutInflater.from(context); this.context = context; this.axr = resType; this.aTm = d.isDayMode(); } public void c(List<hlx.module.resources.d.a> data, boolean clear) { if (clear) { this.aab.clear(); } this.aab.addAll(data); notifyDataSetChanged(); } public void HA() { this.aab.clear(); notifyDataSetChanged(); } public int getCount() { return this.aab == null ? 0 : this.aab.size(); } public Object getItem(int position) { return Integer.valueOf(position); } public long getItemId(int position) { return (long) position; } public void a(j setter) { setter.bf(R.id.root_view, R.attr.tabBackground).bg(R.id.guide_line_image, R.attr.guideLine).bh(R.id.topic_title, R.attr.tabText).bf(R.id.top_dividing_line, R.attr.dividingLine).bf(R.id.interval_block, R.attr.home_interval_bg).bf(R.id.bottom_dividing_line, R.attr.dividingLine); } public View getView(final int position, View convertView, ViewGroup parent) { a holder; if (convertView == null) { convertView = this.mInflater.inflate(R.layout.map_item_subject, parent, false); holder = new a(); holder.bYN = (PaintView) convertView.findViewById(R.id.topic_item_image); holder.bYO = (TextView) convertView.findViewById(R.id.topic_title); holder.bYP = (LinearLayout) convertView.findViewById(R.id.root_view); convertView.setTag(holder); } else { holder = (a) convertView.getTag(); } t.b(holder.bYN, ((hlx.module.resources.d.a) this.aab.get(position)).icon, 0.0f); holder.bYO.setText(((hlx.module.resources.d.a) this.aab.get(position)).name); holder.bYP.setOnClickListener(new OnClickListener(this) { final /* synthetic */ SubjectListAdapter bYM; public void onClick(View v) { hlx.module.resources.d.a item = (hlx.module.resources.d.a) this.bYM.aab.get(position); String className = (String) SubjectListAdapter.bYK.get(this.bYM.axr); String tongjiEvent = (String) SubjectListAdapter.bYL.get(this.bYM.axr); if (!UtilsFunction.empty(className)) { r.ck().K_umengEvent(tongjiEvent + String.valueOf(item.id)); HLog.verbose(toString(), tongjiEvent + String.valueOf(item.id), new Object[0]); com.MCWorld.ui.mctool.d.b(this.bYM.context, className, item.id, item.name); } } }); return convertView; } }
UTF-8
Java
4,500
java
SubjectListAdapter.java
Java
[]
null
[]
package hlx.ui.itemadapter.resource; import android.content.Context; import android.support.v4.util.SparseArrayCompat; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.MCWorld.framework.R; import com.MCWorld.framework.base.image.PaintView; import com.MCWorld.framework.base.log.HLog; import com.MCWorld.framework.base.utils.UtilsFunction; import com.MCWorld.r; import com.MCWorld.t; import com.simple.colorful.b; import com.simple.colorful.d; import com.simple.colorful.setter.j; import java.util.ArrayList; import java.util.List; public class SubjectListAdapter extends BaseAdapter implements b { private static final SparseArrayCompat<String> bYK = new SparseArrayCompat(); private static final SparseArrayCompat<String> bYL = new SparseArrayCompat(); private boolean aTm = true; private List<hlx.module.resources.d.a> aab = new ArrayList(); private int axr; private Context context; private LayoutInflater mInflater; public static class a { PaintView bYN; TextView bYO; LinearLayout bYP; } public List<hlx.module.resources.d.a> getData() { return this.aab; } public void setDayMode(boolean dayMode) { this.aTm = dayMode; } static { bYK.put(1, "map_subject"); bYK.put(2, "js_subject"); bYK.put(3, "skin_subject"); bYK.put(4, "wood_subject"); bYL.put(1, hlx.data.tongji.a.bMw); bYL.put(2, hlx.data.tongji.a.bMx); bYL.put(3, hlx.data.tongji.a.bMz); bYL.put(4, hlx.data.tongji.a.bMy); } public SubjectListAdapter(Context context, int resType) { this.mInflater = LayoutInflater.from(context); this.context = context; this.axr = resType; this.aTm = d.isDayMode(); } public void c(List<hlx.module.resources.d.a> data, boolean clear) { if (clear) { this.aab.clear(); } this.aab.addAll(data); notifyDataSetChanged(); } public void HA() { this.aab.clear(); notifyDataSetChanged(); } public int getCount() { return this.aab == null ? 0 : this.aab.size(); } public Object getItem(int position) { return Integer.valueOf(position); } public long getItemId(int position) { return (long) position; } public void a(j setter) { setter.bf(R.id.root_view, R.attr.tabBackground).bg(R.id.guide_line_image, R.attr.guideLine).bh(R.id.topic_title, R.attr.tabText).bf(R.id.top_dividing_line, R.attr.dividingLine).bf(R.id.interval_block, R.attr.home_interval_bg).bf(R.id.bottom_dividing_line, R.attr.dividingLine); } public View getView(final int position, View convertView, ViewGroup parent) { a holder; if (convertView == null) { convertView = this.mInflater.inflate(R.layout.map_item_subject, parent, false); holder = new a(); holder.bYN = (PaintView) convertView.findViewById(R.id.topic_item_image); holder.bYO = (TextView) convertView.findViewById(R.id.topic_title); holder.bYP = (LinearLayout) convertView.findViewById(R.id.root_view); convertView.setTag(holder); } else { holder = (a) convertView.getTag(); } t.b(holder.bYN, ((hlx.module.resources.d.a) this.aab.get(position)).icon, 0.0f); holder.bYO.setText(((hlx.module.resources.d.a) this.aab.get(position)).name); holder.bYP.setOnClickListener(new OnClickListener(this) { final /* synthetic */ SubjectListAdapter bYM; public void onClick(View v) { hlx.module.resources.d.a item = (hlx.module.resources.d.a) this.bYM.aab.get(position); String className = (String) SubjectListAdapter.bYK.get(this.bYM.axr); String tongjiEvent = (String) SubjectListAdapter.bYL.get(this.bYM.axr); if (!UtilsFunction.empty(className)) { r.ck().K_umengEvent(tongjiEvent + String.valueOf(item.id)); HLog.verbose(toString(), tongjiEvent + String.valueOf(item.id), new Object[0]); com.MCWorld.ui.mctool.d.b(this.bYM.context, className, item.id, item.name); } } }); return convertView; } }
4,500
0.643778
0.640889
124
35.290321
34.582481
285
false
false
0
0
0
0
0
0
0.806452
false
false
15
b59c39c79c5e4a1385b78b4d8a360f4d4f1e3141
28,578,712,432,327
fb1ac88109373ff29330f21b7175fa21f4eb07a6
/src/main/java/com/klm/travel_casestudy/metrics/MetrixController.java
8dd7b53a7140288de2f43e420ac81f2d7222ae89
[]
no_license
santhoshaSiddagangappa/klm_casestudy
https://github.com/santhoshaSiddagangappa/klm_casestudy
46e1d5107a938b4391c9dc4caef1917cc060bc66
2de85c3582930b604496410abd14d21997c9555d
refs/heads/main
2023-04-25T02:14:34.516000
2021-05-17T04:26:26
2021-05-17T04:26:26
368,052,844
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.klm.travel_casestudy.metrics; import com.klm.travel_casestudy.Service.MetricService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.metrics.MetricsEndpoint; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.*; @RestController @Slf4j @RequestMapping("/metrics") public class MetrixController { @Autowired MetricsEndpoint metricsEndpoint; @Autowired MetricService metricService; Map<String, Integer> statusCounter = new HashMap<>(); @GetMapping("/total/requests") public MetricsRespones ggetData() { MetricsRespones metricsRespones = new MetricsRespones(); log.info("under matrixxxx"); MetricsEndpoint.MetricResponse metric = getMatricWithoutTag(); if (metric == null) return metricsRespones; List<MetricsEndpoint.Sample> measurements = metric.getMeasurements(); Map<String, Double> map = new LinkedHashMap<>(); for (MetricsEndpoint.Sample measurement : measurements) { map.put(measurement.getStatistic().toString(), measurement.getValue()); } metricsRespones.setTotalNumberOfRequests(map.get("COUNT")); metricsRespones.setMaxResTime(map.get("MAX")); metricsRespones.setAvgResTime(map.get("TOTAL_TIME")); metricsRespones.setTotalNumberOfOKRes(getData(2)); metricsRespones.setTotalNumberOf5XXRes(getData(5)); metricsRespones.setTotalNumberOf4XXRes(getData(4)); return metricsRespones; } private MetricsEndpoint.MetricResponse getMatricWithoutTag() { return metricsEndpoint.metric("http.server.requests", null); } private MetricsEndpoint.MetricResponse getMatricWithTag(String tag) { return metricsEndpoint.metric("http.server.requests", Arrays.asList(tag)); } private Integer getData(Integer status) { return metricService.getStatusMetric().getOrDefault(status.toString().charAt(0), 0); } }
UTF-8
Java
2,242
java
MetrixController.java
Java
[]
null
[]
package com.klm.travel_casestudy.metrics; import com.klm.travel_casestudy.Service.MetricService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.metrics.MetricsEndpoint; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.*; @RestController @Slf4j @RequestMapping("/metrics") public class MetrixController { @Autowired MetricsEndpoint metricsEndpoint; @Autowired MetricService metricService; Map<String, Integer> statusCounter = new HashMap<>(); @GetMapping("/total/requests") public MetricsRespones ggetData() { MetricsRespones metricsRespones = new MetricsRespones(); log.info("under matrixxxx"); MetricsEndpoint.MetricResponse metric = getMatricWithoutTag(); if (metric == null) return metricsRespones; List<MetricsEndpoint.Sample> measurements = metric.getMeasurements(); Map<String, Double> map = new LinkedHashMap<>(); for (MetricsEndpoint.Sample measurement : measurements) { map.put(measurement.getStatistic().toString(), measurement.getValue()); } metricsRespones.setTotalNumberOfRequests(map.get("COUNT")); metricsRespones.setMaxResTime(map.get("MAX")); metricsRespones.setAvgResTime(map.get("TOTAL_TIME")); metricsRespones.setTotalNumberOfOKRes(getData(2)); metricsRespones.setTotalNumberOf5XXRes(getData(5)); metricsRespones.setTotalNumberOf4XXRes(getData(4)); return metricsRespones; } private MetricsEndpoint.MetricResponse getMatricWithoutTag() { return metricsEndpoint.metric("http.server.requests", null); } private MetricsEndpoint.MetricResponse getMatricWithTag(String tag) { return metricsEndpoint.metric("http.server.requests", Arrays.asList(tag)); } private Integer getData(Integer status) { return metricService.getStatusMetric().getOrDefault(status.toString().charAt(0), 0); } }
2,242
0.71008
0.70562
62
34.161289
28.345901
92
false
false
0
0
0
0
0
0
0.564516
false
false
15
a0988882424974227e6b1f10aec55ed3c9baa6ad
25,091,199,004,880
d6f69903b321fda53c1f6b046dc6f54c5a041242
/src/library/entities/Column.java
61e6e58d8f8765b4ef3c85f684cdc6b9d988f5d1
[]
no_license
JulieC35/Projet
https://github.com/JulieC35/Projet
a9e008b5aefeaf9d61a433b3e8cff8857021ed9f
52ace53f7eb2acdd348fcb789a601234a521cffe
refs/heads/master
2020-06-01T12:27:35.275000
2017-06-27T22:11:47
2017-06-27T22:11:47
94,073,890
0
0
null
false
2017-06-27T22:11:48
2017-06-12T08:38:02
2017-06-12T08:43:00
2017-06-27T22:11:48
344
0
0
0
Java
null
null
/** * A MySQL database table attribute.<br> * A Column object have several attributes meant to describe it in a SQL way : a name, a type and also several * boolean indicators : primary, unique, notNull and autoIncrement<br> * Besides accessors, a Column can be converted into an SQL attribute declaration<br><br> */ package library.entities; import lang.*; public class Column{ private String name, type; private boolean primary, unique, notNull, autoIncrement; /** * The constructor of the class * @param name the name of the column * @param type the type of the column * @param primary true if this is a primary key * @param unique true if this attribute is unique * @param notNull true if this attribute should not be null * @param autoIncrement true if the attribute has auto increment */ public Column(String name, String type, boolean primary, boolean unique, boolean notNull, boolean autoIncrement){ this.name = ( name != null ) ? name : "n/a"; this.type = ( type != null ) ? type : "n/a"; this.primary = primary; this.unique = unique; this.notNull = notNull; this.autoIncrement = autoIncrement; } /** * The constructor of the class */ public Column(){ this.name = "n/a"; this.type = "n/a"; this.primary = false; this.unique = false; this.notNull = false; this.autoIncrement = false; } /** * @return the name of the column */ public String getName(){ return this.name; } /** * @return the type of the column */ public String getType(){ return this.type; } /** * @return true if the column is a primary key */ public boolean isPrimary(){ return this.primary; } /** * @return true if the column is unique */ public boolean isUnique(){ return this.unique; } /** * @return true if the column is not null */ public boolean isNotNull(){ return this.notNull; } /** * @return true if the column has auto increment set on */ public boolean hasAutoIncrement(){ return this.autoIncrement; } /** * @param name the new name of the column. Should not be null or empty * @return true if the name is valid */ public boolean setName(String name){ boolean ret = false; if(name != null && !name.equals("")){ this.name = name; ret = true; } return ret; } /** * @param type the new type of the column. Should not be null or empty * @return true is the type is valid */ public boolean setType(String type){ boolean ret = false; if(type != null && !type.equals("")){ this.type = type; ret = true; } return ret; } /** * @param primary true if the column is a primary key */ public void setPrimary(boolean primary){ this.primary = primary; } /** * @param unique true if the column is unique */ public void setUnique(boolean unique){ this.unique = unique; } /** * @param notNull true if the column is not null */ public void setNotNull(boolean notNull){ this.notNull = notNull; } /** * @param autoI true if the column has auto increment */ public void setAutoIncrement(boolean autoI){ this.autoIncrement = autoI; } /** * Returns the column as a MySQL declaration.<br> * Intended to be used in a table-creation context.<br><br> * Example :<br> * Column col = new Column("id", "INT(11)", true, false, true, true);<br> * System.out.println(col.toSQL());<br><br> * * Result :<br> * `id` INT(11) NOT NULL AUTOINCREMENT, <br> * PRIMARY KEY (`id`) * @return The SQL declaration of the column */ public String toSQL(){ StringBuilder sb = new StringBuilder(); sb.append("`" + this.name + "` " + this.type); if ( this.primary ){ sb.append(" NOT NULL"); if ( this.autoIncrement ) sb.append(" AUTO_INCREMENT"); sb.append(",\nPRIMARY KEY (`" + this.name + "`)"); } else { if ( this.unique && this.notNull) { sb.append(" NOT NULL"); sb.append(",\nUNIQUE (`" + this.name + "`)"); // UNIQUE `uqUserEmail` (`email`) } else if ( this.unique ) sb.append(",\nUNIQUE (`" + this.name + "`)"); else if ( this.notNull ) sb.append(" NOT NULL"); } return sb.toString(); } }
UTF-8
Java
4,134
java
Column.java
Java
[]
null
[]
/** * A MySQL database table attribute.<br> * A Column object have several attributes meant to describe it in a SQL way : a name, a type and also several * boolean indicators : primary, unique, notNull and autoIncrement<br> * Besides accessors, a Column can be converted into an SQL attribute declaration<br><br> */ package library.entities; import lang.*; public class Column{ private String name, type; private boolean primary, unique, notNull, autoIncrement; /** * The constructor of the class * @param name the name of the column * @param type the type of the column * @param primary true if this is a primary key * @param unique true if this attribute is unique * @param notNull true if this attribute should not be null * @param autoIncrement true if the attribute has auto increment */ public Column(String name, String type, boolean primary, boolean unique, boolean notNull, boolean autoIncrement){ this.name = ( name != null ) ? name : "n/a"; this.type = ( type != null ) ? type : "n/a"; this.primary = primary; this.unique = unique; this.notNull = notNull; this.autoIncrement = autoIncrement; } /** * The constructor of the class */ public Column(){ this.name = "n/a"; this.type = "n/a"; this.primary = false; this.unique = false; this.notNull = false; this.autoIncrement = false; } /** * @return the name of the column */ public String getName(){ return this.name; } /** * @return the type of the column */ public String getType(){ return this.type; } /** * @return true if the column is a primary key */ public boolean isPrimary(){ return this.primary; } /** * @return true if the column is unique */ public boolean isUnique(){ return this.unique; } /** * @return true if the column is not null */ public boolean isNotNull(){ return this.notNull; } /** * @return true if the column has auto increment set on */ public boolean hasAutoIncrement(){ return this.autoIncrement; } /** * @param name the new name of the column. Should not be null or empty * @return true if the name is valid */ public boolean setName(String name){ boolean ret = false; if(name != null && !name.equals("")){ this.name = name; ret = true; } return ret; } /** * @param type the new type of the column. Should not be null or empty * @return true is the type is valid */ public boolean setType(String type){ boolean ret = false; if(type != null && !type.equals("")){ this.type = type; ret = true; } return ret; } /** * @param primary true if the column is a primary key */ public void setPrimary(boolean primary){ this.primary = primary; } /** * @param unique true if the column is unique */ public void setUnique(boolean unique){ this.unique = unique; } /** * @param notNull true if the column is not null */ public void setNotNull(boolean notNull){ this.notNull = notNull; } /** * @param autoI true if the column has auto increment */ public void setAutoIncrement(boolean autoI){ this.autoIncrement = autoI; } /** * Returns the column as a MySQL declaration.<br> * Intended to be used in a table-creation context.<br><br> * Example :<br> * Column col = new Column("id", "INT(11)", true, false, true, true);<br> * System.out.println(col.toSQL());<br><br> * * Result :<br> * `id` INT(11) NOT NULL AUTOINCREMENT, <br> * PRIMARY KEY (`id`) * @return The SQL declaration of the column */ public String toSQL(){ StringBuilder sb = new StringBuilder(); sb.append("`" + this.name + "` " + this.type); if ( this.primary ){ sb.append(" NOT NULL"); if ( this.autoIncrement ) sb.append(" AUTO_INCREMENT"); sb.append(",\nPRIMARY KEY (`" + this.name + "`)"); } else { if ( this.unique && this.notNull) { sb.append(" NOT NULL"); sb.append(",\nUNIQUE (`" + this.name + "`)"); // UNIQUE `uqUserEmail` (`email`) } else if ( this.unique ) sb.append(",\nUNIQUE (`" + this.name + "`)"); else if ( this.notNull ) sb.append(" NOT NULL"); } return sb.toString(); } }
4,134
0.642235
0.641268
181
21.845304
21.942122
114
false
false
0
0
0
0
0
0
1.640884
false
false
15
7e248bb1210dce3759d60df966ae0c2e625936c3
36,764,920,059,612
22d8632330f0ef8104c1fd991c36ff766e6f6215
/app/src/main/java/genius/gyulhap/UnderscoreView.java
c37b2781e24e2560d6d2daa27b81b6470609ca18
[]
no_license
EdThe/Find-Set-Match
https://github.com/EdThe/Find-Set-Match
7a95775aa20e7de3eeb632ff77f33318034dcec7
efcb04a6ddf23eb025631a91f1cfa5fb86bd3ce1
refs/heads/master
2021-09-14T00:35:41.619000
2018-05-06T19:13:18
2018-05-06T19:13:18
118,970,200
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//This view class is used to show the underscored numbers of chosen cells in-game package genius.gyulhap; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class UnderscoreView extends View { public boolean p1; public int num; public UnderscoreView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public UnderscoreView(Context context) { super(context); } public UnderscoreView(UnderscoreView uView){ super(uView.getContext()); } public void onDraw(Canvas canvas){ super.onDraw(canvas); //This is the underscore Rect under = new Rect(15,this.getHeight() - 8,this.getWidth() - 15,this.getHeight()); Paint p = new Paint(Color.BLACK); if(p1) p.setColor(getResources().getColor(R.color.colorPrimary)); else p.setColor(getResources().getColor(R.color.colorAccent)); canvas.drawRect(under, p); if(num != 0){ //This draws the number that is chosen. Since 0 can't be chosen, it is used to specify when not to show the number Paint text = new Paint(Color.BLACK); if(p1) text.setColor(getResources().getColor(R.color.colorPrimary)); else text.setColor(getResources().getColor(R.color.colorAccent)); text.setTextSize(55); canvas.drawText(String.valueOf(num),this.getWidth()/2-14,this.getHeight() - 16,text); } } //Sets the number the text will show public void setNum(int num){ this.num = num; invalidate(); requestLayout(); } //Sets the player the view will show, that specifies which color is used public void setP1Turn(boolean p1){ this.p1 = p1; invalidate(); requestLayout(); } }
UTF-8
Java
2,067
java
UnderscoreView.java
Java
[]
null
[]
//This view class is used to show the underscored numbers of chosen cells in-game package genius.gyulhap; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class UnderscoreView extends View { public boolean p1; public int num; public UnderscoreView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public UnderscoreView(Context context) { super(context); } public UnderscoreView(UnderscoreView uView){ super(uView.getContext()); } public void onDraw(Canvas canvas){ super.onDraw(canvas); //This is the underscore Rect under = new Rect(15,this.getHeight() - 8,this.getWidth() - 15,this.getHeight()); Paint p = new Paint(Color.BLACK); if(p1) p.setColor(getResources().getColor(R.color.colorPrimary)); else p.setColor(getResources().getColor(R.color.colorAccent)); canvas.drawRect(under, p); if(num != 0){ //This draws the number that is chosen. Since 0 can't be chosen, it is used to specify when not to show the number Paint text = new Paint(Color.BLACK); if(p1) text.setColor(getResources().getColor(R.color.colorPrimary)); else text.setColor(getResources().getColor(R.color.colorAccent)); text.setTextSize(55); canvas.drawText(String.valueOf(num),this.getWidth()/2-14,this.getHeight() - 16,text); } } //Sets the number the text will show public void setNum(int num){ this.num = num; invalidate(); requestLayout(); } //Sets the player the view will show, that specifies which color is used public void setP1Turn(boolean p1){ this.p1 = p1; invalidate(); requestLayout(); } }
2,067
0.640058
0.629898
71
28.112677
27.397209
126
false
false
0
0
0
0
0
0
0.591549
false
false
15
f3d0a41579990a377f93b3ff6a36f49981d0e480
37,641,093,392,230
92b9c1ea13a5b98049762e058953ddc1966c8c9b
/src/test/java/com/upgenix/step_definitions/LoginPageStepDefinitions.java
9e59a7b2642fe4c242ec6d9eaa2261b7a9d28f46
[]
no_license
Yesimyc/UpGenix
https://github.com/Yesimyc/UpGenix
8652b4c3a50d47046484698ab19f19e1be3fdbfd
3f30a2cbd7e7ff210b0ca07925d5165c972b79b1
refs/heads/master
2021-06-13T23:25:42.847000
2021-04-25T17:26:43
2021-04-25T17:26:43
254,463,236
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.upgenix.step_definitions; import com.upgenix.pages.BasePage; import com.upgenix.pages.DiscussPage; import com.upgenix.pages.LoginPage; import com.upgenix.utilities.BrowserUtils; import com.upgenix.utilities.ConfigurationReader; import com.upgenix.utilities.Driver; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.junit.Assert; import org.openqa.selenium.WebDriver; import java.util.Map; import java.util.concurrent.TimeUnit; public class LoginPageStepDefinitions { LoginPage loginPage=new LoginPage(); BasePage basePage = new BasePage(); DiscussPage discussPage = new DiscussPage(); private WebDriver driver; @Given("user is on the landing page") public void user_is_on_the_landing_page() { System.out.println("I am on the landing page"); Driver.get().get(ConfigurationReader.getProperty("url")); } @Then("user clicks login button") public void user_clicks_login_button() { BrowserUtils.wait(6); // driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS); loginPage.loginModule.click(); } @Then("user verifies that {string} link displayed") public void user_verifies_that_link_displayed(String string) { Assert.assertEquals("Best solution for startups",basePage.pageTitle.getText()); System.out.println(basePage.pageTitle.getText()); System.out.println("Best solution for startups"); } @When("user logs in as eventscrmmanager") public void user_logs_in_as_eventscrmmanager() { String username = ConfigurationReader.getProperty("eventscrm.manager.username"); String password = ConfigurationReader.getProperty("eventscrm.manager.password"); loginPage.login(username,password); System.out.println("user logs in as eventscrmmanager"); } @When("user verifies that {string} page subtitle is displayed") public void user_verifies_that_page_subtitle_is_displayed(String string) { BrowserUtils.wait(3); // driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS); Assert.assertEquals("#Inbox",discussPage.inboxText.getText()); System.out.println(discussPage.inboxText.getText()); System.out.println("#Inbox"); } @When("user enters {string} username and {string} password") public void user_enters_username_and_password(String string, String string2) { // driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); loginPage.login(string,string2); } @When("user verifies that {string} message is displayed") public void user_verifies_that_message_is_displayed(String string) { System.out.println(loginPage.errorMessage.getText()); System.out.println(string); Assert.assertEquals(string, loginPage.errorMessage.getText()); } @When("user logs in as eventscrmmanager with following credentials") public void user_logs_in_as_eventscrmmanager_with_following_credentials(Map<String, String> dataTable) { System.out.println(dataTable); loginPage.login(dataTable.get("username"), dataTable.get("password")); } @When("user logs in as {string}") public void userLogsInAs(String role) { BrowserUtils.wait(6); //driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); loginPage.login(role); } } // public static void main(String[] args) { //// ExcelUtil qa2 = new ExcelUtil("vytrack_testusers.xlsx", "QA2-short"); //// System.out.println("Row count: " + qa2.rowCount()); //// System.out.println(qa2.getColumnsNames()); //// //map is a data structure //// //in map, every value is referenced by key //// //when we retrieve data from map, we don't specify index, we specify key name //// //keys must be unique //// //keys are represented by column names //// //like in properties file key=value //// for (Map<String, String> map : qa2.getDataList()) { //// System.out.println(map.get("username")); //// } //// }
UTF-8
Java
4,133
java
LoginPageStepDefinitions.java
Java
[ { "context": "()) {\n//// System.out.println(map.get(\"username\"));\n//// }\n//// }", "end": 4105, "score": 0.9994229078292847, "start": 4097, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.upgenix.step_definitions; import com.upgenix.pages.BasePage; import com.upgenix.pages.DiscussPage; import com.upgenix.pages.LoginPage; import com.upgenix.utilities.BrowserUtils; import com.upgenix.utilities.ConfigurationReader; import com.upgenix.utilities.Driver; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.junit.Assert; import org.openqa.selenium.WebDriver; import java.util.Map; import java.util.concurrent.TimeUnit; public class LoginPageStepDefinitions { LoginPage loginPage=new LoginPage(); BasePage basePage = new BasePage(); DiscussPage discussPage = new DiscussPage(); private WebDriver driver; @Given("user is on the landing page") public void user_is_on_the_landing_page() { System.out.println("I am on the landing page"); Driver.get().get(ConfigurationReader.getProperty("url")); } @Then("user clicks login button") public void user_clicks_login_button() { BrowserUtils.wait(6); // driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS); loginPage.loginModule.click(); } @Then("user verifies that {string} link displayed") public void user_verifies_that_link_displayed(String string) { Assert.assertEquals("Best solution for startups",basePage.pageTitle.getText()); System.out.println(basePage.pageTitle.getText()); System.out.println("Best solution for startups"); } @When("user logs in as eventscrmmanager") public void user_logs_in_as_eventscrmmanager() { String username = ConfigurationReader.getProperty("eventscrm.manager.username"); String password = ConfigurationReader.getProperty("eventscrm.manager.password"); loginPage.login(username,password); System.out.println("user logs in as eventscrmmanager"); } @When("user verifies that {string} page subtitle is displayed") public void user_verifies_that_page_subtitle_is_displayed(String string) { BrowserUtils.wait(3); // driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS); Assert.assertEquals("#Inbox",discussPage.inboxText.getText()); System.out.println(discussPage.inboxText.getText()); System.out.println("#Inbox"); } @When("user enters {string} username and {string} password") public void user_enters_username_and_password(String string, String string2) { // driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); loginPage.login(string,string2); } @When("user verifies that {string} message is displayed") public void user_verifies_that_message_is_displayed(String string) { System.out.println(loginPage.errorMessage.getText()); System.out.println(string); Assert.assertEquals(string, loginPage.errorMessage.getText()); } @When("user logs in as eventscrmmanager with following credentials") public void user_logs_in_as_eventscrmmanager_with_following_credentials(Map<String, String> dataTable) { System.out.println(dataTable); loginPage.login(dataTable.get("username"), dataTable.get("password")); } @When("user logs in as {string}") public void userLogsInAs(String role) { BrowserUtils.wait(6); //driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); loginPage.login(role); } } // public static void main(String[] args) { //// ExcelUtil qa2 = new ExcelUtil("vytrack_testusers.xlsx", "QA2-short"); //// System.out.println("Row count: " + qa2.rowCount()); //// System.out.println(qa2.getColumnsNames()); //// //map is a data structure //// //in map, every value is referenced by key //// //when we retrieve data from map, we don't specify index, we specify key name //// //keys must be unique //// //keys are represented by column names //// //like in properties file key=value //// for (Map<String, String> map : qa2.getDataList()) { //// System.out.println(map.get("username")); //// } //// }
4,133
0.682797
0.67941
111
36.243244
27.937902
108
false
false
0
0
0
0
0
0
0.594595
false
false
15
2f65f2c3b9bc8f5c08fe8b84f67cede10c430ebf
17,222,818,899,647
48b20bd740207eccccd10bd48d58bea98d61d0c1
/src/states/EndState.java
9c0758ed6e6eab2a047852a6063ad5eecf413459
[]
no_license
Mackbellemore/FireEscape
https://github.com/Mackbellemore/FireEscape
310323cb5f16d82a476faaa3546cdb49fa156049
955af425b3cf5d93d387b095b32048e8d0eceee4
refs/heads/master
2020-03-28T09:34:26.572000
2018-09-09T16:50:08
2018-09-09T16:50:08
148,044,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package states; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import firstgame.Handler; import firstgame.KeyManager; public class EndState extends State{ protected KeyEvent kv; protected KeyManager keymanager; private String[] options = {"Restart", "Quit"}; private int currentSelection = 0; public EndState(Handler handler) { super(handler); } @Override public void tick() { keyPressed(); } @Override public void render(Graphics g) { for(int i = 0; i<options.length; i++) { if(i==currentSelection) { g.setColor(Color.GREEN); } else { g.setColor(Color.BLACK); } g.setFont(new Font("Arial", Font.PLAIN, 40)); g.drawString(options[i], handler.getWidth()/2 - 150, 150 + i*75); } } public void keyPressed() { if(handler.getKeyManager().keyJustPressed(kv.VK_DOWN)){ currentSelection++; if(currentSelection >= options.length) { currentSelection = 0; } } else if(handler.getKeyManager().keyJustPressed(kv.VK_UP)) { currentSelection--; if(currentSelection < 0) { currentSelection = options.length - 1; } } if(handler.getKeyManager().enter) { if(currentSelection == 0) { handler.getGame().stop(); } else if(currentSelection == 1) { System.exit(1); } } } public void keyReleased() { handler.getKeyManager().down = false; handler.getKeyManager().down = false; } }
UTF-8
Java
1,528
java
EndState.java
Java
[]
null
[]
package states; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import firstgame.Handler; import firstgame.KeyManager; public class EndState extends State{ protected KeyEvent kv; protected KeyManager keymanager; private String[] options = {"Restart", "Quit"}; private int currentSelection = 0; public EndState(Handler handler) { super(handler); } @Override public void tick() { keyPressed(); } @Override public void render(Graphics g) { for(int i = 0; i<options.length; i++) { if(i==currentSelection) { g.setColor(Color.GREEN); } else { g.setColor(Color.BLACK); } g.setFont(new Font("Arial", Font.PLAIN, 40)); g.drawString(options[i], handler.getWidth()/2 - 150, 150 + i*75); } } public void keyPressed() { if(handler.getKeyManager().keyJustPressed(kv.VK_DOWN)){ currentSelection++; if(currentSelection >= options.length) { currentSelection = 0; } } else if(handler.getKeyManager().keyJustPressed(kv.VK_UP)) { currentSelection--; if(currentSelection < 0) { currentSelection = options.length - 1; } } if(handler.getKeyManager().enter) { if(currentSelection == 0) { handler.getGame().stop(); } else if(currentSelection == 1) { System.exit(1); } } } public void keyReleased() { handler.getKeyManager().down = false; handler.getKeyManager().down = false; } }
1,528
0.627618
0.615183
71
19.521128
17.067272
68
false
false
0
0
0
0
0
0
2.352113
false
false
15
635087dd362116e69fcc2adc0e58ca38603e94a6
20,349,555,083,943
a64b68f112e2b75b38dbaab6f5ee77ce53bf2168
/sgp-dao-hbxml/src/test/java/com/premize/sgp/dao/pruebas/SgpTipoPrioridadDaoTest.java
2a5aa42694db0ea2c5243d533506b8979f9d9132
[]
no_license
edtiko/Java-Bootstrap
https://github.com/edtiko/Java-Bootstrap
13b4a8b87abc7b516dba9db160ffb273fffd9e6a
23fd3cf5ad8ddc44da6c2f3d48be922738b43220
refs/heads/master
2021-01-02T08:30:19.068000
2017-08-01T15:12:12
2017-08-01T15:12:12
99,013,503
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.premize.sgp.dao.pruebas; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.premize.pmz.api.exception.AppBaseException; import com.premize.sgp.dao.gestion.pruebas.TipoPrioridadDao; import com.premize.sgp.dto.pruebas.TipoPrioridadDTO; import com.premize.sgp.utils.LogUtil; /** * @author <a href="mailto:jhona.filigrana@premize.com">Jhon Alexander Filigrana Cardona</a> * @project sgp-dao-hbxml * @class SgpTipoPrioridadDaoTest * @description * @date 15/07/2014 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/META-INF/spring/applicationContext-map.xml" }) public class SgpTipoPrioridadDaoTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private TipoPrioridadDao tipoPrioridadDao; /** * * @author <a href="mailto:jhona.filigrana@premize.com">Jhon Alexander Filigrana Cardona</a> * @date 15/07/2014 * @description */ @Test public void consultarPrioridadPorTipoHallazgo() { Integer idTipoHallazgo = 5; try { List<TipoPrioridadDTO> result = tipoPrioridadDao.consultarPrioridadPorTipoHallazgo(idTipoHallazgo); Assert.assertNotNull(result); } catch (AppBaseException ex) { LogUtil.log(getClass(), Level.ERROR, ex.getMessage(), ex); fail(ex.getMessage()); } } }
UTF-8
Java
1,859
java
SgpTipoPrioridadDaoTest.java
Java
[ { "context": "gp.utils.LogUtil;\n\n/**\n * @author <a href=\"mailto:jhona.filigrana@premize.com\">Jhon Alexander Filigrana Cardona</a>\n * @project", "end": 859, "score": 0.9999300241470337, "start": 832, "tag": "EMAIL", "value": "jhona.filigrana@premize.com" }, { "context": "thor <a...
null
[]
package com.premize.sgp.dao.pruebas; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.premize.pmz.api.exception.AppBaseException; import com.premize.sgp.dao.gestion.pruebas.TipoPrioridadDao; import com.premize.sgp.dto.pruebas.TipoPrioridadDTO; import com.premize.sgp.utils.LogUtil; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * @project sgp-dao-hbxml * @class SgpTipoPrioridadDaoTest * @description * @date 15/07/2014 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/META-INF/spring/applicationContext-map.xml" }) public class SgpTipoPrioridadDaoTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private TipoPrioridadDao tipoPrioridadDao; /** * * @author <a href="mailto:<EMAIL>"><NAME></a> * @date 15/07/2014 * @description */ @Test public void consultarPrioridadPorTipoHallazgo() { Integer idTipoHallazgo = 5; try { List<TipoPrioridadDTO> result = tipoPrioridadDao.consultarPrioridadPorTipoHallazgo(idTipoHallazgo); Assert.assertNotNull(result); } catch (AppBaseException ex) { LogUtil.log(getClass(), Level.ERROR, ex.getMessage(), ex); fail(ex.getMessage()); } } }
1,767
0.760624
0.747714
57
31.614035
28.907448
105
false
false
0
0
0
0
0
0
0.77193
false
false
15
7ebbb06d07e52be1dfd281bf9a939d9a1e8a6ac9
34,196,529,621,816
2c65c53ef5390bd70fd2ddb9bbc2b19027f2479f
/kangaroo-rong360/src/main/java/io/github/pactstart/rong360/push/bean/RepaymentCodeVerifyResultBean.java
eb204d5d6232219422c8f3526144731832b88925
[]
no_license
zt6220493/kangaroo
https://github.com/zt6220493/kangaroo
f37cdaa815708fb56e33d8f4ed7d83885551011a
16c8a9f7589ec33f01559d3308f8dd8e49493afe
refs/heads/master
2022-12-28T04:50:48.186000
2019-09-25T10:40:27
2019-09-25T10:40:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.pactstart.rong360.push.bean; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @Data public class RepaymentCodeVerifyResultBean { /** * need_verify_code : 1 */ private int need_verify_code; }
UTF-8
Java
255
java
RepaymentCodeVerifyResultBean.java
Java
[ { "context": "package io.github.pactstart.rong360.push.bean;\n\nimport lombok.Data;\nimport lo", "end": 27, "score": 0.9706071019172668, "start": 18, "tag": "USERNAME", "value": "pactstart" } ]
null
[]
package io.github.pactstart.rong360.push.bean; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @Data public class RepaymentCodeVerifyResultBean { /** * need_verify_code : 1 */ private int need_verify_code; }
255
0.721569
0.705882
16
14.9375
16.071981
46
false
false
0
0
0
0
0
0
0.25
false
false
15
3634e83bf26c7be54bc32c3f0612ea95151c7cd2
24,146,306,171,002
bf6f639b302e6338e5121d7cb994cddd32ac38d5
/elevatorDesign/src/elevator/system/ElevatorSystem.java
3c90a6eb453b5403bb40a200911c48e830d7483c
[]
no_license
MERGHOOB/ObjectOrientDesigns
https://github.com/MERGHOOB/ObjectOrientDesigns
952b9aeace0a764d288f8876faab55c40c3cc084
4f7a42d4fbf881e2f0111330e7aa6300c7944cff
refs/heads/master
2020-06-17T21:40:31.695000
2019-07-10T06:41:24
2019-07-10T06:41:24
196,064,736
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package elevator.system; import elevator.system.classes.Elevator; import elevator.system.enums.Direction; import elevator.system.exceptions.OverWeightException; import elevator.system.ifaces.IElevatorSystem; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ElevatorSystem implements IElevatorSystem { int numberOfFloor; List<Elevator> elevatorsAvailable = new ArrayList<>(); public ElevatorSystem(int numberOfFloor) { this.numberOfFloor = numberOfFloor; } @Override public Elevator allocateElevator(Direction up) { //find minimum distance elevator, in which direction you are and if not fulled already and is Avaliable return elevatorsAvailable.get(new Random().nextInt(elevatorsAvailable.size()-1)); } @Override public boolean getIn(Elevator elevator) throws OverWeightException { if(elevator.isOverWeight()) { throw new OverWeightException("overweightException"); } elevator.evaluateWeight(); return true; } @Override public boolean out(Elevator elevator) { elevator.evaluateWeight(); return true; } }
UTF-8
Java
1,195
java
ElevatorSystem.java
Java
[]
null
[]
package elevator.system; import elevator.system.classes.Elevator; import elevator.system.enums.Direction; import elevator.system.exceptions.OverWeightException; import elevator.system.ifaces.IElevatorSystem; import java.util.ArrayList; import java.util.List; import java.util.Random; public class ElevatorSystem implements IElevatorSystem { int numberOfFloor; List<Elevator> elevatorsAvailable = new ArrayList<>(); public ElevatorSystem(int numberOfFloor) { this.numberOfFloor = numberOfFloor; } @Override public Elevator allocateElevator(Direction up) { //find minimum distance elevator, in which direction you are and if not fulled already and is Avaliable return elevatorsAvailable.get(new Random().nextInt(elevatorsAvailable.size()-1)); } @Override public boolean getIn(Elevator elevator) throws OverWeightException { if(elevator.isOverWeight()) { throw new OverWeightException("overweightException"); } elevator.evaluateWeight(); return true; } @Override public boolean out(Elevator elevator) { elevator.evaluateWeight(); return true; } }
1,195
0.713808
0.712971
48
23.895834
26.391476
111
false
false
0
0
0
0
0
0
0.375
false
false
15
4536a1da95f5fecf168c8d7943c41fa90b1641a0
27,599,459,892,764
88a3b3f9aa8f2d4f3dcdad01a0706ed39588f500
/src/main/java/com/example/rabbitmq/web/SendMessageController.java
689077ea71517905788382abf85b4c00120fe09d
[]
no_license
gaojin1568/rabbitmqDemo
https://github.com/gaojin1568/rabbitmqDemo
028bd9d741ec3fd4d20c072b041d613eabe6af58
50503ebcdc6da4f8e1125e9c75b596fd1b9fdfb9
refs/heads/master
2020-03-25T17:44:21.080000
2019-04-14T08:39:33
2019-04-14T08:39:33
143,992,991
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rabbitmq.web; import com.example.rabbitmq.entity.Page; import com.example.rabbitmq.entity.User; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 以发送请求的方式测试 * @author gaojin */ @RestController public class SendMessageController { @Autowired private RabbitTemplate rabbitTemplate; /** * http://localhost:8080/sendQ?message=aaa * @param message */ @RequestMapping("/sendQ") public String sendMQto(String message) { int i = 1; rabbitTemplate.convertAndSend("directexchange","orange", message); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); return "SUCCESS"; } /** * 测试direct * http://localhost:8080/sendQ2?message=bbb * @param message */ @RequestMapping("/sendQ2") public String sendMQ2to(String message) { rabbitTemplate.convertAndSend("directexchange","green", message); return "SUCCESS"; } /** * 测试类 * http://localhost:8080/send/user */ @RequestMapping("/send/user") public String sendUser() { User user = new User(); Page page = new Page(); page.setPageNum(1); page.setPageName("san"); page.setPageSize("2"); user.setPage(page); user.setId(1); user.setUsername("yanggm"); user.setPassword("123456"); rabbitTemplate.convertAndSend("directexchange","bean", user); return "SUCCESS"; } /** * 测试topic * http://localhost:8080/send/topicTest */ @RequestMapping("/send/topicTest") public String sendTopic() { this.rabbitTemplate.convertAndSend("topicexchange", "t.fee", "green"); this.rabbitTemplate.convertAndSend("topicexchange", "t.www", "fee"); return "SUCCESS"; } /** * 测试Fanout * http://localhost:8080/send/fanoutTest?message=高兴 */ @RequestMapping("/send/fanoutTest") public String send(String message) { this.rabbitTemplate.convertAndSend("fanoutExchange","", message); return "SUCCESS"; } }
UTF-8
Java
2,584
java
SendMessageController.java
Java
[ { "context": "tion.RestController;\n\n/**\n * 以发送请求的方式测试\n * @author gaojin\n */\n@RestController\npublic class SendMessageContr", "end": 402, "score": 0.9996216893196106, "start": 396, "tag": "USERNAME", "value": "gaojin" }, { "context": "\n user.setId(1);\n user.setUs...
null
[]
package com.example.rabbitmq.web; import com.example.rabbitmq.entity.Page; import com.example.rabbitmq.entity.User; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 以发送请求的方式测试 * @author gaojin */ @RestController public class SendMessageController { @Autowired private RabbitTemplate rabbitTemplate; /** * http://localhost:8080/sendQ?message=aaa * @param message */ @RequestMapping("/sendQ") public String sendMQto(String message) { int i = 1; rabbitTemplate.convertAndSend("directexchange","orange", message); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); rabbitTemplate.convertAndSend("directexchange","orange", message + i++); return "SUCCESS"; } /** * 测试direct * http://localhost:8080/sendQ2?message=bbb * @param message */ @RequestMapping("/sendQ2") public String sendMQ2to(String message) { rabbitTemplate.convertAndSend("directexchange","green", message); return "SUCCESS"; } /** * 测试类 * http://localhost:8080/send/user */ @RequestMapping("/send/user") public String sendUser() { User user = new User(); Page page = new Page(); page.setPageNum(1); page.setPageName("san"); page.setPageSize("2"); user.setPage(page); user.setId(1); user.setUsername("yanggm"); user.setPassword("<PASSWORD>"); rabbitTemplate.convertAndSend("directexchange","bean", user); return "SUCCESS"; } /** * 测试topic * http://localhost:8080/send/topicTest */ @RequestMapping("/send/topicTest") public String sendTopic() { this.rabbitTemplate.convertAndSend("topicexchange", "t.fee", "green"); this.rabbitTemplate.convertAndSend("topicexchange", "t.www", "fee"); return "SUCCESS"; } /** * 测试Fanout * http://localhost:8080/send/fanoutTest?message=高兴 */ @RequestMapping("/send/fanoutTest") public String send(String message) { this.rabbitTemplate.convertAndSend("fanoutExchange","", message); return "SUCCESS"; } }
2,588
0.647522
0.63454
86
28.569767
23.920673
80
false
false
0
0
0
0
0
0
0.616279
false
false
15
fcf99aab0477b6849561b1d5797e88d9d1848df0
35,665,408,449,424
cd219a7acea9495fa782a5dd3a1351653e8167ee
/app/src/main/java/com/jdcasas/kachuelo/vista/DialogKachuelo.java
a1e23c9eeac0748c9a60e131f758b52648c8ddbe
[]
no_license
jdcasasmoviles/Kachuelo
https://github.com/jdcasasmoviles/Kachuelo
d2fc88279c21f47217683bea22ac6351684e70c2
b393fa509ff4a6f32c247d9e9fda6db123b988b6
refs/heads/master
2020-07-06T06:07:34.720000
2019-08-17T18:22:41
2019-08-17T18:22:41
202,917,284
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jdcasas.kachuelo.vista; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.support.annotation.RequiresApi; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.jdcasas.kachuelo.BuscarEmpleo; import com.jdcasas.kachuelo.PublicarEmpleo; import com.jdcasas.kachuelo.R; import com.jdcasas.kachuelo.RegistrarseOficio; import com.jdcasas.kachuelo.controlaador.BackTaskLogin; import com.jdcasas.kachuelo.controlaador.GeolocalizarCercaTi; import com.jdcasas.kachuelo.controlaador.SpinnerLoad; import com.jdcasas.kachuelo.modelo.BaseDatos; import java.util.ArrayList; public class DialogKachuelo { Context context; private String latitud=""; private String longitud=""; private String opcion=""; ArrayAdapter<String> adaptersp; Spinner sp_general; ArrayList<String> listItems; BaseDatos civiltopia = new BaseDatos(); public DialogKachuelo(Context context){ this.context=context; } public void cargarDialogo(String mensaje){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setIcon( R.drawable.ic_menu_white_24dp); builder.create().show(); } public void cargarModosBuscar(String mensaje){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Empresa", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(context, BuscarEmpleo.class); intent.putExtra("opcion","Empresa"); context.startActivity(intent); dialog.cancel(); } }); builder.setNegativeButton("EMPLEO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //SPINNER DEPARTAMENTO o oficios sp_general=new Spinner(context); listItems = new ArrayList<>(); adaptersp = new ArrayAdapter<String>(context, R.layout.spinner_departamentos_layout, R.id.txtspdepartamentos, listItems); sp_general.setAdapter(adaptersp); setOpcion( "Empleo" ); listarOpciones("BuscarEmpleo",sp_general,listItems,adaptersp,"Departamentos :","regions","name"); dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @SuppressLint("ResourceType") public void cargarDialogoRedes(){ LinearLayout layoutInputv1 = new LinearLayout(context); layoutInputv1.setOrientation(LinearLayout.VERTICAL); HorizontalScrollView sv_horizontal=new HorizontalScrollView(context); LinearLayout layoutInputh1 = new LinearLayout(context); layoutInputh1.setOrientation(LinearLayout.HORIZONTAL); LinearLayout layoutInputvimb1 = new LinearLayout(context); layoutInputvimb1.setOrientation(LinearLayout.VERTICAL); LinearLayout layoutInputvimb2 = new LinearLayout(context); layoutInputvimb2.setOrientation(LinearLayout.VERTICAL); LinearLayout layoutInputvimb3 = new LinearLayout(context); layoutInputvimb3.setOrientation(LinearLayout.VERTICAL); //ImageButton FACEBOOK final ImageButton imb_facebook = new ImageButton(context); imb_facebook.setImageDrawable(context.getResources().getDrawable(R.drawable.facebook)); imb_facebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "https://www.facebook.com/groups/423666934321196/about/"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData( Uri.parse(url)); context.startActivity(intent); } }); //ImageButton TWITTER final ImageButton imb_twitter = new ImageButton(context); imb_twitter.setImageDrawable(context.getResources().getDrawable(R.drawable.twitter)); imb_twitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "imb_twitter", Toast.LENGTH_SHORT).show(); } }); //ImageButton GMAIL final ImageButton imb_gmail = new ImageButton(context); imb_gmail.setImageDrawable(context.getResources().getDrawable(R.drawable.gmail)); imb_gmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", context.getResources().getString(R.string.mail),null)); intent.putExtra(Intent.EXTRA_SUBJECT,context.getResources().getString(R.string.subject)); context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.envio))); } }); final TextView tv_1 = new TextView(context); final TextView tv_2 = new TextView(context); final TextView tv_3 = new TextView(context); tv_1.setTextSize(13); tv_2.setTextSize(13); tv_3.setTextSize(13); tv_1.setText("Facebook"); tv_2.setText("Twitter"); tv_3.setText("Gmail"); tv_1.setGravity( Gravity.CENTER_HORIZONTAL); tv_2.setGravity( Gravity.CENTER_HORIZONTAL); tv_3.setGravity( Gravity.CENTER_HORIZONTAL); tv_1.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); tv_2.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); tv_3.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); layoutInputvimb1.addView( imb_facebook); layoutInputvimb1.addView(tv_1); layoutInputvimb2.addView( imb_twitter); layoutInputvimb2.addView(tv_2); layoutInputvimb3.addView( imb_gmail); layoutInputvimb3.addView(tv_3); layoutInputh1.addView(layoutInputvimb1); layoutInputh1.addView(layoutInputvimb2); layoutInputh1.addView(layoutInputvimb3); sv_horizontal.addView( layoutInputh1); layoutInputv1.addView( sv_horizontal); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(layoutInputv1); builder.setTitle("INFO") .setMessage("") .setPositiveButton("Cancelar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } public void listarOpciones(final String actividad, final Spinner sp_general,final ArrayList<String> listItems,final ArrayAdapter<String> adaptersp, String titulo, final String tabla, final String campo){ LinearLayout layoutInput = new LinearLayout(context); layoutInput.setOrientation(LinearLayout.VERTICAL); //TEXTVIEW TITULO final TextView tvTitulo = new TextView(context); tvTitulo.setTextSize(13); tvTitulo.setText("\n\t"+titulo); layoutInput.addView(tvTitulo); ////SPINNER SpinnerLoad cargarOpciones=new SpinnerLoad(listItems,adaptersp,context); cargarOpciones.loadSpinner(civiltopia.spOpciones(tabla,campo)); // SPINNER VACIAR PARA USAR NUEVO if(sp_general.getParent() != null) { ((ViewGroup)sp_general.getParent()).removeView(sp_general); } layoutInput.addView(sp_general); AlertDialog.Builder builderEditBiodata = new AlertDialog.Builder(context); builderEditBiodata.setIcon(R.drawable.ic_menu_white_24dp); builderEditBiodata.setTitle("OPCIONES"); builderEditBiodata.setView(layoutInput); builderEditBiodata.setPositiveButton("ACEPTAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = null; if (actividad.equals("GPSKachuelo")) { GeolocalizarCercaTi geolocalizarCercaTi = null; if(getOpcion().equals( "Publico"))geolocalizarCercaTi=new GeolocalizarCercaTi(context,"usuarios_kachuelo","oficio",latitud,longitud,sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); else if(getOpcion().equals( "Empresa"))geolocalizarCercaTi=new GeolocalizarCercaTi(context,"usuarios_empresa","oficio",latitud,longitud,sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); geolocalizarCercaTi.execute(); } else if (actividad.equals("GPSUsuarios")) { setOpcion(sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); System.out.println("GPSEmpleadosUsuarios"+sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); if(getOpcion().equals( "Publico")){ System.out.println("PUBLICOOOOO"); listarOpciones("GPSKachuelo",sp_general,listItems,adaptersp,"Oficios :","spinner_oficio","oficio"); } else if(getOpcion().equals( "Empresa")){ System.out.println("EMPRESAAA"); listarOpciones("GPSKachuelo",sp_general,listItems,adaptersp,"Rugros :","spinner_rugro","rugro"); } } else if (actividad.equals("BuscarEmpleo")) { intent = new Intent(context, BuscarEmpleo.class); intent.putExtra("opcion", getOpcion()); intent.putExtra("valorsp", sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); context.startActivity(intent); } else{ if (actividad.equals("Registrarse")) intent = new Intent(context, RegistrarseOficio.class); else if (actividad.equals("PublicarEmpleo")) intent = new Intent(context, PublicarEmpleo.class); intent.putExtra("valorsp", sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); context.startActivity(intent); } } }); builderEditBiodata.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builderEditBiodata.show(); } public void cargarModoUsuario(String mensaje, final String usuario, final String password){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Empresa", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BackTaskLogin conexlogin=new BackTaskLogin(context,"usuarios_empresa",usuario,password); conexlogin.execute(); dialog.cancel(); } }); builder.setNegativeButton("Publico", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BackTaskLogin conexlogin=new BackTaskLogin(context,"usuarios_kachuelo",usuario,password); conexlogin.execute(); dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } public String getLatitud() { return latitud; } public void setLatitud(String latitud) { this.latitud = latitud; } public String getLongitud() { return longitud; } public void setLongitud(String longitud) { this.longitud = longitud; } public String getOpcion() { return opcion; } public void setOpcion(String opcion) { this.opcion = opcion; } }
UTF-8
Java
13,791
java
DialogKachuelo.java
Java
[ { "context": "ckTaskLogin conexlogin=new BackTaskLogin(context,\"usuarios_kachuelo\",usuario,password);\n conexlogin.ex", "end": 13131, "score": 0.9259921908378601, "start": 13114, "tag": "USERNAME", "value": "usuarios_kachuelo" } ]
null
[]
package com.jdcasas.kachuelo.vista; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.net.Uri; import android.os.Build; import android.support.annotation.RequiresApi; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.jdcasas.kachuelo.BuscarEmpleo; import com.jdcasas.kachuelo.PublicarEmpleo; import com.jdcasas.kachuelo.R; import com.jdcasas.kachuelo.RegistrarseOficio; import com.jdcasas.kachuelo.controlaador.BackTaskLogin; import com.jdcasas.kachuelo.controlaador.GeolocalizarCercaTi; import com.jdcasas.kachuelo.controlaador.SpinnerLoad; import com.jdcasas.kachuelo.modelo.BaseDatos; import java.util.ArrayList; public class DialogKachuelo { Context context; private String latitud=""; private String longitud=""; private String opcion=""; ArrayAdapter<String> adaptersp; Spinner sp_general; ArrayList<String> listItems; BaseDatos civiltopia = new BaseDatos(); public DialogKachuelo(Context context){ this.context=context; } public void cargarDialogo(String mensaje){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setIcon( R.drawable.ic_menu_white_24dp); builder.create().show(); } public void cargarModosBuscar(String mensaje){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Empresa", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(context, BuscarEmpleo.class); intent.putExtra("opcion","Empresa"); context.startActivity(intent); dialog.cancel(); } }); builder.setNegativeButton("EMPLEO", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //SPINNER DEPARTAMENTO o oficios sp_general=new Spinner(context); listItems = new ArrayList<>(); adaptersp = new ArrayAdapter<String>(context, R.layout.spinner_departamentos_layout, R.id.txtspdepartamentos, listItems); sp_general.setAdapter(adaptersp); setOpcion( "Empleo" ); listarOpciones("BuscarEmpleo",sp_general,listItems,adaptersp,"Departamentos :","regions","name"); dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @SuppressLint("ResourceType") public void cargarDialogoRedes(){ LinearLayout layoutInputv1 = new LinearLayout(context); layoutInputv1.setOrientation(LinearLayout.VERTICAL); HorizontalScrollView sv_horizontal=new HorizontalScrollView(context); LinearLayout layoutInputh1 = new LinearLayout(context); layoutInputh1.setOrientation(LinearLayout.HORIZONTAL); LinearLayout layoutInputvimb1 = new LinearLayout(context); layoutInputvimb1.setOrientation(LinearLayout.VERTICAL); LinearLayout layoutInputvimb2 = new LinearLayout(context); layoutInputvimb2.setOrientation(LinearLayout.VERTICAL); LinearLayout layoutInputvimb3 = new LinearLayout(context); layoutInputvimb3.setOrientation(LinearLayout.VERTICAL); //ImageButton FACEBOOK final ImageButton imb_facebook = new ImageButton(context); imb_facebook.setImageDrawable(context.getResources().getDrawable(R.drawable.facebook)); imb_facebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = "https://www.facebook.com/groups/423666934321196/about/"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData( Uri.parse(url)); context.startActivity(intent); } }); //ImageButton TWITTER final ImageButton imb_twitter = new ImageButton(context); imb_twitter.setImageDrawable(context.getResources().getDrawable(R.drawable.twitter)); imb_twitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "imb_twitter", Toast.LENGTH_SHORT).show(); } }); //ImageButton GMAIL final ImageButton imb_gmail = new ImageButton(context); imb_gmail.setImageDrawable(context.getResources().getDrawable(R.drawable.gmail)); imb_gmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", context.getResources().getString(R.string.mail),null)); intent.putExtra(Intent.EXTRA_SUBJECT,context.getResources().getString(R.string.subject)); context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.envio))); } }); final TextView tv_1 = new TextView(context); final TextView tv_2 = new TextView(context); final TextView tv_3 = new TextView(context); tv_1.setTextSize(13); tv_2.setTextSize(13); tv_3.setTextSize(13); tv_1.setText("Facebook"); tv_2.setText("Twitter"); tv_3.setText("Gmail"); tv_1.setGravity( Gravity.CENTER_HORIZONTAL); tv_2.setGravity( Gravity.CENTER_HORIZONTAL); tv_3.setGravity( Gravity.CENTER_HORIZONTAL); tv_1.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); tv_2.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); tv_3.setTypeface( Typeface.defaultFromStyle( Typeface.BOLD ) ); layoutInputvimb1.addView( imb_facebook); layoutInputvimb1.addView(tv_1); layoutInputvimb2.addView( imb_twitter); layoutInputvimb2.addView(tv_2); layoutInputvimb3.addView( imb_gmail); layoutInputvimb3.addView(tv_3); layoutInputh1.addView(layoutInputvimb1); layoutInputh1.addView(layoutInputvimb2); layoutInputh1.addView(layoutInputvimb3); sv_horizontal.addView( layoutInputh1); layoutInputv1.addView( sv_horizontal); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(layoutInputv1); builder.setTitle("INFO") .setMessage("") .setPositiveButton("Cancelar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } public void listarOpciones(final String actividad, final Spinner sp_general,final ArrayList<String> listItems,final ArrayAdapter<String> adaptersp, String titulo, final String tabla, final String campo){ LinearLayout layoutInput = new LinearLayout(context); layoutInput.setOrientation(LinearLayout.VERTICAL); //TEXTVIEW TITULO final TextView tvTitulo = new TextView(context); tvTitulo.setTextSize(13); tvTitulo.setText("\n\t"+titulo); layoutInput.addView(tvTitulo); ////SPINNER SpinnerLoad cargarOpciones=new SpinnerLoad(listItems,adaptersp,context); cargarOpciones.loadSpinner(civiltopia.spOpciones(tabla,campo)); // SPINNER VACIAR PARA USAR NUEVO if(sp_general.getParent() != null) { ((ViewGroup)sp_general.getParent()).removeView(sp_general); } layoutInput.addView(sp_general); AlertDialog.Builder builderEditBiodata = new AlertDialog.Builder(context); builderEditBiodata.setIcon(R.drawable.ic_menu_white_24dp); builderEditBiodata.setTitle("OPCIONES"); builderEditBiodata.setView(layoutInput); builderEditBiodata.setPositiveButton("ACEPTAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = null; if (actividad.equals("GPSKachuelo")) { GeolocalizarCercaTi geolocalizarCercaTi = null; if(getOpcion().equals( "Publico"))geolocalizarCercaTi=new GeolocalizarCercaTi(context,"usuarios_kachuelo","oficio",latitud,longitud,sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); else if(getOpcion().equals( "Empresa"))geolocalizarCercaTi=new GeolocalizarCercaTi(context,"usuarios_empresa","oficio",latitud,longitud,sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); geolocalizarCercaTi.execute(); } else if (actividad.equals("GPSUsuarios")) { setOpcion(sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); System.out.println("GPSEmpleadosUsuarios"+sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); if(getOpcion().equals( "Publico")){ System.out.println("PUBLICOOOOO"); listarOpciones("GPSKachuelo",sp_general,listItems,adaptersp,"Oficios :","spinner_oficio","oficio"); } else if(getOpcion().equals( "Empresa")){ System.out.println("EMPRESAAA"); listarOpciones("GPSKachuelo",sp_general,listItems,adaptersp,"Rugros :","spinner_rugro","rugro"); } } else if (actividad.equals("BuscarEmpleo")) { intent = new Intent(context, BuscarEmpleo.class); intent.putExtra("opcion", getOpcion()); intent.putExtra("valorsp", sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); context.startActivity(intent); } else{ if (actividad.equals("Registrarse")) intent = new Intent(context, RegistrarseOficio.class); else if (actividad.equals("PublicarEmpleo")) intent = new Intent(context, PublicarEmpleo.class); intent.putExtra("valorsp", sp_general.getItemAtPosition(sp_general.getSelectedItemPosition()).toString()); context.startActivity(intent); } } }); builderEditBiodata.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builderEditBiodata.show(); } public void cargarModoUsuario(String mensaje, final String usuario, final String password){ final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("INFO") .setMessage(mensaje) .setPositiveButton("Empresa", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BackTaskLogin conexlogin=new BackTaskLogin(context,"usuarios_empresa",usuario,password); conexlogin.execute(); dialog.cancel(); } }); builder.setNegativeButton("Publico", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BackTaskLogin conexlogin=new BackTaskLogin(context,"usuarios_kachuelo",usuario,password); conexlogin.execute(); dialog.cancel(); } }); builder.setIcon(R.drawable.ic_menu_white_24dp); builder.create().show(); } public String getLatitud() { return latitud; } public void setLatitud(String latitud) { this.latitud = latitud; } public String getLongitud() { return longitud; } public void setLongitud(String longitud) { this.longitud = longitud; } public String getOpcion() { return opcion; } public void setOpcion(String opcion) { this.opcion = opcion; } }
13,791
0.622943
0.617432
296
45.591217
33.672386
232
false
false
0
0
0
0
0
0
0.851351
false
false
15
31de952abdbb0bc30a5908e9e50777f9b9bf9bff
21,792,664,117,281
dfd2d9de3a126cae855ad7bcc37dccf60849fb70
/src/Vues/FenetreFournisseur.java
633d3f47d66d728d8b10fd04e97211dbe56e7d65
[]
no_license
Restes-au-bord/restes-au-bord
https://github.com/Restes-au-bord/restes-au-bord
833a5c4db751130927461e409aec76a7804830d7
031553a6988fafee502deaf3fc370e93ab988a03
refs/heads/master
2016-08-12T14:00:14.415000
2016-04-20T18:56:23
2016-04-20T18:56:23
54,050,994
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Vues; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextPane; import Model.Fournisseur; import Model.InformationsResto; import commandes.ArticleCommande; import commandes.Commande; import java.text.DecimalFormat; public class FenetreFournisseur extends JPanel { private FenetrePrincipale fp; private InformationsResto infoResto; private Commande commandeStockEnCours; private Commande commandeEquipementEnCours; private JTextPane txtFactureStock; private JTextPane txtFactureEquipements; private JButton btnPasserCommande; private JButton btnAjouterEquipement; private JButton btnModifierStock; private JLabel lblFacture; private JComboBox cmbChoixFournisseurEquipement; private JComboBox cmbChoixFournisseurStock; private JLabel lblNewLabel_2; private JLabel lblNewLabel_1; private JLabel lblNewLabel; private JButton btnSortir; public FenetreFournisseur(InformationsResto ir, FenetrePrincipale fp) { setLayout(null); infoResto = ir; this.fp = fp; commandeStockEnCours = new Commande(null, infoResto.getNumJournee()); commandeEquipementEnCours = new Commande(null, infoResto.getNumJournee()); btnSortir = new JButton("Sortir"); btnSortir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fermerMagasin(); } }); btnSortir.setBounds(10, 400, 89, 23); add(btnSortir); lblNewLabel = new JLabel("Fournisseurs"); lblNewLabel.setBounds(184, 11, 89, 14); add(lblNewLabel); lblNewLabel_1 = new JLabel("Stocks recette"); lblNewLabel_1.setBounds(21, 33, 109, 14); add(lblNewLabel_1); lblNewLabel_2 = new JLabel("Équipements"); lblNewLabel_2.setBounds(280, 33, 109, 14); add(lblNewLabel_2); cmbChoixFournisseurStock = new JComboBox(); cmbChoixFournisseurStock.setBounds(10, 48, 250, 24); add(cmbChoixFournisseurStock); cmbChoixFournisseurEquipement = new JComboBox(); cmbChoixFournisseurEquipement.setBounds(280, 48, 250, 24); add(cmbChoixFournisseurEquipement); txtFactureStock = new JTextPane(); txtFactureStock.setEditable(false); txtFactureStock.setContentType("text/html"); txtFactureStock.setText("<h1>Facture Stock</h1>"); txtFactureStock.setBounds(10, 106, 250, 134); add(txtFactureStock); lblFacture = new JLabel("Facture Stock"); lblFacture.setBounds(10, 93, 96, 14); add(lblFacture); btnModifierStock = new JButton("Modifier stock"); btnModifierStock.setBounds(txtFactureStock.getX(), txtFactureStock.getY() + txtFactureStock.getHeight() + 20, 250, 34); add(btnModifierStock); txtFactureEquipements = new JTextPane(); txtFactureEquipements.setEditable(false); txtFactureEquipements.setContentType("text/html"); txtFactureEquipements.setText("<h1>Facture equipment</h1>"); txtFactureEquipements.setBounds(280, 106, 250, 134); add(txtFactureEquipements); btnAjouterEquipement = new JButton("Ajouter équipement"); btnAjouterEquipement.setBounds(txtFactureEquipements.getX(), txtFactureEquipements.getY() + txtFactureEquipements.getHeight() + 20, 250, 34); add(btnAjouterEquipement); btnPasserCommande = new JButton("Passer Commande"); btnPasserCommande.setBounds(130, 400, 200, 23); add(btnPasserCommande); JLabel lblNewLabel_3 = new JLabel("Facture Equipement"); lblNewLabel_3.setToolTipText(""); lblNewLabel_3.setBounds(280, 93, 250, 14); add(lblNewLabel_3); } private void fermerMagasin() { // Le dialog est le 4e parent JDialog d = (JDialog) this.getParent().getParent().getParent().getParent(); d.dispose(); } public Commande getCommandeStockEnCours() { return commandeStockEnCours; } public Commande getCommandeEquipementEnCours() { return commandeEquipementEnCours; } public JTextPane getTxtFactureStock() { return txtFactureStock; } public JTextPane getTxtFactureEquipements() { return txtFactureEquipements; } public JButton getBtnPasserCommande() { return btnPasserCommande; } public JButton getBtnAjouterEquipement() { return btnAjouterEquipement; } public JButton getBtnModifierStock() { return btnModifierStock; } public JLabel getLblFacture() { return lblFacture; } public JComboBox getCmbChoixFournisseurEquipement() { return cmbChoixFournisseurEquipement; } public JComboBox getCmbChoixFournisseurStock() { return cmbChoixFournisseurStock; } public JLabel getLblNewLabel_2() { return lblNewLabel_2; } public JLabel getLblNewLabel_1() { return lblNewLabel_1; } public JLabel getLblNewLabel() { return lblNewLabel; } public JButton getBtnSortir() { return btnSortir; } }
ISO-8859-1
Java
4,921
java
FenetreFournisseur.java
Java
[]
null
[]
package Vues; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextPane; import Model.Fournisseur; import Model.InformationsResto; import commandes.ArticleCommande; import commandes.Commande; import java.text.DecimalFormat; public class FenetreFournisseur extends JPanel { private FenetrePrincipale fp; private InformationsResto infoResto; private Commande commandeStockEnCours; private Commande commandeEquipementEnCours; private JTextPane txtFactureStock; private JTextPane txtFactureEquipements; private JButton btnPasserCommande; private JButton btnAjouterEquipement; private JButton btnModifierStock; private JLabel lblFacture; private JComboBox cmbChoixFournisseurEquipement; private JComboBox cmbChoixFournisseurStock; private JLabel lblNewLabel_2; private JLabel lblNewLabel_1; private JLabel lblNewLabel; private JButton btnSortir; public FenetreFournisseur(InformationsResto ir, FenetrePrincipale fp) { setLayout(null); infoResto = ir; this.fp = fp; commandeStockEnCours = new Commande(null, infoResto.getNumJournee()); commandeEquipementEnCours = new Commande(null, infoResto.getNumJournee()); btnSortir = new JButton("Sortir"); btnSortir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fermerMagasin(); } }); btnSortir.setBounds(10, 400, 89, 23); add(btnSortir); lblNewLabel = new JLabel("Fournisseurs"); lblNewLabel.setBounds(184, 11, 89, 14); add(lblNewLabel); lblNewLabel_1 = new JLabel("Stocks recette"); lblNewLabel_1.setBounds(21, 33, 109, 14); add(lblNewLabel_1); lblNewLabel_2 = new JLabel("Équipements"); lblNewLabel_2.setBounds(280, 33, 109, 14); add(lblNewLabel_2); cmbChoixFournisseurStock = new JComboBox(); cmbChoixFournisseurStock.setBounds(10, 48, 250, 24); add(cmbChoixFournisseurStock); cmbChoixFournisseurEquipement = new JComboBox(); cmbChoixFournisseurEquipement.setBounds(280, 48, 250, 24); add(cmbChoixFournisseurEquipement); txtFactureStock = new JTextPane(); txtFactureStock.setEditable(false); txtFactureStock.setContentType("text/html"); txtFactureStock.setText("<h1>Facture Stock</h1>"); txtFactureStock.setBounds(10, 106, 250, 134); add(txtFactureStock); lblFacture = new JLabel("Facture Stock"); lblFacture.setBounds(10, 93, 96, 14); add(lblFacture); btnModifierStock = new JButton("Modifier stock"); btnModifierStock.setBounds(txtFactureStock.getX(), txtFactureStock.getY() + txtFactureStock.getHeight() + 20, 250, 34); add(btnModifierStock); txtFactureEquipements = new JTextPane(); txtFactureEquipements.setEditable(false); txtFactureEquipements.setContentType("text/html"); txtFactureEquipements.setText("<h1>Facture equipment</h1>"); txtFactureEquipements.setBounds(280, 106, 250, 134); add(txtFactureEquipements); btnAjouterEquipement = new JButton("Ajouter équipement"); btnAjouterEquipement.setBounds(txtFactureEquipements.getX(), txtFactureEquipements.getY() + txtFactureEquipements.getHeight() + 20, 250, 34); add(btnAjouterEquipement); btnPasserCommande = new JButton("Passer Commande"); btnPasserCommande.setBounds(130, 400, 200, 23); add(btnPasserCommande); JLabel lblNewLabel_3 = new JLabel("Facture Equipement"); lblNewLabel_3.setToolTipText(""); lblNewLabel_3.setBounds(280, 93, 250, 14); add(lblNewLabel_3); } private void fermerMagasin() { // Le dialog est le 4e parent JDialog d = (JDialog) this.getParent().getParent().getParent().getParent(); d.dispose(); } public Commande getCommandeStockEnCours() { return commandeStockEnCours; } public Commande getCommandeEquipementEnCours() { return commandeEquipementEnCours; } public JTextPane getTxtFactureStock() { return txtFactureStock; } public JTextPane getTxtFactureEquipements() { return txtFactureEquipements; } public JButton getBtnPasserCommande() { return btnPasserCommande; } public JButton getBtnAjouterEquipement() { return btnAjouterEquipement; } public JButton getBtnModifierStock() { return btnModifierStock; } public JLabel getLblFacture() { return lblFacture; } public JComboBox getCmbChoixFournisseurEquipement() { return cmbChoixFournisseurEquipement; } public JComboBox getCmbChoixFournisseurStock() { return cmbChoixFournisseurStock; } public JLabel getLblNewLabel_2() { return lblNewLabel_2; } public JLabel getLblNewLabel_1() { return lblNewLabel_1; } public JLabel getLblNewLabel() { return lblNewLabel; } public JButton getBtnSortir() { return btnSortir; } }
4,921
0.768246
0.739175
184
25.733696
21.408037
116
false
false
0
0
0
0
0
0
1.961957
false
false
15
2b2afc3342d4de1dd59223d6af99788de4f5ca07
21,792,664,117,157
7063b190e508b27991f0877a14e6a88edfc02cf6
/app/src/main/java/scut/carson_ho/androidinterview/AlgorithmLearning/Exam_3.java
3ffd29aa706f61b3ea6e558b1a34ca5f11dd5a1d
[]
no_license
Carson-Ho/AndroidLearning
https://github.com/Carson-Ho/AndroidLearning
c23f76447d71ed1c605c64f17893cf3288e726af
3ebb01aedacccf59b67a6328e69f6d8410667611
refs/heads/master
2021-12-30T13:32:09.758000
2021-12-22T03:46:56
2021-12-22T03:46:56
115,426,105
75
22
null
null
null
null
null
null
null
null
null
null
null
null
null
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/10/18. */ public class Exam_3 { /** * 解题算法:找出数组中重复数字(可修改数组) * @param arr = 输入数组 * @return */ private static boolean answer(int[] arr){ // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 0~n-1范围 // 1.1 判断数组下标是否越界 if(arr == null || arr.length<=0) { System.out.print("输入不合法 "); return false; } // 1.2 判断数字 是否在 (0 ~ n-1)范围 for (int i = 0; i < arr.length; i++) { if (arr[i] < 0 || arr[i] > arr.length-1) { System.out.print("输入不合法 "); return false; } } // 2. 遍历数组 for (int i = 0; i < arr.length; i++) { // 3. 比较 下标= i位置的值与该下标本身 while( arr[i]!=i ){ // 若下标= i位置的值 = 下标= 前者值位置的值,即找到重复数字,输出 if(arr[i]== arr[arr[i]]){ System.out.print("重复的数字是:"+ arr[i] + ""); return true; // 若只需找出任意1个重复数字,则采用return ,即找到重复数字时就直接结束函数 // 采用 break; ,即 找出全部重复的数字 } else { // 否则,交换位置 // 把后者放在属于它的位置 int temp = arr[i]; arr[i] = arr[arr[i]]; arr[temp] = temp; } } } System.out.print("不含重复数字 "); return false; } /** * 解题算法(已经过牛客网测试) * 找出数组中重复数字(可修改数组) * @param numbers = 输入数组 * @param length = 数组长度 * @param duplication = 返回的测试数组 * @return */ public boolean duplicate(int numbers[],int length,int [] duplication) { // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 0~n-1范围 // 1.1 判断数组下标是否越界 if(numbers == null || length <=0) { return false; } // 1.2 判断数字 是否在 (0 ~ n-1)范围 for (int i = 0; i < length; i++) { if (numbers[i] < 0 || numbers[i] > length-1) { return false; } } // 2. 遍历数组 for (int i = 0; i < length; i++) { // 3. 比较 下标= i位置的值与该下标本身 while( numbers[i]!=i ){ // 若下标= i位置的值 = 下标= 前者值位置的值,即找到重复数字,输出 if(numbers[i]== numbers[numbers[i]]){ // 赋值给结果数组 duplication[0] = numbers[i]; return true; // 若只需找出任意1个重复数字,则采用return ,即找到重复数字时就直接结束函数 // 采用 break; ,即 找出全部重复的数字 } else { // 否则,交换位置 // 把后者放在属于它的位置 int temp = numbers[i]; numbers[i] = numbers[numbers[i]]; numbers[temp] = temp; } } } System.out.println("结束"); return false; } /*******************************************/ /** * 找出数组中重复数字(不可修改数组) * 方式:创建辅助数组 * @param arr = 输入数组 * @return */ private static int answer_AssArr(int[] arr){ // 1. 判断输入数据的合法性 // 即,判断数组下标是否越界 & 数字 = 1~n 范围 if(arr==null||arr.length-1<=0) return -1; for (int i = 0; i < arr.length; i++) { if(arr[i]<1||arr[i]>arr.length) return -1; } // 2. 创建辅助数组 int[] cp = new int[arr.length]; for (int i = 0; i < arr.length; i++) { if(cp[arr[i]]==0) // 将原数组中的arr[i]复制到新数组中下标为arr[i]的位置 cp[arr[i]] = arr[i]; else { System.out.println("重复的数字:" + arr[i]); // return arr[i]; // 采用return,则是找出1个重复数字,则马上结束函数 } } System.out.println("结束"); return -1; } /*******************************************/ /** * 找出数组中重复数字(不修改数组) * 方式:二分查找 * @param arr = 输入数组 * @return */ private static int answer_NoChangArr(int[] arr){ // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 1~n 范围 if(arr==null || arr.length==0) return -1; for (int i = 0; i < arr.length; i++) { if(arr[i]<1 || arr[i] > arr.length) return -1; } int start = 1; int end = arr.length-1; while(start <= end){ // 2. 将范围数字分成2部分 int mid = (end+start)/2; // 3. 统计区间内的数字出现的次数 int count = countRange(arr,arr.length-1,start,mid); // 直到分到该部分只有1个数字 & 统计次数>1次,则找到重复数字,输出 if(end == start){ if(count>1) { System.out.print("重复的数字:"); return start; }else break; } // 若左1半统计的次数 > 该范围内的数字,则继续在该左1半采用二分法 if(count>(mid-start+1)) end = mid; else start = mid+1; } System.out.print("无重复数字"); return -1; } /** * 辅助算法:统计区间范围内的数字出现的次数 */ private static int countRange(int[] arr, int n, int start, int end) { // 判断输入数据的合法性 if(arr==null || n<=0 ) return 0; int count = 0; // 统计区间范围内的数字出现的次数 for (int i = 0; i < arr.length; i++) { if(arr[i]>=start&&arr[i]<=end) count++; } return count; } /*******************************************/ /** * 测试用例 */ public static void main(String[] args) { // 功能测试1:数组长度 = 8,含1个重复数字 int[] src = new int[]{2,1,5,4,3,2,6,7}; System.out.println(answer_NoChangArr(src)); // 功能测试2:数组长度 = 8,含多个重复数字 int[] src1 = new int[]{2,2,5,4,3,2,6,7}; System.out.println(answer_NoChangArr(src1)); // 功能测试3:数组长度 = 8,不含重复数字 int[] src2 = new int[]{0,1,2,3,4,5,6,7}; System.out.println(answer_NoChangArr(src2)); // 特殊输入测试:空指针 System.out.println(answer_NoChangArr(null)); } }
UTF-8
Java
7,625
java
Exam_3.java
Java
[ { "context": "oidinterview.AlgorithmLearning;\n\n/**\n * Created by Carson_Ho on 17/10/18.\n */\n\npublic class Exam_3 {\n\n /**\n", "end": 87, "score": 0.9717763066291809, "start": 78, "tag": "NAME", "value": "Carson_Ho" } ]
null
[]
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/10/18. */ public class Exam_3 { /** * 解题算法:找出数组中重复数字(可修改数组) * @param arr = 输入数组 * @return */ private static boolean answer(int[] arr){ // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 0~n-1范围 // 1.1 判断数组下标是否越界 if(arr == null || arr.length<=0) { System.out.print("输入不合法 "); return false; } // 1.2 判断数字 是否在 (0 ~ n-1)范围 for (int i = 0; i < arr.length; i++) { if (arr[i] < 0 || arr[i] > arr.length-1) { System.out.print("输入不合法 "); return false; } } // 2. 遍历数组 for (int i = 0; i < arr.length; i++) { // 3. 比较 下标= i位置的值与该下标本身 while( arr[i]!=i ){ // 若下标= i位置的值 = 下标= 前者值位置的值,即找到重复数字,输出 if(arr[i]== arr[arr[i]]){ System.out.print("重复的数字是:"+ arr[i] + ""); return true; // 若只需找出任意1个重复数字,则采用return ,即找到重复数字时就直接结束函数 // 采用 break; ,即 找出全部重复的数字 } else { // 否则,交换位置 // 把后者放在属于它的位置 int temp = arr[i]; arr[i] = arr[arr[i]]; arr[temp] = temp; } } } System.out.print("不含重复数字 "); return false; } /** * 解题算法(已经过牛客网测试) * 找出数组中重复数字(可修改数组) * @param numbers = 输入数组 * @param length = 数组长度 * @param duplication = 返回的测试数组 * @return */ public boolean duplicate(int numbers[],int length,int [] duplication) { // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 0~n-1范围 // 1.1 判断数组下标是否越界 if(numbers == null || length <=0) { return false; } // 1.2 判断数字 是否在 (0 ~ n-1)范围 for (int i = 0; i < length; i++) { if (numbers[i] < 0 || numbers[i] > length-1) { return false; } } // 2. 遍历数组 for (int i = 0; i < length; i++) { // 3. 比较 下标= i位置的值与该下标本身 while( numbers[i]!=i ){ // 若下标= i位置的值 = 下标= 前者值位置的值,即找到重复数字,输出 if(numbers[i]== numbers[numbers[i]]){ // 赋值给结果数组 duplication[0] = numbers[i]; return true; // 若只需找出任意1个重复数字,则采用return ,即找到重复数字时就直接结束函数 // 采用 break; ,即 找出全部重复的数字 } else { // 否则,交换位置 // 把后者放在属于它的位置 int temp = numbers[i]; numbers[i] = numbers[numbers[i]]; numbers[temp] = temp; } } } System.out.println("结束"); return false; } /*******************************************/ /** * 找出数组中重复数字(不可修改数组) * 方式:创建辅助数组 * @param arr = 输入数组 * @return */ private static int answer_AssArr(int[] arr){ // 1. 判断输入数据的合法性 // 即,判断数组下标是否越界 & 数字 = 1~n 范围 if(arr==null||arr.length-1<=0) return -1; for (int i = 0; i < arr.length; i++) { if(arr[i]<1||arr[i]>arr.length) return -1; } // 2. 创建辅助数组 int[] cp = new int[arr.length]; for (int i = 0; i < arr.length; i++) { if(cp[arr[i]]==0) // 将原数组中的arr[i]复制到新数组中下标为arr[i]的位置 cp[arr[i]] = arr[i]; else { System.out.println("重复的数字:" + arr[i]); // return arr[i]; // 采用return,则是找出1个重复数字,则马上结束函数 } } System.out.println("结束"); return -1; } /*******************************************/ /** * 找出数组中重复数字(不修改数组) * 方式:二分查找 * @param arr = 输入数组 * @return */ private static int answer_NoChangArr(int[] arr){ // 1. 判断输入数据 是否合法 // 即,判断数组下标是否越界 & 数字 = 1~n 范围 if(arr==null || arr.length==0) return -1; for (int i = 0; i < arr.length; i++) { if(arr[i]<1 || arr[i] > arr.length) return -1; } int start = 1; int end = arr.length-1; while(start <= end){ // 2. 将范围数字分成2部分 int mid = (end+start)/2; // 3. 统计区间内的数字出现的次数 int count = countRange(arr,arr.length-1,start,mid); // 直到分到该部分只有1个数字 & 统计次数>1次,则找到重复数字,输出 if(end == start){ if(count>1) { System.out.print("重复的数字:"); return start; }else break; } // 若左1半统计的次数 > 该范围内的数字,则继续在该左1半采用二分法 if(count>(mid-start+1)) end = mid; else start = mid+1; } System.out.print("无重复数字"); return -1; } /** * 辅助算法:统计区间范围内的数字出现的次数 */ private static int countRange(int[] arr, int n, int start, int end) { // 判断输入数据的合法性 if(arr==null || n<=0 ) return 0; int count = 0; // 统计区间范围内的数字出现的次数 for (int i = 0; i < arr.length; i++) { if(arr[i]>=start&&arr[i]<=end) count++; } return count; } /*******************************************/ /** * 测试用例 */ public static void main(String[] args) { // 功能测试1:数组长度 = 8,含1个重复数字 int[] src = new int[]{2,1,5,4,3,2,6,7}; System.out.println(answer_NoChangArr(src)); // 功能测试2:数组长度 = 8,含多个重复数字 int[] src1 = new int[]{2,2,5,4,3,2,6,7}; System.out.println(answer_NoChangArr(src1)); // 功能测试3:数组长度 = 8,不含重复数字 int[] src2 = new int[]{0,1,2,3,4,5,6,7}; System.out.println(answer_NoChangArr(src2)); // 特殊输入测试:空指针 System.out.println(answer_NoChangArr(null)); } }
7,625
0.40605
0.38698
252
23.138889
18.569918
75
false
false
0
0
0
0
0
0
0.472222
false
false
15
ccb7009d08a06a85f7c3c8c444102b67b8fa8559
13,924,284,026,010
e41491665075cfec6d727039a70b10d1926fbc73
/examples/at.ac.tuwien.big.momot.examples.ecore/src/at/ac/tuwien/big/momot/examples/ecore/fitness/metric/LanguageMetrics.java
00bdfca84d65c46f288cc03c32f1da306ff069a3
[]
no_license
liberion1994/momot_updated
https://github.com/liberion1994/momot_updated
fc99665d11c4c7cb4ae6d896daa99af6517807f8
e851a2074f8069a8df3a3e5d657c7a2f74cbaf4d
refs/heads/master
2021-07-07T00:51:07.110000
2019-06-09T11:25:59
2019-06-09T11:25:59
190,997,941
0
2
null
false
2020-10-13T13:46:43
2019-06-09T11:26:49
2019-06-09T11:28:49
2020-10-13T13:46:41
44,872
0
0
1
Java
false
false
package at.ac.tuwien.big.momot.examples.ecore.fitness.metric; import at.ac.tuwien.big.momot.examples.ecore.modularization.Language; import at.ac.tuwien.big.momot.examples.ecore.modularization.Module; public class LanguageMetrics extends Metrics { private static final long serialVersionUID = -8382677736030566696L; protected Language language; protected int nrModules; protected int minModuleSize = Integer.MAX_VALUE; protected int maxModuleSize = Integer.MIN_VALUE; public LanguageMetrics() {} public LanguageMetrics(final Language language) { setLanguage(language); } protected void addNrModules(final int nrModules) { this.nrModules += nrModules; } public void considerModule(final Module module) { addNrModules(1); final int moduleSize = module.getEntities().size(); if(moduleSize < minModuleSize) { minModuleSize = moduleSize; } if(moduleSize > maxModuleSize) { maxModuleSize = moduleSize; } } public Language getLanguage() { return language; } public int getMinMaxDiff() { return maxModuleSize - minModuleSize; } public int getNrModules() { return nrModules; } public void setLanguage(final Language language) { this.language = language; } protected void setNrModules(final int nrModules) { this.nrModules = nrModules; } @Override public String toString(final String indent) { final StringBuilder sb = new StringBuilder(); sb.append(indent + "Language: " + getLanguage().getName() + "\n"); sb.append(indent + "Non-Empty Modules: " + getNrModules() + "\n"); sb.append(indent + "MinMaxDiff: " + getMinMaxDiff() + "\n"); sb.append(super.toString(indent)); return sb.toString(); } }
UTF-8
Java
1,888
java
LanguageMetrics.java
Java
[]
null
[]
package at.ac.tuwien.big.momot.examples.ecore.fitness.metric; import at.ac.tuwien.big.momot.examples.ecore.modularization.Language; import at.ac.tuwien.big.momot.examples.ecore.modularization.Module; public class LanguageMetrics extends Metrics { private static final long serialVersionUID = -8382677736030566696L; protected Language language; protected int nrModules; protected int minModuleSize = Integer.MAX_VALUE; protected int maxModuleSize = Integer.MIN_VALUE; public LanguageMetrics() {} public LanguageMetrics(final Language language) { setLanguage(language); } protected void addNrModules(final int nrModules) { this.nrModules += nrModules; } public void considerModule(final Module module) { addNrModules(1); final int moduleSize = module.getEntities().size(); if(moduleSize < minModuleSize) { minModuleSize = moduleSize; } if(moduleSize > maxModuleSize) { maxModuleSize = moduleSize; } } public Language getLanguage() { return language; } public int getMinMaxDiff() { return maxModuleSize - minModuleSize; } public int getNrModules() { return nrModules; } public void setLanguage(final Language language) { this.language = language; } protected void setNrModules(final int nrModules) { this.nrModules = nrModules; } @Override public String toString(final String indent) { final StringBuilder sb = new StringBuilder(); sb.append(indent + "Language: " + getLanguage().getName() + "\n"); sb.append(indent + "Non-Empty Modules: " + getNrModules() + "\n"); sb.append(indent + "MinMaxDiff: " + getMinMaxDiff() + "\n"); sb.append(super.toString(indent)); return sb.toString(); } }
1,888
0.649364
0.638771
64
27.5
24.188711
82
false
false
0
0
0
0
0
0
0.390625
false
false
15
aafdd04b045022382bdda3023907aad3ba57ff27
34,488,587,418,551
480e612d564319c9279897d982d5346fa79076ca
/mvn-ae-ecommerce/src/main/java/aeecommerce/dao/AziendaHibernateDao.java
d5a8560f2e555bf7861218a8a07a5070345aa315
[]
no_license
andreamartire/ae-ecommerce
https://github.com/andreamartire/ae-ecommerce
2c34c9053a8eab59e309a0de1dd1934c883a2bf5
147d8d054e70f517b76b7a3f280af26f7eee970a
refs/heads/master
2020-06-02T15:27:53.288000
2012-02-04T12:57:39
2012-02-04T12:57:39
32,264,537
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aeecommerce.dao; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Transactional; import aeecommerce.pojo.Azienda; public class AziendaHibernateDao extends HibernateDaoSupport implements AziendaDao { public void insert(Azienda a) { getHibernateTemplate().save(a); } @Transactional public void update(Azienda a) { getHibernateTemplate().update(a); } @Transactional public void delete(int id) { Azienda a = (Azienda) getHibernateTemplate().get(Azienda.class, id); getHibernateTemplate().delete(a); } @Transactional public Azienda findByID(int id) { return (Azienda) getHibernateTemplate().get(Azienda.class,id); } @Transactional @SuppressWarnings("unchecked") public List<Azienda> findAll() { return getHibernateTemplate().find("from Azienda"); } @Transactional public int count() { return findAll().size(); } public void delete(Azienda a) { getHibernateTemplate().delete(a); } }
UTF-8
Java
1,028
java
AziendaHibernateDao.java
Java
[]
null
[]
package aeecommerce.dao; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Transactional; import aeecommerce.pojo.Azienda; public class AziendaHibernateDao extends HibernateDaoSupport implements AziendaDao { public void insert(Azienda a) { getHibernateTemplate().save(a); } @Transactional public void update(Azienda a) { getHibernateTemplate().update(a); } @Transactional public void delete(int id) { Azienda a = (Azienda) getHibernateTemplate().get(Azienda.class, id); getHibernateTemplate().delete(a); } @Transactional public Azienda findByID(int id) { return (Azienda) getHibernateTemplate().get(Azienda.class,id); } @Transactional @SuppressWarnings("unchecked") public List<Azienda> findAll() { return getHibernateTemplate().find("from Azienda"); } @Transactional public int count() { return findAll().size(); } public void delete(Azienda a) { getHibernateTemplate().delete(a); } }
1,028
0.755837
0.754864
48
20.4375
22.382011
84
false
false
0
0
0
0
0
0
1.0625
false
false
15
01f50525a5a6579b482a55f23ab5ab5aebfc2092
34,385,508,201,720
03d29af98e81ee0188194fa9207bc42c2428dabf
/ConnectIt/src/com/connectit/game/gameboard/dices/logic/Generator.java
7ec46fb8b258f606645ab314e843ab2e7683ffe2
[]
no_license
DenisAndr/ConnectIt
https://github.com/DenisAndr/ConnectIt
0b1239b01264dfd3ee6cbadca03c429cad939202
0d63d7f4692eab17ffee26cb9175929e2267d0c8
refs/heads/master
2018-12-28T00:44:50.420000
2016-07-12T14:17:39
2016-07-12T14:17:39
48,498,609
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.connectit.game.gameboard.dices.logic; import java.util.ArrayList; public interface Generator { /** * * @return Возвращает список элементов замкнутой цепи, или null если замкнуть не удалось. */ public ArrayList<GameDice> chackClosedCircuit(); }
WINDOWS-1251
Java
331
java
Generator.java
Java
[]
null
[]
package com.connectit.game.gameboard.dices.logic; import java.util.ArrayList; public interface Generator { /** * * @return Возвращает список элементов замкнутой цепи, или null если замкнуть не удалось. */ public ArrayList<GameDice> chackClosedCircuit(); }
331
0.750929
0.750929
12
21.416666
27.326599
90
false
false
0
0
0
0
0
0
0.833333
false
false
15
7952a75404aefda2a6afb6e851a76c5d1d275159
19,928,648,298,737
388f4dc0b63fb00f6f29017f8eef71de566fad45
/src/main/java/com/hard/function/BezierLines/DIYBezierView.java
742b313645c87c2b016fa4ea9d0d6f1aaef39886
[]
no_license
Jerryzouzou/testtoday
https://github.com/Jerryzouzou/testtoday
11eaebdca3741f7cd29aacbc75817a2c0e837084
96cf2b0a41b07745bcf3d70eff494a0dc9baa32b
refs/heads/master
2021-07-14T09:30:59.807000
2020-02-14T13:38:19
2020-02-14T13:38:19
239,920,185
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hard.function.BezierLines; import android.content.Context; import android.content.res.Resources; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import com.hard.function.R; import com.hard.function.common.GridCoordinateCustomBaseView; import com.hard.function.tool.UIUtils; import java.util.ArrayList; import java.util.List; import androidx.annotation.Nullable; /** * @author Jerry Lai on 2019/06/12 */ public class DIYBezierView extends GridCoordinateCustomBaseView { private PointF centerPointF; //圆心 //控制点列表,顺序为:右上、右下、左下、左上 private List<PointF> controlPointList; //选中的点集合,受 status 影响 private List<PointF> curSelectPointList; private PointF curSelectPoint; private Path controlPath; private Path diyBezierPath; private Paint diyBezierPaint; private Paint controlLinePaint; private Paint controlPointPaint; private Paint circlePaint; private Status status; //拖曳时的状态 private Resources res; private Context mContext; // 线的宽度 private int LINE_WIDTH; // 控制点的半径 private int POINT_RADIO_WIDTH; // 选中控制点的半径 private int SEL_POINT_RADIO_WIDTH; private float mRadius; //圆半径 private float mRatio; //控制点占半径的比例 // 是否显示辅助线 private boolean mIsShowHelpLine; // 触碰的x轴 private float mLastX = -1; // 触碰的y轴 private float mLastY = -1; // 有效触碰的范围 private int mTouchRegionWidth; public DIYBezierView(Context context) { super(context); } public DIYBezierView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public DIYBezierView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void init(Context context) { mContext = context; res = mContext.getResources(); int width = UIUtils.getScreenWidth(context); mRadius = width / 4; LINE_WIDTH = UIUtils.dip2px(2); POINT_RADIO_WIDTH = UIUtils.dip2px(4); SEL_POINT_RADIO_WIDTH = UIUtils.dip2px(6); mTouchRegionWidth = UIUtils.dip2px(20); centerPointF = new PointF(0, 0); controlPointList = new ArrayList<>(); curSelectPointList = new ArrayList<>(); controlPath = new Path(); diyBezierPath = new Path(); mIsShowHelpLine = true; mRatio = 0.55f; status = Status.FREE; diyBezierPaint = UIUtils.getFillPaint(Color.GREEN); circlePaint = UIUtils.getStrokePaint(context, LINE_WIDTH, res.getColor(R.color.colorOrange, null)); controlLinePaint =UIUtils.getStrokePaint(context, LINE_WIDTH, Color.RED); controlPointPaint =UIUtils.getFillPaint(Color.RED); calculateControlPoint(); } @Override protected void onDraw(Canvas canvas) { drawCoordinateGrid(canvas); canvas.translate(mWidth/2, mHeight/2); diyBezierPath.reset(); //计算每边控制基线的贝塞尔曲线路径 for (int i = 0; i < 4; i++) { if(i == 0){ diyBezierPath.moveTo(controlPointList.get(i*3).x, controlPointList.get(i*3).y); }else { diyBezierPath.lineTo(controlPointList.get(i*3).x, controlPointList.get(i*3).y); } int endPonitIndex = (i==3) ? 0 : (i*3+3); diyBezierPath.cubicTo(controlPointList.get(i*3+1).x, controlPointList.get(i*3+1).y, controlPointList.get(i*3+2).x, controlPointList.get(i*3+2).y, controlPointList.get(endPonitIndex).x, controlPointList.get(endPonitIndex).y); } canvas.drawPath(diyBezierPath, diyBezierPaint); if(!mIsShowHelpLine) return; canvas.drawCircle(centerPointF.x, centerPointF.y, mRadius, circlePaint); //绘制控制基线 controlPath.reset(); for (int i = 0; i < 4; i++) { int startIndex = i * 3; if(i == 0){ controlPath.moveTo(controlPointList.get(controlPointList.size()-1).x, controlPointList.get(controlPointList.size() - 1).y); }else { controlPath.moveTo(controlPointList.get(startIndex - 1).x, controlPointList.get(startIndex - 1).y); } controlPath.lineTo(controlPointList.get(startIndex).x, controlPointList.get(startIndex).y); controlPath.lineTo(controlPointList.get(startIndex+1).x, controlPointList.get(startIndex+1).y); } canvas.drawPath(controlPath, controlLinePaint); //绘制控制点 for (int i = 0; i < controlPointList.size(); i++) { PointF point = controlPointList.get(i); float w; if(curSelectPointList.contains(point)){ controlPointPaint.setColor(Color.BLUE); w = SEL_POINT_RADIO_WIDTH; }else { controlPointPaint.setColor(Color.RED); w = POINT_RADIO_WIDTH; } canvas.drawCircle(point.x, point.y, w, controlPointPaint); } // 如果为三点拽动,将三点连接 if(status == Status.THREE){ if(curSelectPointList.size() == 1) return; for (int i = 0; i < curSelectPointList.size() - 1; i++) { controlPointPaint.setColor(Color.BLUE); canvas.drawLine(curSelectPointList.get(i).x, curSelectPointList.get(i).y, curSelectPointList.get(i+1).x, curSelectPointList.get(i+1).y, controlPointPaint); } } } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if(selectControlPoint(x, y)){ mLastX = x; mLastY = y; } break; case MotionEvent.ACTION_MOVE: if(mLastY==-1 || mLastX==-1){ return true; } float offsetX = x - mLastX; float offsetY = y - mLastY; if((status==Status.MIRROR_DIFF || status==Status.MIRROR_SAME) && curSelectPoint!=null){ curSelectPoint.x += offsetX; curSelectPoint.y += offsetY; if(status == Status.MIRROR_DIFF){ offsetX = -offsetX; offsetY = -offsetY; } PointF otherPoint = null; for (PointF point : curSelectPointList){ if(point != curSelectPoint){ otherPoint = point; break; } } if(otherPoint != null){ otherPoint.x += offsetX; otherPoint.y += offsetY; } }else{ for (PointF point : curSelectPointList){ point.x += offsetX; point.y += offsetY; } } mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: curSelectPointList.clear(); curSelectPoint = null; mLastY = mLastX = -1; break; } invalidate(); return true; } /** * 是否在有效的触碰范围 */ private boolean selectControlPoint(float x, float y) { int selectIndex = -1; for (int i = 0; i < controlPointList.size(); i++) { PointF point = controlPointList.get(i); float realX = point.x + mWidth/2; float realY = point.y + mHeight/2; RectF rectRange = new RectF(realX-mTouchRegionWidth, realY-mTouchRegionWidth, realX+mTouchRegionWidth, realY+mTouchRegionWidth); if(rectRange.contains(x, y)){ selectIndex = i; break; } } if(selectIndex == -1){ return false; } curSelectPointList.clear(); curSelectPoint = controlPointList.get(selectIndex); switch (status){ case FREE: // 任意点拽动 curSelectPointList.add(curSelectPoint); break; case THREE: int offsetSeleIndex = (selectIndex + 1) % 12; int offsetRangeIndex = offsetSeleIndex / 3; if(offsetSeleIndex == 0){ curSelectPointList.add(controlPointList.get(11)); }else { curSelectPointList.add(controlPointList.get(offsetRangeIndex*3 - 1)); } curSelectPointList.add(controlPointList.get(offsetRangeIndex*3)); curSelectPointList.add(controlPointList.get(offsetRangeIndex*3 + 1)); break; case MIRROR_DIFF: case MIRROR_SAME: if(selectIndex==0 || selectIndex==6){ curSelectPointList.add(controlPointList.get(0)); curSelectPointList.add(controlPointList.get(6)); }else { curSelectPointList.add(controlPointList.get(selectIndex)); curSelectPointList.add(controlPointList.get(12 - selectIndex)); } break; } return true; } public void reset(){ calculateControlPoint(); invalidate(); } public void setStatus(Status status) { this.status = status; } /** * 设置比例--印象计算控制点因子 */ public void setRatio(float ratio) { this.mRatio = ratio; calculateControlPoint(); invalidate(); } public void setIsShowHelpLine(boolean isShowHelpLine) { this.mIsShowHelpLine = isShowHelpLine; invalidate(); } public List<PointF> getControlPointList() { return controlPointList; } /** * 计算圆的控制点 */ private void calculateControlPoint() { // 计算 中间控制点到端点的距离 float controlWidth = mRatio * mRadius; controlPointList.clear(); // 右上 controlPointList.add(new PointF(0, -mRadius)); controlPointList.add(new PointF(controlWidth, -mRadius)); controlPointList.add(new PointF(mRadius, -controlWidth)); // 右下 controlPointList.add(new PointF(mRadius, 0)); controlPointList.add(new PointF(mRadius, controlWidth)); controlPointList.add(new PointF(controlWidth, mRadius)); // 左下 controlPointList.add(new PointF(0, mRadius)); controlPointList.add(new PointF(-controlWidth, mRadius)); controlPointList.add(new PointF(-mRadius, controlWidth)); // 左上 controlPointList.add(new PointF(-mRadius, 0)); controlPointList.add(new PointF(-mRadius, -controlWidth)); controlPointList.add(new PointF(-controlWidth, -mRadius)); } public enum Status { FREE, // 自由拽动 THREE, // 三点拽动 MIRROR_DIFF, // 镜像异向 MIRROR_SAME, // 镜像同向 } }
UTF-8
Java
11,861
java
DIYBezierView.java
Java
[ { "context": "port androidx.annotation.Nullable;\n\n/**\n * @author Jerry Lai on 2019/06/12\n */\npublic class DIYBezierView exte", "end": 654, "score": 0.9998458027839661, "start": 645, "tag": "NAME", "value": "Jerry Lai" } ]
null
[]
package com.hard.function.BezierLines; import android.content.Context; import android.content.res.Resources; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import com.hard.function.R; import com.hard.function.common.GridCoordinateCustomBaseView; import com.hard.function.tool.UIUtils; import java.util.ArrayList; import java.util.List; import androidx.annotation.Nullable; /** * @author <NAME> on 2019/06/12 */ public class DIYBezierView extends GridCoordinateCustomBaseView { private PointF centerPointF; //圆心 //控制点列表,顺序为:右上、右下、左下、左上 private List<PointF> controlPointList; //选中的点集合,受 status 影响 private List<PointF> curSelectPointList; private PointF curSelectPoint; private Path controlPath; private Path diyBezierPath; private Paint diyBezierPaint; private Paint controlLinePaint; private Paint controlPointPaint; private Paint circlePaint; private Status status; //拖曳时的状态 private Resources res; private Context mContext; // 线的宽度 private int LINE_WIDTH; // 控制点的半径 private int POINT_RADIO_WIDTH; // 选中控制点的半径 private int SEL_POINT_RADIO_WIDTH; private float mRadius; //圆半径 private float mRatio; //控制点占半径的比例 // 是否显示辅助线 private boolean mIsShowHelpLine; // 触碰的x轴 private float mLastX = -1; // 触碰的y轴 private float mLastY = -1; // 有效触碰的范围 private int mTouchRegionWidth; public DIYBezierView(Context context) { super(context); } public DIYBezierView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public DIYBezierView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void init(Context context) { mContext = context; res = mContext.getResources(); int width = UIUtils.getScreenWidth(context); mRadius = width / 4; LINE_WIDTH = UIUtils.dip2px(2); POINT_RADIO_WIDTH = UIUtils.dip2px(4); SEL_POINT_RADIO_WIDTH = UIUtils.dip2px(6); mTouchRegionWidth = UIUtils.dip2px(20); centerPointF = new PointF(0, 0); controlPointList = new ArrayList<>(); curSelectPointList = new ArrayList<>(); controlPath = new Path(); diyBezierPath = new Path(); mIsShowHelpLine = true; mRatio = 0.55f; status = Status.FREE; diyBezierPaint = UIUtils.getFillPaint(Color.GREEN); circlePaint = UIUtils.getStrokePaint(context, LINE_WIDTH, res.getColor(R.color.colorOrange, null)); controlLinePaint =UIUtils.getStrokePaint(context, LINE_WIDTH, Color.RED); controlPointPaint =UIUtils.getFillPaint(Color.RED); calculateControlPoint(); } @Override protected void onDraw(Canvas canvas) { drawCoordinateGrid(canvas); canvas.translate(mWidth/2, mHeight/2); diyBezierPath.reset(); //计算每边控制基线的贝塞尔曲线路径 for (int i = 0; i < 4; i++) { if(i == 0){ diyBezierPath.moveTo(controlPointList.get(i*3).x, controlPointList.get(i*3).y); }else { diyBezierPath.lineTo(controlPointList.get(i*3).x, controlPointList.get(i*3).y); } int endPonitIndex = (i==3) ? 0 : (i*3+3); diyBezierPath.cubicTo(controlPointList.get(i*3+1).x, controlPointList.get(i*3+1).y, controlPointList.get(i*3+2).x, controlPointList.get(i*3+2).y, controlPointList.get(endPonitIndex).x, controlPointList.get(endPonitIndex).y); } canvas.drawPath(diyBezierPath, diyBezierPaint); if(!mIsShowHelpLine) return; canvas.drawCircle(centerPointF.x, centerPointF.y, mRadius, circlePaint); //绘制控制基线 controlPath.reset(); for (int i = 0; i < 4; i++) { int startIndex = i * 3; if(i == 0){ controlPath.moveTo(controlPointList.get(controlPointList.size()-1).x, controlPointList.get(controlPointList.size() - 1).y); }else { controlPath.moveTo(controlPointList.get(startIndex - 1).x, controlPointList.get(startIndex - 1).y); } controlPath.lineTo(controlPointList.get(startIndex).x, controlPointList.get(startIndex).y); controlPath.lineTo(controlPointList.get(startIndex+1).x, controlPointList.get(startIndex+1).y); } canvas.drawPath(controlPath, controlLinePaint); //绘制控制点 for (int i = 0; i < controlPointList.size(); i++) { PointF point = controlPointList.get(i); float w; if(curSelectPointList.contains(point)){ controlPointPaint.setColor(Color.BLUE); w = SEL_POINT_RADIO_WIDTH; }else { controlPointPaint.setColor(Color.RED); w = POINT_RADIO_WIDTH; } canvas.drawCircle(point.x, point.y, w, controlPointPaint); } // 如果为三点拽动,将三点连接 if(status == Status.THREE){ if(curSelectPointList.size() == 1) return; for (int i = 0; i < curSelectPointList.size() - 1; i++) { controlPointPaint.setColor(Color.BLUE); canvas.drawLine(curSelectPointList.get(i).x, curSelectPointList.get(i).y, curSelectPointList.get(i+1).x, curSelectPointList.get(i+1).y, controlPointPaint); } } } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if(selectControlPoint(x, y)){ mLastX = x; mLastY = y; } break; case MotionEvent.ACTION_MOVE: if(mLastY==-1 || mLastX==-1){ return true; } float offsetX = x - mLastX; float offsetY = y - mLastY; if((status==Status.MIRROR_DIFF || status==Status.MIRROR_SAME) && curSelectPoint!=null){ curSelectPoint.x += offsetX; curSelectPoint.y += offsetY; if(status == Status.MIRROR_DIFF){ offsetX = -offsetX; offsetY = -offsetY; } PointF otherPoint = null; for (PointF point : curSelectPointList){ if(point != curSelectPoint){ otherPoint = point; break; } } if(otherPoint != null){ otherPoint.x += offsetX; otherPoint.y += offsetY; } }else{ for (PointF point : curSelectPointList){ point.x += offsetX; point.y += offsetY; } } mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: curSelectPointList.clear(); curSelectPoint = null; mLastY = mLastX = -1; break; } invalidate(); return true; } /** * 是否在有效的触碰范围 */ private boolean selectControlPoint(float x, float y) { int selectIndex = -1; for (int i = 0; i < controlPointList.size(); i++) { PointF point = controlPointList.get(i); float realX = point.x + mWidth/2; float realY = point.y + mHeight/2; RectF rectRange = new RectF(realX-mTouchRegionWidth, realY-mTouchRegionWidth, realX+mTouchRegionWidth, realY+mTouchRegionWidth); if(rectRange.contains(x, y)){ selectIndex = i; break; } } if(selectIndex == -1){ return false; } curSelectPointList.clear(); curSelectPoint = controlPointList.get(selectIndex); switch (status){ case FREE: // 任意点拽动 curSelectPointList.add(curSelectPoint); break; case THREE: int offsetSeleIndex = (selectIndex + 1) % 12; int offsetRangeIndex = offsetSeleIndex / 3; if(offsetSeleIndex == 0){ curSelectPointList.add(controlPointList.get(11)); }else { curSelectPointList.add(controlPointList.get(offsetRangeIndex*3 - 1)); } curSelectPointList.add(controlPointList.get(offsetRangeIndex*3)); curSelectPointList.add(controlPointList.get(offsetRangeIndex*3 + 1)); break; case MIRROR_DIFF: case MIRROR_SAME: if(selectIndex==0 || selectIndex==6){ curSelectPointList.add(controlPointList.get(0)); curSelectPointList.add(controlPointList.get(6)); }else { curSelectPointList.add(controlPointList.get(selectIndex)); curSelectPointList.add(controlPointList.get(12 - selectIndex)); } break; } return true; } public void reset(){ calculateControlPoint(); invalidate(); } public void setStatus(Status status) { this.status = status; } /** * 设置比例--印象计算控制点因子 */ public void setRatio(float ratio) { this.mRatio = ratio; calculateControlPoint(); invalidate(); } public void setIsShowHelpLine(boolean isShowHelpLine) { this.mIsShowHelpLine = isShowHelpLine; invalidate(); } public List<PointF> getControlPointList() { return controlPointList; } /** * 计算圆的控制点 */ private void calculateControlPoint() { // 计算 中间控制点到端点的距离 float controlWidth = mRatio * mRadius; controlPointList.clear(); // 右上 controlPointList.add(new PointF(0, -mRadius)); controlPointList.add(new PointF(controlWidth, -mRadius)); controlPointList.add(new PointF(mRadius, -controlWidth)); // 右下 controlPointList.add(new PointF(mRadius, 0)); controlPointList.add(new PointF(mRadius, controlWidth)); controlPointList.add(new PointF(controlWidth, mRadius)); // 左下 controlPointList.add(new PointF(0, mRadius)); controlPointList.add(new PointF(-controlWidth, mRadius)); controlPointList.add(new PointF(-mRadius, controlWidth)); // 左上 controlPointList.add(new PointF(-mRadius, 0)); controlPointList.add(new PointF(-mRadius, -controlWidth)); controlPointList.add(new PointF(-controlWidth, -mRadius)); } public enum Status { FREE, // 自由拽动 THREE, // 三点拽动 MIRROR_DIFF, // 镜像异向 MIRROR_SAME, // 镜像同向 } }
11,858
0.565255
0.557224
338
32.890533
24.325514
107
false
false
0
0
0
0
0
0
0.713018
false
false
15
083b01bf184d90f12080d4508b659f6e07c0ac0b
34,557,306,899,371
f29829677fbf35a7fc3dcb3e4bf7da95a89f2f63
/base/src/main/java/com/synjones/base/bridge/SharedViewModel.java
f4d4f5cbcb28b0536dcaffe287e4a76a9049d5c3
[]
no_license
sutingshuai/xuepay_v2
https://github.com/sutingshuai/xuepay_v2
5ca102ec4a5e39beddda1d869b7f2f5a1000b2c5
35c3cfed27a516568f041d9dc05ac4aa7c7eab09
refs/heads/master
2020-08-11T15:55:13.459000
2020-04-16T06:53:42
2020-04-16T06:53:42
214,591,000
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.synjones.base.bridge; import android.gesture.Gesture; import com.synjones.base.Config.GestureCode; import com.synjones.base.Config.WebStatus; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; /** * Created by sutingshuai on 2019-11-27 * Describe: */ public class SharedViewModel extends ViewModel { /** * 中英文 * tips:需要在程序启动时判断它的值 */ public final MutableLiveData<Boolean> useEnglish = new MutableLiveData<>(); /** * 主题背景色 */ public final MutableLiveData<Integer> themeColor = new MutableLiveData<>(); /** * 控制是否切换到功能页 */ public final UnPeekLiveData<Boolean> isShowFunctionsPage = new UnPeekLiveData<>(); /** * 控制是否切换到用户页 */ public final UnPeekLiveData<Boolean> isShowAccountPage = new UnPeekLiveData<>(); /** * 控制是否切换到主页 */ public final UnPeekLiveData<Boolean> isShowHomePage = new UnPeekLiveData<>(); /** * 控制是否切换到设置页 */ public final UnPeekLiveData<Boolean> isShowSettingPage = new UnPeekLiveData<>(); /** * webview 加载状态 */ public final MutableLiveData<WebStatus> showWebStatus = new MutableLiveData<>(); /** * 是否在登录页登录成功 */ public final UnPeekLiveData<Boolean> Is_LoggedIn = new UnPeekLiveData<>(); public final MutableLiveData<Boolean> isVerificationPager = new MutableLiveData<>(); public final MutableLiveData<GestureCode> currentGestureVerCode = new MutableLiveData<>(); /** * 是否可以关闭测划 */ public final MutableLiveData<Boolean> isCanCloseSelectSchoolSide = new MutableLiveData<>(); /** * 关闭选学校的测滑 */ public final UnPeekLiveData<Boolean> closeSelectSchoolSide = new UnPeekLiveData<>(); /** * 展示等待状态 */ public final MutableLiveData<Boolean> showProgressDialog = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedSysVersion = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedSchoolConfig = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedBottomNavigation = new MutableLiveData<>(); public final UnPeekLiveData<String> authRespCode = new UnPeekLiveData<>(); public final MutableLiveData<Boolean> isMainPage = new MutableLiveData<>(); }
UTF-8
Java
2,494
java
SharedViewModel.java
Java
[ { "context": "t androidx.lifecycle.ViewModel;\n\n/**\n * Created by sutingshuai on 2019-11-27\n * Describe:\n */\npublic class Share", "end": 267, "score": 0.9994333982467651, "start": 256, "tag": "USERNAME", "value": "sutingshuai" } ]
null
[]
package com.synjones.base.bridge; import android.gesture.Gesture; import com.synjones.base.Config.GestureCode; import com.synjones.base.Config.WebStatus; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; /** * Created by sutingshuai on 2019-11-27 * Describe: */ public class SharedViewModel extends ViewModel { /** * 中英文 * tips:需要在程序启动时判断它的值 */ public final MutableLiveData<Boolean> useEnglish = new MutableLiveData<>(); /** * 主题背景色 */ public final MutableLiveData<Integer> themeColor = new MutableLiveData<>(); /** * 控制是否切换到功能页 */ public final UnPeekLiveData<Boolean> isShowFunctionsPage = new UnPeekLiveData<>(); /** * 控制是否切换到用户页 */ public final UnPeekLiveData<Boolean> isShowAccountPage = new UnPeekLiveData<>(); /** * 控制是否切换到主页 */ public final UnPeekLiveData<Boolean> isShowHomePage = new UnPeekLiveData<>(); /** * 控制是否切换到设置页 */ public final UnPeekLiveData<Boolean> isShowSettingPage = new UnPeekLiveData<>(); /** * webview 加载状态 */ public final MutableLiveData<WebStatus> showWebStatus = new MutableLiveData<>(); /** * 是否在登录页登录成功 */ public final UnPeekLiveData<Boolean> Is_LoggedIn = new UnPeekLiveData<>(); public final MutableLiveData<Boolean> isVerificationPager = new MutableLiveData<>(); public final MutableLiveData<GestureCode> currentGestureVerCode = new MutableLiveData<>(); /** * 是否可以关闭测划 */ public final MutableLiveData<Boolean> isCanCloseSelectSchoolSide = new MutableLiveData<>(); /** * 关闭选学校的测滑 */ public final UnPeekLiveData<Boolean> closeSelectSchoolSide = new UnPeekLiveData<>(); /** * 展示等待状态 */ public final MutableLiveData<Boolean> showProgressDialog = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedSysVersion = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedSchoolConfig = new MutableLiveData<>(); public final MutableLiveData<Boolean> updatedBottomNavigation = new MutableLiveData<>(); public final UnPeekLiveData<String> authRespCode = new UnPeekLiveData<>(); public final MutableLiveData<Boolean> isMainPage = new MutableLiveData<>(); }
2,494
0.691739
0.688261
89
24.842697
32.281731
95
false
false
0
0
0
0
0
0
0.269663
false
false
15
f7088d09973f811eb8eda97bd299504d5671ca9e
3,221,225,505,963
740e4b298bc3a1cba429e213b2266510b2eeb814
/src/main/java/fr/mjta/tenis/controller/PrepareMatchController.java
a7c019278b91e62b7d5d444ffeb84e43c288cf8b
[]
no_license
Ombrelin/efrei-m1-jakartaee-projet
https://github.com/Ombrelin/efrei-m1-jakartaee-projet
0a631c23e7fc060704c861a0af2ced4820fb67ff
d4fa97a6153ea85d2ea9f92fd7a7360dd8fe66c3
refs/heads/master
2023-03-29T10:36:51.921000
2020-12-21T20:26:41
2020-12-21T20:26:41
312,290,798
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.mjta.tenis.controller; import fr.mjta.tenis.domain.entities.Player; import fr.mjta.tenis.domain.entities.Referee; import fr.mjta.tenis.domain.services.MatchService; import fr.mjta.tenis.domain.services.PlayerService; import fr.mjta.tenis.domain.services.RefereeService; import fr.mjta.tenis.models.Result; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Objects; import java.util.Set; @WebServlet("/admin/prepareMatch") public class PrepareMatchController extends HttpServlet { @EJB private MatchService matchService; @EJB private PlayerService playerService; @EJB private RefereeService refereeService; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if((Objects.equals(request.getParameter("type"), "double") &&!Objects.equals(request.getParameter("team1player1"), "") && !Objects.equals(request.getParameter("team1player2"), "") && !Objects.equals(request.getParameter("team2player1"), "") && !Objects.equals(request.getParameter("team2player2"), "") && !Objects.equals(request.getParameter("referee"), ""))){ String team1player1 = request.getParameter("team1player1"); String team1player2 = request.getParameter("team1player2"); String team2player1 = request.getParameter("team2player1"); String team2player2 = request.getParameter("team2player2"); String refereeId = request.getParameter("referee"); String matchId = request.getParameter("matchId"); Player player1 = playerService.getById(team1player1); Player player2 = playerService.getById(team1player2); Player player3 = playerService.getById(team2player1); Player player4 = playerService.getById(team2player2); Set<Player> team1 = new HashSet<>(); Set<Player> team2 = new HashSet<>(); team1.add(player1); team1.add(player2); team2.add(player3); team2.add(player4); Referee referee = refereeService.getById(refereeId); try{ matchService.prepareMatch(matchId, team1, team2, referee); }catch (Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } }else if ((Objects.equals(request.getParameter("type"), "simple") &&!Objects.equals(request.getParameter("team1player1"), "") && !Objects.equals(request.getParameter("team2player1"), "") && !Objects.equals(request.getParameter("referee"), "") && !Objects.equals(request.getParameter("matchId"), ""))) { String team1player1 = request.getParameter("team1player1"); String team2player1 = request.getParameter("team2player1"); String refereeId = request.getParameter("referee"); String matchId = request.getParameter("matchId"); Player player1 = playerService.getById(team1player1); Player player2 = playerService.getById(team2player1); Set<Player> team1 = new HashSet<>(); Set<Player> team2 = new HashSet<>(); team1.add(player1); team2.add(player2); Referee referee = refereeService.getById(refereeId); try{ matchService.prepareMatch(matchId, team1, team2, referee); }catch (Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } } else{ request.setAttribute("result", "Failure"); } response.sendRedirect(request.getContextPath() +"/admin/consultMatches"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String matchId = request.getParameter("matchId"); try{ var match = matchService.getMatchToPrepare(matchId); request.setAttribute("match", match); request.setAttribute("players", playerService.getAll()); request.setAttribute("referees", refereeService.getAll()); this.getServletContext().getRequestDispatcher("/WEB-INF/prepareMatch.jsp").forward(request, response); } catch(Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } } }
UTF-8
Java
5,058
java
PrepareMatchController.java
Java
[]
null
[]
package fr.mjta.tenis.controller; import fr.mjta.tenis.domain.entities.Player; import fr.mjta.tenis.domain.entities.Referee; import fr.mjta.tenis.domain.services.MatchService; import fr.mjta.tenis.domain.services.PlayerService; import fr.mjta.tenis.domain.services.RefereeService; import fr.mjta.tenis.models.Result; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Objects; import java.util.Set; @WebServlet("/admin/prepareMatch") public class PrepareMatchController extends HttpServlet { @EJB private MatchService matchService; @EJB private PlayerService playerService; @EJB private RefereeService refereeService; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if((Objects.equals(request.getParameter("type"), "double") &&!Objects.equals(request.getParameter("team1player1"), "") && !Objects.equals(request.getParameter("team1player2"), "") && !Objects.equals(request.getParameter("team2player1"), "") && !Objects.equals(request.getParameter("team2player2"), "") && !Objects.equals(request.getParameter("referee"), ""))){ String team1player1 = request.getParameter("team1player1"); String team1player2 = request.getParameter("team1player2"); String team2player1 = request.getParameter("team2player1"); String team2player2 = request.getParameter("team2player2"); String refereeId = request.getParameter("referee"); String matchId = request.getParameter("matchId"); Player player1 = playerService.getById(team1player1); Player player2 = playerService.getById(team1player2); Player player3 = playerService.getById(team2player1); Player player4 = playerService.getById(team2player2); Set<Player> team1 = new HashSet<>(); Set<Player> team2 = new HashSet<>(); team1.add(player1); team1.add(player2); team2.add(player3); team2.add(player4); Referee referee = refereeService.getById(refereeId); try{ matchService.prepareMatch(matchId, team1, team2, referee); }catch (Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } }else if ((Objects.equals(request.getParameter("type"), "simple") &&!Objects.equals(request.getParameter("team1player1"), "") && !Objects.equals(request.getParameter("team2player1"), "") && !Objects.equals(request.getParameter("referee"), "") && !Objects.equals(request.getParameter("matchId"), ""))) { String team1player1 = request.getParameter("team1player1"); String team2player1 = request.getParameter("team2player1"); String refereeId = request.getParameter("referee"); String matchId = request.getParameter("matchId"); Player player1 = playerService.getById(team1player1); Player player2 = playerService.getById(team2player1); Set<Player> team1 = new HashSet<>(); Set<Player> team2 = new HashSet<>(); team1.add(player1); team2.add(player2); Referee referee = refereeService.getById(refereeId); try{ matchService.prepareMatch(matchId, team1, team2, referee); }catch (Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } } else{ request.setAttribute("result", "Failure"); } response.sendRedirect(request.getContextPath() +"/admin/consultMatches"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String matchId = request.getParameter("matchId"); try{ var match = matchService.getMatchToPrepare(matchId); request.setAttribute("match", match); request.setAttribute("players", playerService.getAll()); request.setAttribute("referees", refereeService.getAll()); this.getServletContext().getRequestDispatcher("/WEB-INF/prepareMatch.jsp").forward(request, response); } catch(Exception e){ request.setAttribute("errorMessage", e.getMessage()); this.getServletContext().getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response); } } }
5,058
0.653223
0.638592
112
44.160713
31.001888
122
false
false
0
0
0
0
0
0
0.857143
false
false
15
96633022421aaa55bc152e7a47f46a1e166703f6
34,102,040,368,117
611bfa0979ca4c26d250b024c3771e93a76f8c2e
/src/main/java/com/lcyzh/nmerp/service/TOutStockService.java
c36f5f85633449017ef326e85ad3609cce3b0d61
[]
no_license
LovingInJava/smErp
https://github.com/LovingInJava/smErp
6437cb235cfd87951179fbbb70e9803492e8de03
e1458464de7fbdbbc359345632a84b84dfe5d586
refs/heads/master
2020-06-13T23:37:36.867000
2019-07-02T07:31:56
2019-07-02T07:31:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lcyzh.nmerp.service; import com.lcyzh.nmerp.entity.TOutStock; import com.lcyzh.nmerp.model.vo.OutStockDetailVo; import com.lcyzh.nmerp.model.vo.OutStockVo; import java.util.List; /** * Author ljk * Date 2019-06-06 */ public interface TOutStockService { /** * @Description: 根据出库单查看 * @Param: [outCode] * @return: com.lcyzh.nmerp.entity.TOutStock * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ TOutStock findByOutCode(String outCode); /** * @Description: 根据订单号查看 * @Param: [ordCode] * @return: com.lcyzh.nmerp.entity.TOutStock * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ TOutStock findByOrdCode(String ordCode); /** * @Description: 多条件查询 * @Param: [tOutStock] * @return: java.util.List<com.lcyzh.nmerp.entity.TOutStock> * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ List<TOutStock> findList(TOutStock tOutStock); /** * @Description: 出库记录 * @Param: [vo] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:49 AM */ int insertStore(OutStockDetailVo vo); /** * @Description: 创建出库单并返回 * @Param: [applyUserId, remark] * @return: java.lang.String * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:47 AM */ String createAndReturnOutCode(Long applyUserId, String remark); /** * @Description: 更新出库信息 * @Param: [tOutStock] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:50 AM */ int update(OutStockVo tOutStock); /** * @Description: 删除出库记录:分三种,删除该入库单中的一条记录;或者删除一个订单的所有,或者删除整个出库单 * @Param: [vo] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:50 AM */ int delete(OutStockVo vo); }
UTF-8
Java
2,196
java
TOutStockService.java
Java
[ { "context": "ockVo;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * Author ljk\r\n * Date 2019-06-06\r\n */\r\npublic interface TOutS", "end": 220, "score": 0.9996660947799683, "start": 217, "tag": "USERNAME", "value": "ljk" }, { "context": " com.lcyzh.nmerp.entity.TOutStock\r\n ...
null
[]
package com.lcyzh.nmerp.service; import com.lcyzh.nmerp.entity.TOutStock; import com.lcyzh.nmerp.model.vo.OutStockDetailVo; import com.lcyzh.nmerp.model.vo.OutStockVo; import java.util.List; /** * Author ljk * Date 2019-06-06 */ public interface TOutStockService { /** * @Description: 根据出库单查看 * @Param: [outCode] * @return: com.lcyzh.nmerp.entity.TOutStock * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ TOutStock findByOutCode(String outCode); /** * @Description: 根据订单号查看 * @Param: [ordCode] * @return: com.lcyzh.nmerp.entity.TOutStock * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ TOutStock findByOrdCode(String ordCode); /** * @Description: 多条件查询 * @Param: [tOutStock] * @return: java.util.List<com.lcyzh.nmerp.entity.TOutStock> * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:48 AM */ List<TOutStock> findList(TOutStock tOutStock); /** * @Description: 出库记录 * @Param: [vo] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:49 AM */ int insertStore(OutStockDetailVo vo); /** * @Description: 创建出库单并返回 * @Param: [applyUserId, remark] * @return: java.lang.String * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:47 AM */ String createAndReturnOutCode(Long applyUserId, String remark); /** * @Description: 更新出库信息 * @Param: [tOutStock] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:50 AM */ int update(OutStockVo tOutStock); /** * @Description: 删除出库记录:分三种,删除该入库单中的一条记录;或者删除一个订单的所有,或者删除整个出库单 * @Param: [vo] * @return: int * @Author: lijinku * @Iteration : 1.0 * @Date: 2019/7/2 10:50 AM */ int delete(OutStockVo vo); }
2,196
0.560039
0.514764
85
21.905882
16.124969
67
false
false
0
0
0
0
0
0
0.164706
false
false
15
fc88e4262035681c28897cf922d2de040e4fd167
34,986,803,628,140
abc4371198896003dac9997ce23fad5a5f5c0bb5
/ArrestRecords.java
65ee0b6770b5944627ebdd56e0e588a2dcf08007
[]
no_license
KhashamKhan/PMS
https://github.com/KhashamKhan/PMS
23b98d602b996ee4e347d2f0d3840d6eaac93f0e
bdd849af6726329f649941e2338590bdff72ead7
refs/heads/master
2021-01-18T23:33:53.298000
2017-04-29T08:52:32
2017-04-29T08:52:32
87,116,503
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pms; public class ArrestRecords { public void arrestRecords(){ CustomerPanel cp = new CustomerPanel(); System.out.println("Enter ID# to see if the person is under arrest"); cp.userOptions(); } }
UTF-8
Java
221
java
ArrestRecords.java
Java
[]
null
[]
package pms; public class ArrestRecords { public void arrestRecords(){ CustomerPanel cp = new CustomerPanel(); System.out.println("Enter ID# to see if the person is under arrest"); cp.userOptions(); } }
221
0.692308
0.692308
9
22.555555
21.802708
71
false
false
0
0
0
0
0
0
1.333333
false
false
15
9c3d880b25350f5046c7bbb7e220b98bdd960109
34,127,810,175,209
263798d418bbd5d82821b9c9c448300745e93eb8
/src/main/java/com/mraof/minestuck/fluid/MSFluids.java
fd249a6450c2c90f31cfd401ed978688ec99ae6e
[]
no_license
mraof/Minestuck
https://github.com/mraof/Minestuck
f6a4a4afdd55d1ea606707b3c673c58a9b7c19e2
a949eb1ee6c93f7998a7008bf8e1d431fa9a0684
refs/heads/1.19
2023-08-31T15:37:08.978000
2023-07-22T22:09:53
2023-07-22T22:09:53
10,291,390
48
108
null
false
2023-09-10T03:50:51
2013-05-25T23:49:16
2023-06-11T20:51:22
2023-09-10T03:50:50
171,169
51
66
44
Java
false
false
package com.mraof.minestuck.fluid; import com.mraof.minestuck.Minestuck; import com.mraof.minestuck.block.MSBlocks; import com.mraof.minestuck.item.MSItems; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; import net.minecraftforge.fluids.FluidType; import net.minecraftforge.fluids.ForgeFlowingFluid; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Consumer; public final class MSFluids //TODO Set fluid type properties { public static final DeferredRegister<Fluid> REGISTER = DeferredRegister.create(ForgeRegistries.FLUIDS, Minestuck.MOD_ID); public static final DeferredRegister<FluidType> TYPE_REGISTER = DeferredRegister.create(ForgeRegistries.Keys.FLUID_TYPES, Minestuck.MOD_ID); public static final RegistryObject<FlowingFluid> OIL = REGISTER.register("oil", () -> new ForgeFlowingFluid.Source(MSFluids.OIL_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_OIL = REGISTER.register("flowing_oil", () -> new ForgeFlowingFluid.Flowing(MSFluids.OIL_PROPERTIES)); public static final RegistryObject<FluidType> OIL_TYPE = TYPE_REGISTER.register("oil", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_oil"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_oil"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties OIL_PROPERTIES = new ForgeFlowingFluid.Properties(OIL_TYPE, OIL, FLOWING_OIL).bucket(MSItems.OIL_BUCKET).block(MSBlocks.OIL).slopeFindDistance(3).explosionResistance(100F); public static final RegistryObject<FlowingFluid> LIGHT_WATER = REGISTER.register("light_water", () -> new ForgeFlowingFluid.Source(MSFluids.LIGHT_WATER_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_LIGHT_WATER = REGISTER.register("flowing_light_water", () -> new ForgeFlowingFluid.Flowing(MSFluids.LIGHT_WATER_PROPERTIES)); public static final RegistryObject<FluidType> LIGHT_WATER_TYPE = TYPE_REGISTER.register("light_water", () -> new FluidType(FluidType.Properties.create().canConvertToSource(true)){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_light_water"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_light_water"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties LIGHT_WATER_PROPERTIES = new ForgeFlowingFluid.Properties(LIGHT_WATER_TYPE, LIGHT_WATER, FLOWING_LIGHT_WATER).bucket(MSItems.LIGHT_WATER_BUCKET).block(MSBlocks.LIGHT_WATER).explosionResistance(100F); public static final RegistryObject<FlowingFluid> BLOOD = REGISTER.register("blood", () -> new ForgeFlowingFluid.Source(MSFluids.BLOOD_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_BLOOD = REGISTER.register("flowing_blood", () -> new ForgeFlowingFluid.Flowing(MSFluids.BLOOD_PROPERTIES)); public static final RegistryObject<FluidType> BLOOD_TYPE = TYPE_REGISTER.register("blood", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_blood"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_blood"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties BLOOD_PROPERTIES = new ForgeFlowingFluid.Properties(BLOOD_TYPE, BLOOD, FLOWING_BLOOD).bucket(MSItems.BLOOD_BUCKET).block(MSBlocks.BLOOD).explosionResistance(100F); public static final RegistryObject<FlowingFluid> BRAIN_JUICE = REGISTER.register("brain_juice", () -> new ForgeFlowingFluid.Source(MSFluids.BRAIN_JUICE_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_BRAIN_JUICE = REGISTER.register("flowing_brain_juice", () -> new ForgeFlowingFluid.Flowing(MSFluids.BRAIN_JUICE_PROPERTIES)); public static final RegistryObject<FluidType> BRAIN_JUICE_TYPE = TYPE_REGISTER.register("brain_juice", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_brain_juice"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_brain_juice"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties BRAIN_JUICE_PROPERTIES = new ForgeFlowingFluid.Properties(BRAIN_JUICE_TYPE, BRAIN_JUICE, FLOWING_BRAIN_JUICE).bucket(MSItems.BRAIN_JUICE_BUCKET).block(MSBlocks.BRAIN_JUICE).explosionResistance(100F); public static final RegistryObject<FlowingFluid> WATER_COLORS = REGISTER.register("water_colors", () -> new ForgeFlowingFluid.Source(MSFluids.WATER_COLORS_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_WATER_COLORS = REGISTER.register("flowing_water_colors", () -> new ForgeFlowingFluid.Flowing(MSFluids.WATER_COLORS_PROPERTIES)); public static final RegistryObject<FluidType> WATER_COLORS_TYPE = TYPE_REGISTER.register("water_colors", () -> new FluidType(FluidType.Properties.create().canConvertToSource(true)){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_water_colors"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_water_colors"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties WATER_COLORS_PROPERTIES = new ForgeFlowingFluid.Properties(WATER_COLORS_TYPE, WATER_COLORS, FLOWING_WATER_COLORS).bucket(MSItems.WATER_COLORS_BUCKET).block(MSBlocks.WATER_COLORS).explosionResistance(100F); public static final RegistryObject<FlowingFluid> ENDER = REGISTER.register("ender", () -> new ForgeFlowingFluid.Source(MSFluids.ENDER_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_ENDER = REGISTER.register("flowing_ender", () -> new ForgeFlowingFluid.Flowing(MSFluids.ENDER_PROPERTIES)); public static final RegistryObject<FluidType> ENDER_TYPE = TYPE_REGISTER.register("ender", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_ender"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_ender"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties ENDER_PROPERTIES = new ForgeFlowingFluid.Properties(ENDER_TYPE, ENDER, FLOWING_ENDER).bucket(MSItems.ENDER_BUCKET).block(MSBlocks.ENDER).slopeFindDistance(2).levelDecreasePerBlock(2).explosionResistance(100F); }
UTF-8
Java
9,115
java
MSFluids.java
Java
[]
null
[]
package com.mraof.minestuck.fluid; import com.mraof.minestuck.Minestuck; import com.mraof.minestuck.block.MSBlocks; import com.mraof.minestuck.item.MSItems; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.material.FlowingFluid; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; import net.minecraftforge.fluids.FluidType; import net.minecraftforge.fluids.ForgeFlowingFluid; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Consumer; public final class MSFluids //TODO Set fluid type properties { public static final DeferredRegister<Fluid> REGISTER = DeferredRegister.create(ForgeRegistries.FLUIDS, Minestuck.MOD_ID); public static final DeferredRegister<FluidType> TYPE_REGISTER = DeferredRegister.create(ForgeRegistries.Keys.FLUID_TYPES, Minestuck.MOD_ID); public static final RegistryObject<FlowingFluid> OIL = REGISTER.register("oil", () -> new ForgeFlowingFluid.Source(MSFluids.OIL_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_OIL = REGISTER.register("flowing_oil", () -> new ForgeFlowingFluid.Flowing(MSFluids.OIL_PROPERTIES)); public static final RegistryObject<FluidType> OIL_TYPE = TYPE_REGISTER.register("oil", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_oil"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_oil"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties OIL_PROPERTIES = new ForgeFlowingFluid.Properties(OIL_TYPE, OIL, FLOWING_OIL).bucket(MSItems.OIL_BUCKET).block(MSBlocks.OIL).slopeFindDistance(3).explosionResistance(100F); public static final RegistryObject<FlowingFluid> LIGHT_WATER = REGISTER.register("light_water", () -> new ForgeFlowingFluid.Source(MSFluids.LIGHT_WATER_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_LIGHT_WATER = REGISTER.register("flowing_light_water", () -> new ForgeFlowingFluid.Flowing(MSFluids.LIGHT_WATER_PROPERTIES)); public static final RegistryObject<FluidType> LIGHT_WATER_TYPE = TYPE_REGISTER.register("light_water", () -> new FluidType(FluidType.Properties.create().canConvertToSource(true)){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_light_water"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_light_water"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties LIGHT_WATER_PROPERTIES = new ForgeFlowingFluid.Properties(LIGHT_WATER_TYPE, LIGHT_WATER, FLOWING_LIGHT_WATER).bucket(MSItems.LIGHT_WATER_BUCKET).block(MSBlocks.LIGHT_WATER).explosionResistance(100F); public static final RegistryObject<FlowingFluid> BLOOD = REGISTER.register("blood", () -> new ForgeFlowingFluid.Source(MSFluids.BLOOD_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_BLOOD = REGISTER.register("flowing_blood", () -> new ForgeFlowingFluid.Flowing(MSFluids.BLOOD_PROPERTIES)); public static final RegistryObject<FluidType> BLOOD_TYPE = TYPE_REGISTER.register("blood", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_blood"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_blood"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties BLOOD_PROPERTIES = new ForgeFlowingFluid.Properties(BLOOD_TYPE, BLOOD, FLOWING_BLOOD).bucket(MSItems.BLOOD_BUCKET).block(MSBlocks.BLOOD).explosionResistance(100F); public static final RegistryObject<FlowingFluid> BRAIN_JUICE = REGISTER.register("brain_juice", () -> new ForgeFlowingFluid.Source(MSFluids.BRAIN_JUICE_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_BRAIN_JUICE = REGISTER.register("flowing_brain_juice", () -> new ForgeFlowingFluid.Flowing(MSFluids.BRAIN_JUICE_PROPERTIES)); public static final RegistryObject<FluidType> BRAIN_JUICE_TYPE = TYPE_REGISTER.register("brain_juice", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_brain_juice"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_brain_juice"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties BRAIN_JUICE_PROPERTIES = new ForgeFlowingFluid.Properties(BRAIN_JUICE_TYPE, BRAIN_JUICE, FLOWING_BRAIN_JUICE).bucket(MSItems.BRAIN_JUICE_BUCKET).block(MSBlocks.BRAIN_JUICE).explosionResistance(100F); public static final RegistryObject<FlowingFluid> WATER_COLORS = REGISTER.register("water_colors", () -> new ForgeFlowingFluid.Source(MSFluids.WATER_COLORS_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_WATER_COLORS = REGISTER.register("flowing_water_colors", () -> new ForgeFlowingFluid.Flowing(MSFluids.WATER_COLORS_PROPERTIES)); public static final RegistryObject<FluidType> WATER_COLORS_TYPE = TYPE_REGISTER.register("water_colors", () -> new FluidType(FluidType.Properties.create().canConvertToSource(true)){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_water_colors"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_water_colors"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties WATER_COLORS_PROPERTIES = new ForgeFlowingFluid.Properties(WATER_COLORS_TYPE, WATER_COLORS, FLOWING_WATER_COLORS).bucket(MSItems.WATER_COLORS_BUCKET).block(MSBlocks.WATER_COLORS).explosionResistance(100F); public static final RegistryObject<FlowingFluid> ENDER = REGISTER.register("ender", () -> new ForgeFlowingFluid.Source(MSFluids.ENDER_PROPERTIES)); public static final RegistryObject<FlowingFluid> FLOWING_ENDER = REGISTER.register("flowing_ender", () -> new ForgeFlowingFluid.Flowing(MSFluids.ENDER_PROPERTIES)); public static final RegistryObject<FluidType> ENDER_TYPE = TYPE_REGISTER.register("ender", () -> new FluidType(FluidType.Properties.create()){ @Override public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) { consumer.accept(new IClientFluidTypeExtensions() { public static final ResourceLocation STILL_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/still_ender"); public static final ResourceLocation FLOWING_TEXTURE = new ResourceLocation(Minestuck.MOD_ID, "block/flowing_ender"); @Override public ResourceLocation getStillTexture() { return STILL_TEXTURE; } @Override public ResourceLocation getFlowingTexture() { return FLOWING_TEXTURE; } }); } }); public static final ForgeFlowingFluid.Properties ENDER_PROPERTIES = new ForgeFlowingFluid.Properties(ENDER_TYPE, ENDER, FLOWING_ENDER).bucket(MSItems.ENDER_BUCKET).block(MSBlocks.ENDER).slopeFindDistance(2).levelDecreasePerBlock(2).explosionResistance(100F); }
9,115
0.776303
0.773999
175
51.091427
63.798458
259
false
false
0
0
0
0
0
0
3.188571
false
false
15
1a44b8ce4c1ebb659a1d41119b62a78b78110cc6
35,244,501,664,341
171c0651d0216b6be7bde899bdc4fa01206bd1ba
/sssm_service/src/main/java/com/ruixun/service/UserService.java
212c8ee12ac7c1da03366a3c1235a48c68e5ad96
[]
no_license
hellosuitao/mysssm
https://github.com/hellosuitao/mysssm
a0921fa03163dddce0bee8e57f6b68025d0e57ad
9af0a4f7cb1c874aa8e1bfbd946b21a79ed9c979
refs/heads/master
2022-12-20T10:13:15.404000
2019-10-19T02:14:43
2019-10-19T02:14:43
216,136,258
0
0
null
false
2022-12-16T05:04:50
2019-10-19T02:10:48
2019-10-19T02:15:52
2022-12-16T05:04:48
35,818
0
0
10
Java
false
false
package com.ruixun.service; import com.ruixun.entity.UserInfo; import org.springframework.security.core.userdetails.UserDetailsService; import java.util.List; public interface UserService extends UserDetailsService { public List<UserInfo> findAll() throws Exception; }
UTF-8
Java
277
java
UserService.java
Java
[]
null
[]
package com.ruixun.service; import com.ruixun.entity.UserInfo; import org.springframework.security.core.userdetails.UserDetailsService; import java.util.List; public interface UserService extends UserDetailsService { public List<UserInfo> findAll() throws Exception; }
277
0.815884
0.815884
11
24.181818
25.54788
72
false
false
0
0
0
0
0
0
0.454545
false
false
15
9bb0774b0852e592126f94896bf632bcce86fa56
36,833,639,547,080
a5b39df8c447620f996073c4dbde3fe8db5c8bb3
/day02_静态、继承、模板设计模式、抽象类、final/src/com/itheima/demo15_抽象类的注意事项/Test.java
75a97aa31b90c8119ed23fe8902159fc5f004355
[]
no_license
xiaozhi1218/javaee
https://github.com/xiaozhi1218/javaee
b6a72fee7e7145f577732c85b167fe65bc4dc6e4
b12496c77f450e20d6b75454c991c8106589269c
refs/heads/main
2021-12-03T12:13:08.620000
2021-12-01T06:59:57
2021-12-01T06:59:57
198,920,540
1
0
null
false
2021-04-22T18:29:28
2019-07-26T00:49:52
2020-02-23T07:50:53
2021-04-22T18:29:28
70,699
1
0
11
TSQL
false
false
package com.itheima.demo15_抽象类的注意事项; /** * @Author:pengzhilin * @Date: 2020/9/6 15:00 */ abstract class Animal{ private String name; private int age; public Animal() { } public Animal(String name, int age) { this.name = name; this.age = age; } public void show(){ System.out.println(name+","+age); } // 抽象类没有抽象方法 } class Dog extends Animal{ public Dog() { super(); } public Dog(String name, int age) { super(name, age); } } abstract class Person{ // 抽象方法 public abstract void eat(); public abstract void drink(); } //普通子类继承抽象类后,必须重写抽象类中所有的抽象方法 class Student extends Person{ @Override public void eat() { // ... } @Override public void drink() { // ... } } //抽象子类继承抽象类后,可以不用重写抽象类中的抽象方法 abstract class Teacher extends Person{ @Override public void eat() { // ... 可以重写... } } public class Test { public static void main(String[] args) { /* 抽象类的注意事项: - 抽象类不能被创建对象,就是用来做“父类”,被子类继承的。 - 抽象类不能被创建对象,但可以有“构造方法”——为成员变量初始化。 - 抽象类中可以没有抽象方法,但抽象方法必须定义在抽象类中(抽象类中不一定有抽象方法,但抽象方法一定在抽象类中) - 子类继承抽象类后,必须重写抽象类中所有的抽象方法,否则子类必须也是一个抽象类 */ // 抽象类不能被创建对象,就是用来做“父类”,被子类继承的。 //Animal anl = new Animal(); // 抽象类不能被创建对象,但可以有“构造方法”——为成员变量初始化。 Dog d = new Dog("旺财", 2); d.show();// 旺财,2 } }
UTF-8
Java
2,055
java
Test.java
Java
[ { "context": "kage com.itheima.demo15_抽象类的注意事项;\n\n/**\n * @Author:pengzhilin\n * @Date: 2020/9/6 15:00\n */\nabstract class Anima", "end": 63, "score": 0.9897829294204712, "start": 53, "tag": "USERNAME", "value": "pengzhilin" } ]
null
[]
package com.itheima.demo15_抽象类的注意事项; /** * @Author:pengzhilin * @Date: 2020/9/6 15:00 */ abstract class Animal{ private String name; private int age; public Animal() { } public Animal(String name, int age) { this.name = name; this.age = age; } public void show(){ System.out.println(name+","+age); } // 抽象类没有抽象方法 } class Dog extends Animal{ public Dog() { super(); } public Dog(String name, int age) { super(name, age); } } abstract class Person{ // 抽象方法 public abstract void eat(); public abstract void drink(); } //普通子类继承抽象类后,必须重写抽象类中所有的抽象方法 class Student extends Person{ @Override public void eat() { // ... } @Override public void drink() { // ... } } //抽象子类继承抽象类后,可以不用重写抽象类中的抽象方法 abstract class Teacher extends Person{ @Override public void eat() { // ... 可以重写... } } public class Test { public static void main(String[] args) { /* 抽象类的注意事项: - 抽象类不能被创建对象,就是用来做“父类”,被子类继承的。 - 抽象类不能被创建对象,但可以有“构造方法”——为成员变量初始化。 - 抽象类中可以没有抽象方法,但抽象方法必须定义在抽象类中(抽象类中不一定有抽象方法,但抽象方法一定在抽象类中) - 子类继承抽象类后,必须重写抽象类中所有的抽象方法,否则子类必须也是一个抽象类 */ // 抽象类不能被创建对象,就是用来做“父类”,被子类继承的。 //Animal anl = new Animal(); // 抽象类不能被创建对象,但可以有“构造方法”——为成员变量初始化。 Dog d = new Dog("旺财", 2); d.show();// 旺财,2 } }
2,055
0.552147
0.542604
82
16.890244
15.536743
68
false
false
0
0
0
0
0
0
0.304878
false
false
15
79e866f73e5f05d512720d7801fb5a594854ec04
37,082,747,647,992
6ef54cf0016edbbcfec9d4ef257eaf02a3927a0f
/src/main/java/com/ddc/service/UserService.java
03dfeffffe62a121877b32b546a26b53b424ff29
[]
no_license
sam-dxs/springMvc04
https://github.com/sam-dxs/springMvc04
5e1bee73a7b7e46bdc33c04f5de9a730c9394133
4f85fb1607146425f4bd34096c831de05d77294f
refs/heads/master
2020-04-06T13:48:07.056000
2018-11-16T00:08:18
2018-11-16T00:08:18
157,515,191
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ddc.service; import com.ddc.model.User; public interface UserService { User selectUserById(Integer userId); }
UTF-8
Java
129
java
UserService.java
Java
[]
null
[]
package com.ddc.service; import com.ddc.model.User; public interface UserService { User selectUserById(Integer userId); }
129
0.75969
0.75969
7
17.571428
15.837182
42
false
false
0
0
0
0
0
0
0.428571
false
false
15
e1778a358df21a3373f811f7d87a2ff5254ae9c8
3,513,283,309,607
1b28e293d6c89d37d6a6daac70279d1b64deacc7
/Notas/app/src/main/java/com/example/notas/models/NotasDao.java
5e194c1d6748879414c123824935c49f5d9dc093
[]
no_license
marcelom1/DDM054705
https://github.com/marcelom1/DDM054705
aec60f89f22c99dbf5f55409df2bac4dceac452a
fe14ba09ca19a68438d9436be7dde4c905281f25
refs/heads/master
2021-01-06T20:09:52.129000
2020-10-12T15:47:07
2020-10-12T15:47:07
241,473,982
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.notas.models; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.notas.models.Nota; import java.util.ArrayList; public class NotasDao { Context mContext; SQLiteDatabase meudb; public NotasDao(Context mContext) { this.mContext = mContext; meudb = mContext.openOrCreateDatabase("bdNotas", mContext.MODE_PRIVATE, null); meudb.execSQL("CREATE TABLE IF NOT EXISTS notas(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT ," + "text vachar);"); } public void insertNotas(Nota notas){ ContentValues notasValores = new ContentValues(); notasValores.put("text", notas.getText()); meudb.insert("notas", null, notasValores); } public void atualizaNotas(Nota notas){ ContentValues notasValores = new ContentValues(); notasValores.put("text", notas.getText()); meudb.update("notas", notasValores,"_id="+ notas.getId(),null); } public ArrayList<Nota> getAll(){ Cursor dataset = meudb.rawQuery("SELECT * FROM notas ", null); dataset.moveToFirst(); ArrayList<Nota> ListaNotas = new ArrayList<>(); while (!dataset.isAfterLast()){ int id = dataset.getInt(dataset.getColumnIndex("_id")); String text = dataset.getString(dataset.getColumnIndex("text")); ListaNotas.add(new Nota(id,text)); dataset.moveToNext(); } return ListaNotas; } public Nota getNota(int id){ String[] whereArgs = { String.valueOf(id) }; Cursor dataset = meudb.rawQuery("SELECT * FROM notas WHERE _id = ?", whereArgs); dataset.moveToFirst(); String text = dataset.getString(dataset.getColumnIndex("text")); Nota retorno = new Nota(id, text); return retorno; } public void dropNota(int id){ meudb.delete("notas","_id="+id,null); } }
UTF-8
Java
2,046
java
NotasDao.java
Java
[]
null
[]
package com.example.notas.models; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.notas.models.Nota; import java.util.ArrayList; public class NotasDao { Context mContext; SQLiteDatabase meudb; public NotasDao(Context mContext) { this.mContext = mContext; meudb = mContext.openOrCreateDatabase("bdNotas", mContext.MODE_PRIVATE, null); meudb.execSQL("CREATE TABLE IF NOT EXISTS notas(" + "_id INTEGER PRIMARY KEY AUTOINCREMENT ," + "text vachar);"); } public void insertNotas(Nota notas){ ContentValues notasValores = new ContentValues(); notasValores.put("text", notas.getText()); meudb.insert("notas", null, notasValores); } public void atualizaNotas(Nota notas){ ContentValues notasValores = new ContentValues(); notasValores.put("text", notas.getText()); meudb.update("notas", notasValores,"_id="+ notas.getId(),null); } public ArrayList<Nota> getAll(){ Cursor dataset = meudb.rawQuery("SELECT * FROM notas ", null); dataset.moveToFirst(); ArrayList<Nota> ListaNotas = new ArrayList<>(); while (!dataset.isAfterLast()){ int id = dataset.getInt(dataset.getColumnIndex("_id")); String text = dataset.getString(dataset.getColumnIndex("text")); ListaNotas.add(new Nota(id,text)); dataset.moveToNext(); } return ListaNotas; } public Nota getNota(int id){ String[] whereArgs = { String.valueOf(id) }; Cursor dataset = meudb.rawQuery("SELECT * FROM notas WHERE _id = ?", whereArgs); dataset.moveToFirst(); String text = dataset.getString(dataset.getColumnIndex("text")); Nota retorno = new Nota(id, text); return retorno; } public void dropNota(int id){ meudb.delete("notas","_id="+id,null); } }
2,046
0.63392
0.63392
71
27.816902
25.136421
88
false
false
0
0
0
0
0
0
0.704225
false
false
15
5278cf8ecfe8933f512a2ad7bdaaeb20bc2c2bee
4,604,205,002,640
f2555e1cf20a8e7228fa3525e278c363e98806b5
/PR3/Test/pr01/ListaDeReproduccionTest.java
7a77968e242720a9dd8b1b87938dce6cd982fc99
[]
no_license
unaaimendi/PR3
https://github.com/unaaimendi/PR3
58c5bd5f9ca49e393c0d92af0e48c7f878a99586
71ba04ef48e74a5d83f117f91b7f19e4ae3be0b3
refs/heads/master
2020-08-01T01:51:47.998000
2019-11-29T07:21:29
2019-11-29T07:21:29
210,818,883
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pr01; import static org.junit.Assert.*; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ListaDeReproduccionTest { private ListaDeReproduccion lr1; private ListaDeReproduccion lr2; private final File FIC_TEST1 = new File("test/res/No del grupo.mp4"); private final File FIC_TEST2 = new File("test/res/Fichero Pentatoniz no video.txt"); @Before public void setUp() throws Exception { lr1 = new ListaDeReproduccion(); lr2 = new ListaDeReproduccion(); lr2.add(FIC_TEST1); } @After public void tearDown() { lr2.clear(); } // Chequeo de error por getFic(índice) por encima de final @Test(expected = IndexOutOfBoundsException.class) public void testGet_Exc1() { lr1.getFic(0); // Debe dar error porque aún no existe la posición 0 } // Chequeo de error por get(índice) por debajo de 0 @Test(expected = IndexOutOfBoundsException.class) public void testGet_Exc2() { lr2.getFic(-1); // Debe dar error porque aún no existe la posición -1 } // Chequeo de funcionamiento correcto de get(índice) @Test public void testGet() { assertEquals( FIC_TEST1, lr2.getFic(0) ); // El único dato es el fic-test1 } @Test public void addRemoveTest() { lr1.add(FIC_TEST1); assertEquals(lr2.getSize(), lr1.getSize()); assertEquals(1, lr2.getSize()); lr1.removeFic(0); lr2.removeFic(0); assertEquals(lr2.getSize(), lr1.getSize()); assertEquals(0, lr2.getSize()); } @Test public void sizeTest() { assertEquals( lr1.getSize(), lr2.getSize()-1); } @Test public void intercambiaTest() { lr1.add(FIC_TEST1); lr1.add(FIC_TEST2); lr1.intercambia(0, 1); assertEquals(FIC_TEST2, lr1.getFic(0)); } }
ISO-8859-1
Java
1,827
java
ListaDeReproduccionTest.java
Java
[]
null
[]
package pr01; import static org.junit.Assert.*; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.Test; public class ListaDeReproduccionTest { private ListaDeReproduccion lr1; private ListaDeReproduccion lr2; private final File FIC_TEST1 = new File("test/res/No del grupo.mp4"); private final File FIC_TEST2 = new File("test/res/Fichero Pentatoniz no video.txt"); @Before public void setUp() throws Exception { lr1 = new ListaDeReproduccion(); lr2 = new ListaDeReproduccion(); lr2.add(FIC_TEST1); } @After public void tearDown() { lr2.clear(); } // Chequeo de error por getFic(índice) por encima de final @Test(expected = IndexOutOfBoundsException.class) public void testGet_Exc1() { lr1.getFic(0); // Debe dar error porque aún no existe la posición 0 } // Chequeo de error por get(índice) por debajo de 0 @Test(expected = IndexOutOfBoundsException.class) public void testGet_Exc2() { lr2.getFic(-1); // Debe dar error porque aún no existe la posición -1 } // Chequeo de funcionamiento correcto de get(índice) @Test public void testGet() { assertEquals( FIC_TEST1, lr2.getFic(0) ); // El único dato es el fic-test1 } @Test public void addRemoveTest() { lr1.add(FIC_TEST1); assertEquals(lr2.getSize(), lr1.getSize()); assertEquals(1, lr2.getSize()); lr1.removeFic(0); lr2.removeFic(0); assertEquals(lr2.getSize(), lr1.getSize()); assertEquals(0, lr2.getSize()); } @Test public void sizeTest() { assertEquals( lr1.getSize(), lr2.getSize()-1); } @Test public void intercambiaTest() { lr1.add(FIC_TEST1); lr1.add(FIC_TEST2); lr1.intercambia(0, 1); assertEquals(FIC_TEST2, lr1.getFic(0)); } }
1,827
0.664651
0.636064
70
23.985714
22.163349
85
false
false
0
0
0
0
0
0
1.542857
false
false
15
eda050dcf0d15559c629928e51f035a36841d799
38,139,309,608,137
e5f2941065d63c572a02cf9cde38536b781ea6d2
/src/main/java/builder/carBuilderExample/CarBuilder.java
d927e74a98dcfc225f8095f7ad5c39d13a968d5c
[]
no_license
michalnormann/Design-Patterns
https://github.com/michalnormann/Design-Patterns
1bed7d0f2a9004f5a0a2e16bc1b8cceea90fc5dd
3b4bd87917fb48a0f6714d43147013f8423ae2e7
refs/heads/master
2020-06-17T10:11:15.507000
2020-03-21T15:00:58
2020-03-21T15:00:58
195,892,654
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package builder.carBuilderExample; public class CarBuilder { private Car car; public CarBuilder() { car = new Car(); } public CarBuilder withMark(String mark) { car.setMark(mark); return this; } public CarBuilder withModel(String model) { car.setModel(model); return this; } public CarBuilder withEngine(Engine engine) { car.setEngine(engine); return this; } public CarBuilder withYearOfProduction(int yearOfProduction) { car.setYearOfProduction(yearOfProduction); return this; } public CarBuilder withColour(String colour) { car.setColour(colour); return this; } public Car build() { return car; } }
UTF-8
Java
765
java
CarBuilder.java
Java
[]
null
[]
package builder.carBuilderExample; public class CarBuilder { private Car car; public CarBuilder() { car = new Car(); } public CarBuilder withMark(String mark) { car.setMark(mark); return this; } public CarBuilder withModel(String model) { car.setModel(model); return this; } public CarBuilder withEngine(Engine engine) { car.setEngine(engine); return this; } public CarBuilder withYearOfProduction(int yearOfProduction) { car.setYearOfProduction(yearOfProduction); return this; } public CarBuilder withColour(String colour) { car.setColour(colour); return this; } public Car build() { return car; } }
765
0.611765
0.611765
39
18.641026
17.610439
66
false
false
0
0
0
0
0
0
0.358974
false
false
15
7fa66f09fa0a2e693bd8efbf2b34f8ee6e77cc10
39,092,792,328,272
4f2c6bcd1b17353530fe2b571487c309a9dd15b3
/src/main/java/text/Studen.java
0aaa70debe750e7d73ed698dd9a79edc821d3183
[ "MIT" ]
permissive
xHadoop/base-admin
https://github.com/xHadoop/base-admin
8d210a885fa77376198533b97498ca2f722213e8
d2ac364e22679ba8a2ddf14d6b77e98fdd26c458
refs/heads/master
2022-12-04T08:46:51.912000
2020-08-30T17:34:58
2020-08-30T17:34:58
291,520,040
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package text; public class Studen { public String name; private Integer age; public Integer getAge() { return age; } public Studen(String name, Integer age) { this.name = name; this.age = age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Studen{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
UTF-8
Java
492
java
Studen.java
Java
[]
null
[]
package text; public class Studen { public String name; private Integer age; public Integer getAge() { return age; } public Studen(String name, Integer age) { this.name = name; this.age = age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Studen{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
492
0.473577
0.473577
28
16.571428
13.594717
45
false
false
0
0
0
0
0
0
0.357143
false
false
15
87775c32795b46ca9886331cec51a15d67b788ca
558,345,819,594
7958af25ed9839e45ca0145499cd642ce280936f
/Paginize-master/actvieandroid/src/main/java/com/yuanyukun/activeandroid/Page/JsonRequestPage.java
7edb857cbed37d3aa2764c4c71d2776d184781ab
[ "MIT" ]
permissive
yuanyukun/PaginizeDemo
https://github.com/yuanyukun/PaginizeDemo
1699bc06a9cee45c455323cbbe3ce4e99de3ffc6
6cb0f076478e5b8e10a6f135cf02a47f1333747b
refs/heads/master
2016-08-08T19:12:24.642000
2016-02-02T08:33:10
2016-02-02T08:33:10
50,100,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yuanyukun.activeandroid.Page; import net.neevek.android.lib.paginize.PageActivity; /** * Created by yuanyukun on 2016/1/27. */ public class JsonRequestPage extends BasePage { public JsonRequestPage(PageActivity pageActivity) { super(pageActivity); setNextBtnHide(true); setTitle("JsonRequest"); } }
UTF-8
Java
349
java
JsonRequestPage.java
Java
[ { "context": "roid.lib.paginize.PageActivity;\n\n/**\n * Created by yuanyukun on 2016/1/27.\n */\npublic class JsonRequestPage ex", "end": 125, "score": 0.9995969533920288, "start": 116, "tag": "USERNAME", "value": "yuanyukun" } ]
null
[]
package com.yuanyukun.activeandroid.Page; import net.neevek.android.lib.paginize.PageActivity; /** * Created by yuanyukun on 2016/1/27. */ public class JsonRequestPage extends BasePage { public JsonRequestPage(PageActivity pageActivity) { super(pageActivity); setNextBtnHide(true); setTitle("JsonRequest"); } }
349
0.710602
0.690544
16
20.8125
20.540262
55
false
false
0
0
0
0
0
0
0.3125
false
false
15
2584b28d190d863413a80fd6ea5289ee29372293
25,486,335,987,242
7c8d3655edf7ccbaf007a59a9879357e64a85747
/EventBooking/src/main/java/CommonLibs/NadaEMailService.java
daa562a743cf64116913477e9bcee9d34ded657c
[]
no_license
sanradiancewebauto/eventenergies
https://github.com/sanradiancewebauto/eventenergies
b62bca7e3e6c1bb7d0a05e62f36cb4c492042d5c
e24ab8c4eae475cc7ed026d86ae7e91f99462083
refs/heads/master
2022-11-26T15:44:08.230000
2020-02-15T05:53:09
2020-02-15T05:53:09
217,196,764
0
0
null
false
2022-11-16T09:51:37
2019-10-24T02:44:02
2020-02-15T05:53:13
2022-11-16T09:51:34
10,424
0
0
8
Java
false
false
package CommonLibs; import java.io.IOException; import java.util.Objects; import org.apache.commons.lang.RandomStringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class NadaEMailService { static Logger log = LogManager.getLogger(ConditionChecks.class.getName()); private static final String NADA_EMAIL_DOMAIN = "@getnada.com"; private static final String INBOX_MESSAGE_KEY_NAME = "msgs"; private static final String EMAIL_ID_ROUTE_PARAM = "email-id"; private static final int EMAIL_CHARS_LENGTH = 10; private static final int PASSWORD_CHARS_LENGTH = 10; private String emailId; private String password; String msgId; private void generateEmailId(){ this.emailId = RandomStringUtils.randomAlphanumeric(EMAIL_CHARS_LENGTH).toLowerCase().concat(NADA_EMAIL_DOMAIN); } private void generatePassword(){ this.password = RandomStringUtils.randomAlphanumeric(PASSWORD_CHARS_LENGTH); } //generates a random email for the first time. //call reset for a new random email public String getEmailId(){ if(Objects.isNull(this.emailId)){ this.generateEmailId(); } return this.emailId; } public String getPassword(){ if(Objects.isNull(this.password)){ this.generatePassword(); } return this.password; } //to re-generate a new random email id public void reset(){ this.emailId = null; } public String initMailID(String mailID) throws JSONException, UnirestException, JsonParseException, JsonMappingException, IOException { log.info("Initializing the autogenerated Email Id : [{}]",mailID); Unirest.get("https://getnada.com/api/v1/inboxes/{email-id}") .routeParam(EMAIL_ID_ROUTE_PARAM, mailID) .asJson() .getBody() .getObject() .getJSONArray(INBOX_MESSAGE_KEY_NAME); return mailID; } public Boolean readMessages(String mailID) throws JsonParseException, JsonMappingException, UnirestException, IOException { Boolean msgStatus = null; JSONArray jsonResponseMsgs = Unirest.get("https://getnada.com/api/v1/inboxes/{email-id}") .routeParam(EMAIL_ID_ROUTE_PARAM, mailID) .asJson() .getBody() .getObject() .getJSONArray(INBOX_MESSAGE_KEY_NAME); int i = 0; if (jsonResponseMsgs != null && jsonResponseMsgs.length() > 0) { while(i < jsonResponseMsgs.length()) { String msgId = jsonResponseMsgs.getJSONObject(i).optString("uid"); log.info("Captured message ID is [{}]", msgId); JSONObject messageDetails = getMessageById(msgId); if ((messageDetails.get("fe").equals("admin@eventenergies.com")) && (messageDetails.get("s").equals("You are Singed-up. Here is your Email Confirmation link"))){ String messageHTML = (String) messageDetails.get("html"); Document doc = Jsoup.parse(messageHTML); //Parsing and traversing a HTML Document String confirmURL = doc.body().getElementsByClass("mcnButtonContent").select("a").first().attr("href"); // capturing the confirmation URL from the HTML body log.info("Captured comfirmation url [{}]",confirmURL); String regConfirmStatus = Unirest.get(confirmURL).asString().getStatusText(); log.info("Confirmation status: {}",regConfirmStatus); if (regConfirmStatus.equals("OK")) { log.info("Registered user email verification successful."); msgStatus = true; }else { log.error("Registered user email verification failed."); msgStatus = false; break; } } i = i + 1; } } return msgStatus; } public JSONObject getMessageById(String messageId) throws UnirestException, JsonParseException, JsonMappingException, IOException { log.info("Getting message detail of message ID [{}]",messageId); JSONObject messageDetails = Unirest.get("https://getnada.com/api/v1/messages/" + messageId) .asJson() .getBody() .getObject(); return messageDetails; } public JSONObject triggerGetMethod(String url) { JSONObject getResponseObject = null; try { getResponseObject = Unirest.get(url) .asJson() .getBody() .getObject(); return getResponseObject; } catch (UnirestException e) { // TODO Auto-generated catch block e.printStackTrace(); } return getResponseObject; } }
UTF-8
Java
5,116
java
NadaEMailService.java
Java
[ { "context": " if ((messageDetails.get(\"fe\").equals(\"admin@eventenergies.com\")) && \n \t\t(messageDetails.get(\"s\")", "end": 3167, "score": 0.9999247193336487, "start": 3144, "tag": "EMAIL", "value": "admin@eventenergies.com" } ]
null
[]
package CommonLibs; import java.io.IOException; import java.util.Objects; import org.apache.commons.lang.RandomStringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class NadaEMailService { static Logger log = LogManager.getLogger(ConditionChecks.class.getName()); private static final String NADA_EMAIL_DOMAIN = "@getnada.com"; private static final String INBOX_MESSAGE_KEY_NAME = "msgs"; private static final String EMAIL_ID_ROUTE_PARAM = "email-id"; private static final int EMAIL_CHARS_LENGTH = 10; private static final int PASSWORD_CHARS_LENGTH = 10; private String emailId; private String password; String msgId; private void generateEmailId(){ this.emailId = RandomStringUtils.randomAlphanumeric(EMAIL_CHARS_LENGTH).toLowerCase().concat(NADA_EMAIL_DOMAIN); } private void generatePassword(){ this.password = RandomStringUtils.randomAlphanumeric(PASSWORD_CHARS_LENGTH); } //generates a random email for the first time. //call reset for a new random email public String getEmailId(){ if(Objects.isNull(this.emailId)){ this.generateEmailId(); } return this.emailId; } public String getPassword(){ if(Objects.isNull(this.password)){ this.generatePassword(); } return this.password; } //to re-generate a new random email id public void reset(){ this.emailId = null; } public String initMailID(String mailID) throws JSONException, UnirestException, JsonParseException, JsonMappingException, IOException { log.info("Initializing the autogenerated Email Id : [{}]",mailID); Unirest.get("https://getnada.com/api/v1/inboxes/{email-id}") .routeParam(EMAIL_ID_ROUTE_PARAM, mailID) .asJson() .getBody() .getObject() .getJSONArray(INBOX_MESSAGE_KEY_NAME); return mailID; } public Boolean readMessages(String mailID) throws JsonParseException, JsonMappingException, UnirestException, IOException { Boolean msgStatus = null; JSONArray jsonResponseMsgs = Unirest.get("https://getnada.com/api/v1/inboxes/{email-id}") .routeParam(EMAIL_ID_ROUTE_PARAM, mailID) .asJson() .getBody() .getObject() .getJSONArray(INBOX_MESSAGE_KEY_NAME); int i = 0; if (jsonResponseMsgs != null && jsonResponseMsgs.length() > 0) { while(i < jsonResponseMsgs.length()) { String msgId = jsonResponseMsgs.getJSONObject(i).optString("uid"); log.info("Captured message ID is [{}]", msgId); JSONObject messageDetails = getMessageById(msgId); if ((messageDetails.get("fe").equals("<EMAIL>")) && (messageDetails.get("s").equals("You are Singed-up. Here is your Email Confirmation link"))){ String messageHTML = (String) messageDetails.get("html"); Document doc = Jsoup.parse(messageHTML); //Parsing and traversing a HTML Document String confirmURL = doc.body().getElementsByClass("mcnButtonContent").select("a").first().attr("href"); // capturing the confirmation URL from the HTML body log.info("Captured comfirmation url [{}]",confirmURL); String regConfirmStatus = Unirest.get(confirmURL).asString().getStatusText(); log.info("Confirmation status: {}",regConfirmStatus); if (regConfirmStatus.equals("OK")) { log.info("Registered user email verification successful."); msgStatus = true; }else { log.error("Registered user email verification failed."); msgStatus = false; break; } } i = i + 1; } } return msgStatus; } public JSONObject getMessageById(String messageId) throws UnirestException, JsonParseException, JsonMappingException, IOException { log.info("Getting message detail of message ID [{}]",messageId); JSONObject messageDetails = Unirest.get("https://getnada.com/api/v1/messages/" + messageId) .asJson() .getBody() .getObject(); return messageDetails; } public JSONObject triggerGetMethod(String url) { JSONObject getResponseObject = null; try { getResponseObject = Unirest.get(url) .asJson() .getBody() .getObject(); return getResponseObject; } catch (UnirestException e) { // TODO Auto-generated catch block e.printStackTrace(); } return getResponseObject; } }
5,100
0.649335
0.64699
143
34.76923
31.87381
173
false
false
0
0
0
0
0
0
2.041958
false
false
15
26b10cc40df25a6607ad29dd48587db6d85cf0f7
34,179,349,785,971
7d1e801895fab977afecd929e8ac142923da9bd4
/Code/Java/Base/lab1/lab1_1.java
b00e48a4cd72cf45e82a3522b2e01c82c10ad4cd
[]
no_license
rain-sumire/Home
https://github.com/rain-sumire/Home
8623f45a592a962e410ed237ce663638c2f13b50
5c9ff399657ad99cafb869d4862aef2f0fc08287
refs/heads/main
2021-01-04T06:18:10.854000
2021-01-03T14:39:16
2021-01-03T14:39:16
240,425,384
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package EX.lab1; import java.util.Arrays; import java.util.Scanner; public class lab1_1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n; int[] a = new int[50]; Arrays.fill(a,0); for(int o:a){ System.out.print(o); } System.out.println(); while((n = input.nextInt())!= 0){ a[n]++; } for(int i = 0;i < a.length;i++){ if(a[i] != 0){ if(a[i]>1){ System.out.println(i+" appears times:"+a[i]); } else{ System.out.println(i+" appear time:"+a[i]); } } } input.close(); } }
UTF-8
Java
794
java
lab1_1.java
Java
[]
null
[]
package EX.lab1; import java.util.Arrays; import java.util.Scanner; public class lab1_1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n; int[] a = new int[50]; Arrays.fill(a,0); for(int o:a){ System.out.print(o); } System.out.println(); while((n = input.nextInt())!= 0){ a[n]++; } for(int i = 0;i < a.length;i++){ if(a[i] != 0){ if(a[i]>1){ System.out.println(i+" appears times:"+a[i]); } else{ System.out.println(i+" appear time:"+a[i]); } } } input.close(); } }
794
0.401763
0.389169
30
24.4
15.696284
65
false
false
0
0
0
0
0
0
0.533333
false
false
15
2eedb5e4db8a5c5217531269231bcae78fb21d09
35,639,638,655,624
9dcfa192d21d1b4486185677d602c7bb90e0eff2
/app/src/main/java/hr/fer/android/sglab/qr/SettingsActivity.java
d9a2c6ebe4283689cd51c0a1afe37acb78365c19
[]
no_license
franjurinec/SGLab-QR
https://github.com/franjurinec/SGLab-QR
5a998034657e9cec2b74c3bd705edf73493f2305
4d97d6623ef8a341d879c0350b4b66c94fbe5b6b
refs/heads/master
2020-03-29T10:26:51.622000
2018-12-13T09:27:35
2018-12-13T09:27:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hr.fer.android.sglab.qr; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import hr.fer.android.sglab.qr.utils.SharedPreferencesUtils; public class SettingsActivity extends AppCompatActivity implements View.OnClickListener { private EditText endpointUrl; private EditText username; private EditText password; private Button btnEdit; private Button btnSave; private SharedPreferencesUtils prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); prefs = SharedPreferencesUtils.get(this); endpointUrl = findViewById(R.id.endpoint_url); endpointUrl.setText(prefs.getWebServiceEndpoint()); username = findViewById(R.id.username); username.setText(prefs.getUsername()); password = findViewById(R.id.password); password.setText(prefs.getPassword()); btnEdit = findViewById(R.id.btn_edit); btnEdit.setOnClickListener(this); btnSave = findViewById(R.id.btn_save); btnSave.setOnClickListener(this); } @Override public void onClick(final View view) { switch (view.getId()) { case (R.id.btn_edit) : endpointUrl.setEnabled(true); endpointUrl.requestFocus(); username.setEnabled(true); password.setEnabled(true); btnEdit.setVisibility(View.GONE); btnSave.setVisibility(View.VISIBLE); break; case (R.id.btn_save) : if (TextUtils.isEmpty(endpointUrl.getText()) || TextUtils.isEmpty(username.getText()) || TextUtils.isEmpty(password.getText())) { Toast.makeText(this, getResources().getString(R.string.message__fill_all_fields), Toast.LENGTH_LONG).show(); return; } prefs.setWebServiceEndpoint(endpointUrl.getText().toString()); prefs.setUsername(username.getText().toString()); prefs.setPassword(password.getText().toString()); endpointUrl.setEnabled(false); username.setEnabled(false); password.setEnabled(false); btnEdit.setVisibility(View.VISIBLE); btnSave.setVisibility(View.GONE); break; } } }
UTF-8
Java
2,646
java
SettingsActivity.java
Java
[]
null
[]
package hr.fer.android.sglab.qr; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import hr.fer.android.sglab.qr.utils.SharedPreferencesUtils; public class SettingsActivity extends AppCompatActivity implements View.OnClickListener { private EditText endpointUrl; private EditText username; private EditText password; private Button btnEdit; private Button btnSave; private SharedPreferencesUtils prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); prefs = SharedPreferencesUtils.get(this); endpointUrl = findViewById(R.id.endpoint_url); endpointUrl.setText(prefs.getWebServiceEndpoint()); username = findViewById(R.id.username); username.setText(prefs.getUsername()); password = findViewById(R.id.password); password.setText(prefs.getPassword()); btnEdit = findViewById(R.id.btn_edit); btnEdit.setOnClickListener(this); btnSave = findViewById(R.id.btn_save); btnSave.setOnClickListener(this); } @Override public void onClick(final View view) { switch (view.getId()) { case (R.id.btn_edit) : endpointUrl.setEnabled(true); endpointUrl.requestFocus(); username.setEnabled(true); password.setEnabled(true); btnEdit.setVisibility(View.GONE); btnSave.setVisibility(View.VISIBLE); break; case (R.id.btn_save) : if (TextUtils.isEmpty(endpointUrl.getText()) || TextUtils.isEmpty(username.getText()) || TextUtils.isEmpty(password.getText())) { Toast.makeText(this, getResources().getString(R.string.message__fill_all_fields), Toast.LENGTH_LONG).show(); return; } prefs.setWebServiceEndpoint(endpointUrl.getText().toString()); prefs.setUsername(username.getText().toString()); prefs.setPassword(password.getText().toString()); endpointUrl.setEnabled(false); username.setEnabled(false); password.setEnabled(false); btnEdit.setVisibility(View.VISIBLE); btnSave.setVisibility(View.GONE); break; } } }
2,646
0.626228
0.62585
81
31.666666
25.095865
128
false
false
0
0
0
0
0
0
0.641975
false
false
15
ad610b0aa58ae4be42b9fc3b2922c68521995107
30,897,994,782,246
73d4aae69364fb6044a4f7135e2cde6782830868
/classblog/java/src/main/java/com/somecoder/demo/blog/entity/response/ChangeInformationResponse.java
eb1345514e5ba251d757a2db12a5d9c25fe75800
[]
no_license
miskamuska/xian_hub
https://github.com/miskamuska/xian_hub
1a7ce73fa553accc54e8b23e5d7d6b3c18b03404
32b9a19d928919e7e788f02ac9aebf9b220de87d
refs/heads/main
2023-06-08T23:46:49.019000
2021-06-25T15:11:18
2021-06-25T15:11:18
355,435,947
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.somecoder.demo.blog.entity.response; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author Liangkeyu * @since 2021-01-28 */ @Data @ApiModel("修改学生信息响应") public class ChangeInformationResponse { @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "性别") private String gender; @ApiModelProperty(value = "学号") private String studentNumber; @ApiModelProperty(value = "邮箱") private String email; @ApiModelProperty(value = "个性签名") private String personalSignature; @ApiModelProperty(value = "出生日期") private String birthday; @ApiModelProperty(value = "星座") private String constellation; @ApiModelProperty(value = "所在地") private String location; }
UTF-8
Java
881
java
ChangeInformationResponse.java
Java
[ { "context": "ModelProperty;\nimport lombok.Data;\n\n/**\n * @author Liangkeyu\n * @since 2021-01-28\n */\n@Data\n@ApiModel(\"修改学生信息响", "end": 183, "score": 0.9761678576469421, "start": 174, "tag": "NAME", "value": "Liangkeyu" } ]
null
[]
package com.somecoder.demo.blog.entity.response; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author Liangkeyu * @since 2021-01-28 */ @Data @ApiModel("修改学生信息响应") public class ChangeInformationResponse { @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "性别") private String gender; @ApiModelProperty(value = "学号") private String studentNumber; @ApiModelProperty(value = "邮箱") private String email; @ApiModelProperty(value = "个性签名") private String personalSignature; @ApiModelProperty(value = "出生日期") private String birthday; @ApiModelProperty(value = "星座") private String constellation; @ApiModelProperty(value = "所在地") private String location; }
881
0.709599
0.699879
38
20.657894
16.395245
48
false
false
0
0
0
0
0
0
0.315789
false
false
15
e6044b5e28bf39c7c7554b41e93a503f083ffa3a
30,897,994,783,306
a4c68cef6bbe991d18b5642c975d1586059624e4
/BackEnd/src/main/java/com/rmit/sept/mon15307/backend/model/UserAccount.java
5f931d17afcdcc157f5aa1bb7a2a354db38da786
[]
no_license
RMIT-SEPT/majorproject-mon-1530-7
https://github.com/RMIT-SEPT/majorproject-mon-1530-7
c53f8158d4ded0d7120afda096de75b88b551c4d
fa450198d8d9f7ac0e8b2845ddb487bb89fd70b9
refs/heads/master
2023-01-01T18:01:48.534000
2020-10-18T12:13:40
2020-10-18T12:13:40
282,833,258
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rmit.sept.mon15307.backend.model; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.Collection; import java.util.Date; @Entity public class UserAccount implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(UserAccountViews.Public.class) private Long userId; @NotNull @NotBlank @JsonView(UserAccountViews.Public.class) private String fullName; @JsonView(UserAccountViews.Public.class) private String preferredName; @NotBlank(message = "Password field is required") @JsonView(UserAccountViews.Internal.class) private String password; @Email @Column(unique = true) @NotNull @JsonView(UserAccountViews.Public.class) private String username; @Pattern(regexp = "[0-9]{10}") @NotNull @JsonView(UserAccountViews.Public.class) private String phoneNumber; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isAdmin; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isWorker; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isCustomer; @Transient @JsonView(UserAccountViews.Internal.class) private String confirmPassword; @CreatedDate private Date createdAt; @LastModifiedDate private Date updatedAt; public UserAccount() {} @JsonGetter("id") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPreferredName(){ return preferredName; } public void setPreferredName(String preferredName) { this.preferredName = preferredName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public Boolean getAdmin() { return isAdmin; } public void setAdmin(Boolean admin) { isAdmin = admin; } public Boolean getWorker() { return isWorker; } public void setWorker(Boolean worker) { isWorker = worker; } public Boolean getCustomer() { return isCustomer; } public void setCustomer(Boolean customer) { isCustomer = customer; } @JsonGetter("role") @JsonView(UserAccountViews.Public.class) public String getRole() { return this.isAdmin ? "admin" : this.isWorker ? "worker" : "customer"; } @PrePersist protected void onCreate() { this.createdAt = new Date(); } @PreUpdate protected void onUpdate() { this.updatedAt = new Date(); } @Override @JsonIgnore public Collection<? extends GrantedAuthority> getAuthorities() { return null; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @JsonGetter("email") @JsonAlias("username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override @JsonIgnore public boolean isAccountNonExpired() { return true; } /* UserDetails interface methods */ @Override @JsonIgnore public boolean isAccountNonLocked() { return true; } @Override @JsonIgnore public boolean isCredentialsNonExpired() { return true; } @Override @JsonIgnore public boolean isEnabled() { return true; } public static class UserAccountViews { public static class Public {} public static class Internal extends Public {} } }
UTF-8
Java
4,765
java
UserAccount.java
Java
[ { "context": "assword(String password) {\n this.password = password;\n }\n\n @JsonGetter(\"email\")\n @JsonAlias(\"", "end": 3957, "score": 0.519137442111969, "start": 3949, "tag": "PASSWORD", "value": "password" }, { "context": ";\n }\n\n @JsonGetter(\"email\")...
null
[]
package com.rmit.sept.mon15307.backend.model; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.Collection; import java.util.Date; @Entity public class UserAccount implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonView(UserAccountViews.Public.class) private Long userId; @NotNull @NotBlank @JsonView(UserAccountViews.Public.class) private String fullName; @JsonView(UserAccountViews.Public.class) private String preferredName; @NotBlank(message = "Password field is required") @JsonView(UserAccountViews.Internal.class) private String password; @Email @Column(unique = true) @NotNull @JsonView(UserAccountViews.Public.class) private String username; @Pattern(regexp = "[0-9]{10}") @NotNull @JsonView(UserAccountViews.Public.class) private String phoneNumber; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isAdmin; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isWorker; @NotNull @JsonView(UserAccountViews.Internal.class) private Boolean isCustomer; @Transient @JsonView(UserAccountViews.Internal.class) private String confirmPassword; @CreatedDate private Date createdAt; @LastModifiedDate private Date updatedAt; public UserAccount() {} @JsonGetter("id") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPreferredName(){ return preferredName; } public void setPreferredName(String preferredName) { this.preferredName = preferredName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public Boolean getAdmin() { return isAdmin; } public void setAdmin(Boolean admin) { isAdmin = admin; } public Boolean getWorker() { return isWorker; } public void setWorker(Boolean worker) { isWorker = worker; } public Boolean getCustomer() { return isCustomer; } public void setCustomer(Boolean customer) { isCustomer = customer; } @JsonGetter("role") @JsonView(UserAccountViews.Public.class) public String getRole() { return this.isAdmin ? "admin" : this.isWorker ? "worker" : "customer"; } @PrePersist protected void onCreate() { this.createdAt = new Date(); } @PreUpdate protected void onUpdate() { this.updatedAt = new Date(); } @Override @JsonIgnore public Collection<? extends GrantedAuthority> getAuthorities() { return null; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = <PASSWORD>; } @JsonGetter("email") @JsonAlias("username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override @JsonIgnore public boolean isAccountNonExpired() { return true; } /* UserDetails interface methods */ @Override @JsonIgnore public boolean isAccountNonLocked() { return true; } @Override @JsonIgnore public boolean isCredentialsNonExpired() { return true; } @Override @JsonIgnore public boolean isEnabled() { return true; } public static class UserAccountViews { public static class Public {} public static class Internal extends Public {} } }
4,767
0.674921
0.673033
212
21.476416
18.692255
78
false
false
0
0
0
0
0
0
0.264151
false
false
15
ae5d317eb0be98e924ed7c11d7f7e7e027314478
35,227,321,799,720
7ae990438edc6cfa3121ac17c614350345c7b60e
/Java Resources/Screener/StockResult.java
00b7999466c150b013cb674487f2ea5b0fee64be
[]
no_license
rcarlton25/cs201final
https://github.com/rcarlton25/cs201final
12390a72ba39a67635d287c4e6a5379c0cfcbebf
2b827a4212a168876b9a4e17d1c41cf670d87ad2
refs/heads/master
2020-09-01T22:40:37.360000
2019-12-03T03:55:30
2019-12-03T03:55:30
219,076,705
4
0
null
false
2019-12-02T13:04:24
2019-11-01T23:21:11
2019-12-02T13:00:47
2019-12-02T13:04:24
8,938
3
0
1
Java
false
false
package Screener; public class StockResult { public int symbols_requested; public int symbols_returned; public StockData[] data; public int getSymbolsRequested() { return this.symbols_requested; } public int getSymbolsReturned() { return this.symbols_returned; } public StockData[] getStockData() { return this.data; } }
UTF-8
Java
338
java
StockResult.java
Java
[]
null
[]
package Screener; public class StockResult { public int symbols_requested; public int symbols_returned; public StockData[] data; public int getSymbolsRequested() { return this.symbols_requested; } public int getSymbolsReturned() { return this.symbols_returned; } public StockData[] getStockData() { return this.data; } }
338
0.745562
0.745562
17
18.941177
13.866891
36
false
false
0
0
0
0
0
0
1.352941
false
false
15
9776596289e7ab6a00f2f10a6e3f1951e12cf1e5
18,047,452,641,513
d6a7fca1d7dd36f5f687172457040be05ef66e35
/server/src/main/java/org/vyhlidka/homeautomation/eq3/domain/LMaxMessage.java
9997634596a078e3ecd5283639a3cb2a841d226c
[ "Apache-2.0" ]
permissive
LukasVyhlidka/HomeAutomator
https://github.com/LukasVyhlidka/HomeAutomator
de86f9bfe50c819a1a6370cb995ad02729448ca7
d1f15b934f66a0168c179fa85eb1ff88a2b84ec1
refs/heads/master
2022-12-22T21:19:19.604000
2021-01-04T13:36:00
2021-01-04T13:36:00
76,788,652
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.vyhlidka.homeautomation.eq3.domain; import org.apache.commons.lang3.Validate; import java.util.Collections; import java.util.List; /** * Represents the L-type of the MAX message. */ public class LMaxMessage extends MaxMessage { public final List<MaxDevice> devices; public LMaxMessage(final String message, final List<MaxDevice> devices) { super(message); Validate.notNull(devices, "devices can not be null;"); this.devices = Collections.unmodifiableList(devices); } @Override public String toString() { return "LMaxMessage{" + "devices=" + devices + '}'; } public static class MaxDevice { public MaxDeviceType type; public final int rfAddress; public final byte unknown; public final int flags; public final byte valvePosition; /* temp * 2 (divide by two to get the temperature) */ public final int temperature; public final int dateUntil; public final byte timeUntil; /* temp * 10 (divide by ten to get the actual temperature) */ public final int actualTemperature; public MaxDevice(final MaxDeviceType type, final int rfAddress, final byte unknown, final int flags, final byte valvePosition, final int temperature, final int dateUntil, final byte timeUntil, final int actualTemperature) { this.type = type; this.rfAddress = rfAddress; this.unknown = unknown; this.flags = flags; this.valvePosition = valvePosition; this.temperature = temperature; this.dateUntil = dateUntil; this.timeUntil = timeUntil; this.actualTemperature = actualTemperature; } @Override public String toString() { return "MaxDevice{" + "type=" + type + ", rfAddress=" + rfAddress + ", valvePosition=" + valvePosition + ", temperature=" + temperature + ", actualTemperature=" + actualTemperature + "}\n"; } } public enum MaxDeviceType { ECO, VALVE, THERMOSTAT; } }
UTF-8
Java
2,303
java
LMaxMessage.java
Java
[]
null
[]
package org.vyhlidka.homeautomation.eq3.domain; import org.apache.commons.lang3.Validate; import java.util.Collections; import java.util.List; /** * Represents the L-type of the MAX message. */ public class LMaxMessage extends MaxMessage { public final List<MaxDevice> devices; public LMaxMessage(final String message, final List<MaxDevice> devices) { super(message); Validate.notNull(devices, "devices can not be null;"); this.devices = Collections.unmodifiableList(devices); } @Override public String toString() { return "LMaxMessage{" + "devices=" + devices + '}'; } public static class MaxDevice { public MaxDeviceType type; public final int rfAddress; public final byte unknown; public final int flags; public final byte valvePosition; /* temp * 2 (divide by two to get the temperature) */ public final int temperature; public final int dateUntil; public final byte timeUntil; /* temp * 10 (divide by ten to get the actual temperature) */ public final int actualTemperature; public MaxDevice(final MaxDeviceType type, final int rfAddress, final byte unknown, final int flags, final byte valvePosition, final int temperature, final int dateUntil, final byte timeUntil, final int actualTemperature) { this.type = type; this.rfAddress = rfAddress; this.unknown = unknown; this.flags = flags; this.valvePosition = valvePosition; this.temperature = temperature; this.dateUntil = dateUntil; this.timeUntil = timeUntil; this.actualTemperature = actualTemperature; } @Override public String toString() { return "MaxDevice{" + "type=" + type + ", rfAddress=" + rfAddress + ", valvePosition=" + valvePosition + ", temperature=" + temperature + ", actualTemperature=" + actualTemperature + "}\n"; } } public enum MaxDeviceType { ECO, VALVE, THERMOSTAT; } }
2,303
0.582284
0.580113
80
27.7875
24.684355
108
false
false
0
0
0
0
0
0
0.575
false
false
15
76a2ae91901066b03ebbd719f8c0f11d33986fe6
16,192,026,756,420
e5d4052b7b1343bc6ff4daeea1223e54173e02be
/hüseyin engin 202802005 NO Yazilimyapimi final ödevi/app/src/main/java/com/huso/yazilimyapimi/almakistenilenleradapter.java
a3e08f0faf96c52dff77d97a78cba38dc7208064
[]
no_license
huseyin0709/yazilimyapimifinal
https://github.com/huseyin0709/yazilimyapimifinal
447faa46e01e1ff0460931b3e307ce24c412c7ef
6dec20e51fa23734a15c22b769438a27b7a7450c
refs/heads/main
2023-06-03T15:24:09.428000
2021-06-18T20:49:37
2021-06-18T20:49:37
378,257,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huso.yazilimyapimi; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.Map; public class almakistenilenleradapter extends RecyclerView.Adapter<almakistenilenleradapter.Postalmakistenilenler> { ArrayList<String> almakistenenurunleridarray; ArrayList<Double> almakistenenmiktarlaridarray; ArrayList<Double> almakistenenkgfiyatlariidarray; FirebaseFirestore firebaseFirestore; FirebaseUser firebaseUser; ArrayList<String> almakistenenleridarray; String eklenenurun; Double eklenenmiktar; Double eklenenkgfiyati; Double para; String eklenenidler; String almakistenenurun; //constructor ile diger sayfadan gonderilenler bu sayfada cekiyoruz public almakistenilenleradapter(ArrayList<String> almakistenenurunleridarray,ArrayList<Double> almakistenenmiktarlaridarray,ArrayList<Double> almakistenenkgfiyatlariidarray,FirebaseFirestore firebaseFirestore,FirebaseUser firebaseUser,ArrayList<String> almakistenenleridarray,String eklenenurun,Double eklenenmiktar,Double eklenenkgfiyati,String eklenenidler,Double para,String almakistenenurun) { this.almakistenenurunleridarray = almakistenenurunleridarray; this.almakistenenmiktarlaridarray = almakistenenmiktarlaridarray; this.almakistenenkgfiyatlariidarray = almakistenenkgfiyatlariidarray; this.firebaseFirestore = firebaseFirestore; this.firebaseUser = firebaseUser; this.almakistenenleridarray=almakistenenleridarray; this.eklenenurun=eklenenurun; this.eklenenmiktar=eklenenmiktar; this.eklenenkgfiyati=eklenenkgfiyati; this.eklenenidler=eklenenidler; this.para=para; this.almakistenenurun=almakistenenurun; } @NonNull @Override public Postalmakistenilenler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());//ayarladigimz recyclerviewin tanimini yapiyoruz View view=layoutInflater.inflate(R.layout.almakistenen_recyclerview,parent,false); return new almakistenilenleradapter.Postalmakistenilenler(view); } @Override public void onBindViewHolder(@NonNull Postalmakistenilenler holder, int position) {//aldigimiz bilgileri recyclerviewdakilara entegre ediyoruz holder.almakistenenurun.setText(" "+"URUNLER : "+almakistenenurunleridarray.get(position)); holder.almakistenenmiktar.setText(" "+"Miktar : "+almakistenenmiktarlaridarray.get(position)+" "+"KG"); holder.almakistenenkgfiyati.setText(" "+"KG Fiyatı : "+almakistenenkgfiyatlariidarray.get(position)+" "+"TL"); holder.guncellebutonu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (eklenenurun.matches(almakistenenurun) && almakistenenmiktarlaridarray.get(position)<=eklenenmiktar && almakistenenkgfiyatlariidarray.get(position)<=eklenenkgfiyati){//istediklerimiz fiyat olusumundaki ile kontol ediyoruz Double yenimiktar = eklenenmiktar - almakistenenmiktarlaridarray.get(position); if (yenimiktar>0){ firebaseFirestore.collection("Eklenenurunler").document(eklenenidler).update("miktar",yenimiktar).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { firebaseFirestore.collection("almakistenenler").document(firebaseUser.getUid()).collection("alinanlar").document(almakistenenleridarray.get(position)).delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } }); Double parasonuc = para - (almakistenenmiktarlaridarray.get(position) * almakistenenkgfiyatlariidarray.get(position)) - (almakistenenmiktarlaridarray.get(position) * almakistenenkgfiyatlariidarray.get(position))*1/100;//satin aldigimiz urunden muhasebe ucreti %1 kisinin parasindan cekiyoruz if (parasonuc>0){ firebaseFirestore.collection("Eklenenpara").document(firebaseUser.getUid()).update("paramiktar",parasonuc).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); }else { firebaseFirestore.collection("Eklenenpara").document(firebaseUser.getUid()).update("paramiktar",0).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } else { firebaseFirestore.collection("Eklenenurunler").document(eklenenidler).delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } } }); } @Override public int getItemCount() { return almakistenenurunleridarray.size(); } class Postalmakistenilenler extends RecyclerView.ViewHolder{//recyclerviewdaki gerekli tanimlari yapiyoruz TextView almakistenenurun,almakistenenmiktar,almakistenenkgfiyati; Button guncellebutonu; ArrayList<String> idarray; ArrayList<Double> miktararray; public Postalmakistenilenler(@NonNull View itemView) { super(itemView); almakistenenurun=itemView.findViewById(R.id.almakisteneniurun_textview); almakistenenmiktar=itemView.findViewById(R.id.almakistenenmiktar_textview); almakistenenkgfiyati=itemView.findViewById(R.id.almakistenenkgfiyati_textview); guncellebutonu=itemView.findViewById(R.id.guncelle_butonu); idarray=new ArrayList<>(); miktararray=new ArrayList<>(); } } }
UTF-8
Java
7,107
java
almakistenilenleradapter.java
Java
[]
null
[]
package com.huso.yazilimyapimi; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.Map; public class almakistenilenleradapter extends RecyclerView.Adapter<almakistenilenleradapter.Postalmakistenilenler> { ArrayList<String> almakistenenurunleridarray; ArrayList<Double> almakistenenmiktarlaridarray; ArrayList<Double> almakistenenkgfiyatlariidarray; FirebaseFirestore firebaseFirestore; FirebaseUser firebaseUser; ArrayList<String> almakistenenleridarray; String eklenenurun; Double eklenenmiktar; Double eklenenkgfiyati; Double para; String eklenenidler; String almakistenenurun; //constructor ile diger sayfadan gonderilenler bu sayfada cekiyoruz public almakistenilenleradapter(ArrayList<String> almakistenenurunleridarray,ArrayList<Double> almakistenenmiktarlaridarray,ArrayList<Double> almakistenenkgfiyatlariidarray,FirebaseFirestore firebaseFirestore,FirebaseUser firebaseUser,ArrayList<String> almakistenenleridarray,String eklenenurun,Double eklenenmiktar,Double eklenenkgfiyati,String eklenenidler,Double para,String almakistenenurun) { this.almakistenenurunleridarray = almakistenenurunleridarray; this.almakistenenmiktarlaridarray = almakistenenmiktarlaridarray; this.almakistenenkgfiyatlariidarray = almakistenenkgfiyatlariidarray; this.firebaseFirestore = firebaseFirestore; this.firebaseUser = firebaseUser; this.almakistenenleridarray=almakistenenleridarray; this.eklenenurun=eklenenurun; this.eklenenmiktar=eklenenmiktar; this.eklenenkgfiyati=eklenenkgfiyati; this.eklenenidler=eklenenidler; this.para=para; this.almakistenenurun=almakistenenurun; } @NonNull @Override public Postalmakistenilenler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());//ayarladigimz recyclerviewin tanimini yapiyoruz View view=layoutInflater.inflate(R.layout.almakistenen_recyclerview,parent,false); return new almakistenilenleradapter.Postalmakistenilenler(view); } @Override public void onBindViewHolder(@NonNull Postalmakistenilenler holder, int position) {//aldigimiz bilgileri recyclerviewdakilara entegre ediyoruz holder.almakistenenurun.setText(" "+"URUNLER : "+almakistenenurunleridarray.get(position)); holder.almakistenenmiktar.setText(" "+"Miktar : "+almakistenenmiktarlaridarray.get(position)+" "+"KG"); holder.almakistenenkgfiyati.setText(" "+"KG Fiyatı : "+almakistenenkgfiyatlariidarray.get(position)+" "+"TL"); holder.guncellebutonu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (eklenenurun.matches(almakistenenurun) && almakistenenmiktarlaridarray.get(position)<=eklenenmiktar && almakistenenkgfiyatlariidarray.get(position)<=eklenenkgfiyati){//istediklerimiz fiyat olusumundaki ile kontol ediyoruz Double yenimiktar = eklenenmiktar - almakistenenmiktarlaridarray.get(position); if (yenimiktar>0){ firebaseFirestore.collection("Eklenenurunler").document(eklenenidler).update("miktar",yenimiktar).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { firebaseFirestore.collection("almakistenenler").document(firebaseUser.getUid()).collection("alinanlar").document(almakistenenleridarray.get(position)).delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } }); Double parasonuc = para - (almakistenenmiktarlaridarray.get(position) * almakistenenkgfiyatlariidarray.get(position)) - (almakistenenmiktarlaridarray.get(position) * almakistenenkgfiyatlariidarray.get(position))*1/100;//satin aldigimiz urunden muhasebe ucreti %1 kisinin parasindan cekiyoruz if (parasonuc>0){ firebaseFirestore.collection("Eklenenpara").document(firebaseUser.getUid()).update("paramiktar",parasonuc).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); }else { firebaseFirestore.collection("Eklenenpara").document(firebaseUser.getUid()).update("paramiktar",0).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } else { firebaseFirestore.collection("Eklenenurunler").document(eklenenidler).delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { } }); } } } }); } @Override public int getItemCount() { return almakistenenurunleridarray.size(); } class Postalmakistenilenler extends RecyclerView.ViewHolder{//recyclerviewdaki gerekli tanimlari yapiyoruz TextView almakistenenurun,almakistenenmiktar,almakistenenkgfiyati; Button guncellebutonu; ArrayList<String> idarray; ArrayList<Double> miktararray; public Postalmakistenilenler(@NonNull View itemView) { super(itemView); almakistenenurun=itemView.findViewById(R.id.almakisteneniurun_textview); almakistenenmiktar=itemView.findViewById(R.id.almakistenenmiktar_textview); almakistenenkgfiyati=itemView.findViewById(R.id.almakistenenkgfiyati_textview); guncellebutonu=itemView.findViewById(R.id.guncelle_butonu); idarray=new ArrayList<>(); miktararray=new ArrayList<>(); } } }
7,107
0.671545
0.670419
139
50.122303
58.310314
401
false
false
0
0
0
0
0
0
0.633094
false
false
15
066e73d6ae330c8b5e3ff5be9c8262bf32ee24a5
39,307,540,709,347
96d3a00468ebb3f2defc2b6a66dcc0e6af59affd
/fsdevtools-commands/module/src/main/java/com/espirit/moddev/cli/commands/module/utils/ModuleInstaller.java
c04da97eefd5a57acadad93106898a8c4dbe8626
[ "Apache-2.0" ]
permissive
liphis/FSDevTools
https://github.com/liphis/FSDevTools
63606aad0437c8c6687572770dff80959864ce24
01835b7cf7a3ef291e36771b7b1b809739904a69
refs/heads/master
2023-08-10T17:42:12.824000
2021-08-12T07:51:08
2021-08-12T07:51:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * * ********************************************************************* * fsdevtools * %% * Copyright (C) 2021 e-Spirit AG * %% * 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.espirit.moddev.cli.commands.module.utils; import com.espirit.moddev.cli.commands.module.installCommand.ModuleInstallationParameters; import com.espirit.moddev.shared.StringUtils; import com.espirit.moddev.shared.webapp.WebAppIdentifier; import de.espirit.firstspirit.access.Connection; import de.espirit.firstspirit.access.ServerConfiguration; import de.espirit.firstspirit.access.project.Project; import de.espirit.firstspirit.access.store.LockException; import de.espirit.firstspirit.agency.ModuleAdminAgent; import de.espirit.firstspirit.agency.ModuleAdminAgent.ModuleResult; import de.espirit.firstspirit.agency.WebAppId; import de.espirit.firstspirit.io.FileHandle; import de.espirit.firstspirit.io.FileSystem; import de.espirit.firstspirit.module.descriptor.ComponentDescriptor; import de.espirit.firstspirit.module.descriptor.ModuleDescriptor; import de.espirit.firstspirit.module.descriptor.ProjectAppDescriptor; import de.espirit.firstspirit.server.module.WebAppType; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static com.espirit.moddev.shared.webapp.WebAppIdentifier.isFs5RootWebApp; import static de.espirit.firstspirit.access.ConnectionManager.SOCKET_MODE; import static de.espirit.firstspirit.module.descriptor.ComponentDescriptor.Type.SERVICE; import static de.espirit.firstspirit.module.descriptor.ComponentDescriptor.Type.WEBAPP; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; /** * This class can install modules and module configurations. */ @SuppressWarnings("squid:S1200") public class ModuleInstaller { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ModuleInstaller.class); private static boolean setActiveWebServer(final ServerConfiguration serverConfiguration, final WebAppIdentifier webScope, final Project project) { if (webScope.isGlobal()) { return true; } final String scopeName = webScope.getScope().name(); String activeWebServer = project.getActiveWebServer(scopeName); if (StringUtils.isNullOrEmpty(project.getActiveWebServer(scopeName))) { activeWebServer = serverConfiguration.getActiveWebserverConfiguration(WebAppType.FS5ROOT.getId()); if (StringUtils.isNullOrEmpty(activeWebServer)) { LOGGER.warn("Project has no active web server. Using default webserver of global root."); } else { LOGGER.warn("Project has no active web server. Using webserver '" + activeWebServer + "' of global root."); } try { project.lock(); project.setActiveWebServer(scopeName, activeWebServer); project.save(); } catch (LockException e) { LOGGER.error("Cannot lock and save project!", e); return false; } finally { LOGGER.debug("Unlocking project"); project.unlock(); } } else { LOGGER.info("'{}' already has an active web server for scope '{}'. Active web server is: {}", project.getName(), scopeName, activeWebServer); } return true; } private final Connection _connection; private ModuleAdminAgent _moduleAdminAgent; /** * Instantiates a {@link ModuleInstaller}. Doesn't do anything else. */ public ModuleInstaller(final Connection connection) { // Nothing to do here _connection = connection; } private synchronized ModuleAdminAgent getModuleAdminAgent() { if (_moduleAdminAgent == null) { _moduleAdminAgent = _connection.getBroker().requireSpecialist(ModuleAdminAgent.TYPE); } return _moduleAdminAgent; } /** * Method for installing a given FirstSpirit module (only the module itself will be installed, no components will be added to any project). * * @param fsm The path to the FirstSpirit module file (fsm) to be installed * @return An InstallModuleResult. Result might be absent when there's an exception with the fsm file stream. * @throws IOException may be thrown server side while installing the module */ @NotNull private ModuleResult installFsm(@NotNull final File fsm, final boolean deploy) throws IOException { LOGGER.info("Starting module installation for fsm '{}'...", fsm.getName()); try (FileInputStream fsmStream = new FileInputStream(fsm)) { LOGGER.debug("Installing module in fsm '{}'...", fsm.getName()); ModuleResult result = getModuleAdminAgent().install(fsmStream, true, deploy); final String moduleName = result.getDescriptor().getModuleName(); LOGGER.debug("Module '{}' installed (fsm was '{}').", moduleName, fsm.getName()); LOGGER.debug("Setting module '{}' as trusted...", moduleName); getModuleAdminAgent().setTrusted(moduleName, true); LOGGER.debug("Module '{}' is now trusted.", moduleName); LOGGER.info("Module of fsm '{}' successfully installed.", fsm.getName()); return result; } } /** * Method for activating auto start of services of a given module * * @param descriptor the module descriptor * @param parameters the {@link ModuleInstallationParameters parameters} of the command */ private void activateServices(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final String moduleName = descriptor.getModuleName(); final ComponentDescriptor[] componentDescriptors = descriptor.getComponents(); if (componentDescriptors == null) { LOGGER.error("No components found for module '{}'!", moduleName); } else { List<ComponentDescriptor> serviceDescriptors = stream(componentDescriptors).filter(it -> it.getType().equals(SERVICE)).collect(toList()); if (!serviceDescriptors.isEmpty()) { LOGGER.info("Configuring services for module '{}'...", moduleName); serviceDescriptors.forEach(serviceDescriptor -> { LOGGER.info("Configuring service '{}:{}'...", moduleName, serviceDescriptor.getName()); File configuration = parameters.getServiceConfigurations().get(serviceDescriptor.getName()); if (configuration != null) { createConfigurationFile(SERVICE, serviceDescriptor, configuration, moduleName, parameters.getProjectName(), null); } else { LOGGER.info("No configuration file for service '{}:{}' found. Nothing to do.", moduleName, serviceDescriptor.getName()); } setAutostartAndRestartService(moduleName, serviceDescriptor); LOGGER.info("Service '{}:{}' configured.", moduleName, serviceDescriptor.getName()); }); } } } private void setAutostartAndRestartService(@NotNull final String moduleName, @NotNull final ComponentDescriptor descriptor) { final ModuleAdminAgent moduleAdminAgent = getModuleAdminAgent(); String componentDescriptorName = descriptor.getName(); LOGGER.info("Setting autostart for service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.setAutostart(componentDescriptorName, true); LOGGER.debug("Autostart for service '{}:{}' set.", moduleName, componentDescriptorName); LOGGER.info("Stopping service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.stopService(componentDescriptorName); LOGGER.debug("Service service '{}:{}' stopped.", moduleName, componentDescriptorName); LOGGER.info("Starting service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.startService(componentDescriptorName); LOGGER.info("Status of service '{}:{}': {}", moduleName, componentDescriptorName, moduleAdminAgent.isRunning(componentDescriptorName) ? "RUNNING" : "STOPPED"); } /** * Convenience method for copying the configuration files forProjectAndScope the module to the server-dirs * * @param type Type of the module whose configuration should be written e.g. Service, ProjectApp * @param componentDescriptor The component forProjectAndScope the module.xml to use * @param configurationFile The map forProjectAndScope the pom.xml that includes the configuration files * @param moduleName The name of the module whose configuration should be written (nullable) * @param projectName The optional project name applications shall be installed to * @param webAppId The webAppId to use - only used by webapp configurations */ private void createConfigurationFile(final ComponentDescriptor.Type type, final ComponentDescriptor componentDescriptor, final File configurationFile, final String moduleName, final String projectName, WebAppId webAppId) { final String fileName = configurationFile.getName(); LOGGER.info("Creating configuration file '{}' ( type = {} ) for '{}:{}'...", fileName, type.name(), moduleName, componentDescriptor.getName()); FileSystem<?> fileSystem = getFileSystemForConfigurationType(type, componentDescriptor, moduleName, projectName, webAppId); try { LOGGER.debug("Fetching file '{}'...", fileName); FileHandle handle = fileSystem.obtain(fileName); LOGGER.info("Saving file to '{}'...", handle.getPath()); handle.save(new FileInputStream(configurationFile)); LOGGER.debug("File {} saved.", handle.getPath()); } catch (IOException e) { LOGGER.error("Error uploading file!", e); } LOGGER.info("Configuration file '{}' ( type = {} ) for '{}:{}' created.", fileName, type.name(), moduleName, componentDescriptor.getName()); } @NotNull private FileSystem<?> getFileSystemForConfigurationType(final ComponentDescriptor.Type type, final ComponentDescriptor componentDescriptor, final String moduleName, final String projectName, final WebAppId webAppId) { ModuleAdminAgent moduleAdminAgent = getModuleAdminAgent(); final String componentName = componentDescriptor.getName(); switch (type) { case SERVICE: { LOGGER.debug("Retrieving filesystem for service '{}:{}'...", moduleName, componentName); return moduleAdminAgent.getServiceConfig(componentName); } case PROJECTAPP: { LOGGER.debug("Retrieving filesystem for project app '{}:{}:{}'...", projectName, moduleName, componentName); Project project = safelyRetrieveProject(projectName); return moduleAdminAgent.getProjectAppConfig(moduleName, componentName, project); } case WEBAPP: { LOGGER.debug("Retrieving filesystem for webapp '{}:{}:{}'...", webAppId, moduleName, componentName); return moduleAdminAgent.getWebAppConfig(moduleName, componentName, webAppId); } default: { throw new IllegalStateException(String.format("Unknown component type '%s'!", type.name())); } } } private Project safelyRetrieveProject(final String projectName) { if (StringUtils.isNullOrEmpty(projectName)) { throw new IllegalArgumentException("No project given, can't get a project app configuration!"); } Project project = _connection.getProjectByName(projectName); if (project == null) { throw new IllegalArgumentException("Cannot find project " + projectName + "!"); } return project; } /** * Method for installing the project applications of a given module into a given project * * @param descriptor the descriptor of the module whose project applications shall be installed * @param parameters the {@link ModuleInstallationParameters} of the current command */ private void installProjectApps(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { List<ComponentDescriptor> projectAppDescriptors = stream(descriptor.getComponents()).filter(it -> it instanceof ProjectAppDescriptor).collect(toList()); final String moduleName = descriptor.getModuleName(); final String projectName = parameters.getProjectName(); if (StringUtils.isNullOrEmpty(projectName)) { if (!projectAppDescriptors.isEmpty()) { LOGGER.info("Found project apps in module '{}', but cannot install project apps without a project name!", moduleName); } } else { if (!projectAppDescriptors.isEmpty()) { LOGGER.info("Installing project apps of module '{}' in project '{}'...", moduleName, projectName); projectAppDescriptors.forEach(projectAppDescriptor -> { LOGGER.info("Creating project app configuration '{}:{}' in project '{}' ...", moduleName, projectAppDescriptor.getName(), projectName); createProjectAppConfiguration(projectName, moduleName, projectAppDescriptor); LOGGER.debug("Project app configuration '{}:{}' in project '{}' created.", moduleName, projectAppDescriptor.getName(), projectName); LOGGER.info("Installing project app '{}:{}' in '{}'...", moduleName, projectAppDescriptor.getName(), projectName); Project project = safelyRetrieveProject(projectName); getModuleAdminAgent().installProjectApp(moduleName, projectAppDescriptor.getName(), project); LOGGER.debug("Project app '{}:{}' installed in '{}'.", moduleName, projectAppDescriptor.getName(), projectName); parameters.getProjectAppConfiguration().ifPresent(projectAppFile -> createConfigurationFile(ComponentDescriptor.Type.PROJECTAPP, projectAppDescriptor, projectAppFile, moduleName, projectName, null)); }); } } } private void createProjectAppConfiguration(final String projectName, final String moduleName, final ComponentDescriptor projectAppDescriptor) { FileSystem<?> projectAppConfig = null; try { projectAppConfig = getFileSystemForConfigurationType(projectAppDescriptor.getType(), projectAppDescriptor, moduleName, projectName, null); } catch (IllegalArgumentException e) { LOGGER.info("Project app configuration for '{}:{}' in project '{}' already exists - creating...", moduleName, projectAppDescriptor.getName(), projectName); LOGGER.debug("Exception: ", e); } if (projectAppConfig != null) { LOGGER.info("Project app configuration for '{}:{}' in project '{}' already exists - updating...", moduleName, projectAppDescriptor.getName(), projectName); } } private boolean installProjectWebAppsAndCreateConfig(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final String moduleName = descriptor.getModuleName(); final List<ComponentDescriptor> webappDescriptors = stream(descriptor.getComponents()).filter(it -> WEBAPP.equals(it.getType())).collect(toList()); final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); final AtomicBoolean result = new AtomicBoolean(true); if (!webappDescriptors.isEmpty() && !webAppScopes.isEmpty()) { LOGGER.info("Configuring web app components for module '{}'...", moduleName); webappDescriptors.forEach(componentDescriptor -> { for (WebAppIdentifier scope : webAppScopes) { final String componentName = componentDescriptor.getName(); LOGGER.info("Configuring web app component '{}:{}' in scope {}...", moduleName, componentName, scope.getScope()); final boolean webAppAndConfigurationsCreated = createWebAppAndConfigurations(descriptor, parameters, componentDescriptor, scope); if (webAppAndConfigurationsCreated) { LOGGER.debug("Web app component '{}:{}' in scope {} configured.", moduleName, componentName, scope.getScope()); } else { LOGGER.warn("Could not configure web app component '{}:{}' in scope {}...", moduleName, componentName, scope.getScope()); } result.set(result.get() && webAppAndConfigurationsCreated); } }); } return result.get(); } /** * Method for installing the web applications of a given module into a given project * * @param descriptor A {@link ModuleDescriptor} to describe FirstSpirit module components * @param parameters parameters containing the specific entries forProjectAndScope the config files * @return success indicator */ private boolean installProjectWebAppsAndDeploy(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { if (!installProjectWebAppsAndCreateConfig(descriptor, parameters)) { return false; } if (parameters.getDeploy()) { return deployWebAppsForScopes(descriptor, parameters); } else { return true; } } private boolean installWebAppAndActivateWebServer(final WebAppIdentifier webScope, final ModuleInstallationParameters parameters) { try { final String projectName = parameters.getProjectName(); Project projectOrNull = null; if (!StringUtils.isNullOrEmpty(projectName)) { projectOrNull = _connection.getProjectByName(projectName); } LOGGER.info("Setting active webserver for project scope: {}", webScope); boolean activeServerForProjectSet = setActiveWebServer(_connection.getServerConfiguration(), webScope, projectOrNull); LOGGER.info(activeServerForProjectSet ? "Setting active webserver was successful." : "Setting active webserver wasn't successful."); if (!activeServerForProjectSet) { return false; } return deployWebApp(webScope, projectOrNull); } catch (IllegalStateException ise) { LOGGER.error("Cannot deploy war file!", ise); return false; } } private boolean createWebAppAndConfigurations(final ModuleDescriptor moduleDescriptor, final ModuleInstallationParameters parameters, final ComponentDescriptor componentDescriptor, final WebAppIdentifier scope) { final String projectName = parameters.getProjectName(); final String moduleName = moduleDescriptor.getModuleName(); final Map<WebAppIdentifier, File> webAppConfigurations = parameters.getWebAppConfigurations(); Project projectOrNull = StringUtils.isNullOrEmpty(projectName) ? null : _connection.getProjectByName(projectName); try { WebAppId id = scope.createWebAppId(projectOrNull); getModuleAdminAgent().installWebApp(moduleName, componentDescriptor.getName(), id, parameters.getDeploy()); if (webAppConfigurations.containsKey(scope)) { createConfigurationFile(WEBAPP, componentDescriptor, webAppConfigurations.get(scope), moduleName, projectName, id); } LOGGER.info("WebAppScope: {}", scope); return true; } catch (IllegalArgumentException e) { LOGGER.error("Invalid Scope " + scope, e); return false; } } private boolean deployWebAppsForScopes(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final ComponentDescriptor[] componentDescriptors = descriptor.getComponents(); final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); List<ComponentDescriptor> webAppDescriptors = asList(componentDescriptors).stream().filter(componentDescriptor -> WEBAPP.equals(componentDescriptor.getType())).collect(toList()); if (!webAppDescriptors.isEmpty() && !webAppScopes.isEmpty()) { LOGGER.info("Installing Project WebApps"); } for (ComponentDescriptor componentDescriptor : webAppDescriptors) { if (!deployWebApps(componentDescriptor, parameters)) { return false; } } return true; } private boolean deployWebApps(final ComponentDescriptor descriptor, final ModuleInstallationParameters parameters) { final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); LOGGER.info("Going to install and activate component {} with webAppIds: {}", descriptor.getName(), webAppScopes); Optional<Boolean> failed = webAppScopes .stream() .map(it -> installWebAppAndActivateWebServer(it, parameters)) .filter(it -> !it) .findAny(); if (failed.isPresent()) { LOGGER.error("Cannot install WebApp for specific scope! IDs: {}", webAppScopes); return false; } return true; } private boolean deployWebApp(final WebAppIdentifier webScope, final Project projectOrNull) { final WebAppId webAppId = webScope.createWebAppId(projectOrNull); final boolean isRootWebAppAndNonSocketConnection = isFs5RootWebApp(webAppId) && SOCKET_MODE != _connection.getMode(); boolean successfullyDeployed = false; if (isRootWebAppAndNonSocketConnection) { LOGGER.error("Cannot use a non socket connection to deploy a web component to the FirstSpirit root WebApp. Use SOCKET as connection mode!"); } else { LOGGER.info("Deploying WebApp {}", projectOrNull == null ? webScope.toString() : (projectOrNull.getName() + '/' + webScope.getScope())); successfullyDeployed = getModuleAdminAgent().deployWebApp(webAppId); LOGGER.info("Successfully deployed: {}", successfullyDeployed); } return successfullyDeployed; } /** * Installs a module on a FirstSpirit server. Uses the given connection. * If any of the configured components is already installed, it is updated. * * @param parameters a parameter bean that defines how the module should be installed * @return the optional {@link ModuleResult}, which is empty on failure * @throws IOException may be thrown server side while installing the module */ @NotNull public ModuleResult install(@NotNull final ModuleInstallationParameters parameters, final boolean deploy) throws IOException { if (_connection == null || !_connection.isConnected()) { throw new IllegalStateException("Connection is null or not connected!"); } final ModuleResult moduleResult = installFsm(parameters.getFsm(), parameters.getDeploy()); final ModuleDescriptor moduleDescriptor = moduleResult.getDescriptor(); final String moduleName = moduleDescriptor.getName(); // activate services activateServices(moduleDescriptor, parameters); // install project apps installProjectApps(moduleDescriptor, parameters); if (deploy) { // install and deploy project web apps final boolean webAppsSuccessfullyInstalledAndDeployed = installProjectWebAppsAndDeploy(moduleDescriptor, parameters); if (!webAppsSuccessfullyInstalledAndDeployed) { LOGGER.error("WebApp installation and activation for module '{}' failed!", moduleName); } } else { // only create configurations final boolean webAppsConfigured = installProjectWebAppsAndCreateConfig(moduleDescriptor, parameters); if (!webAppsConfigured) { LOGGER.error("WebApp configuration for module '{}' failed!", moduleName); } } return moduleResult; } }
UTF-8
Java
22,815
java
ModuleInstaller.java
Java
[]
null
[]
/* * * ********************************************************************* * fsdevtools * %% * Copyright (C) 2021 e-Spirit AG * %% * 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.espirit.moddev.cli.commands.module.utils; import com.espirit.moddev.cli.commands.module.installCommand.ModuleInstallationParameters; import com.espirit.moddev.shared.StringUtils; import com.espirit.moddev.shared.webapp.WebAppIdentifier; import de.espirit.firstspirit.access.Connection; import de.espirit.firstspirit.access.ServerConfiguration; import de.espirit.firstspirit.access.project.Project; import de.espirit.firstspirit.access.store.LockException; import de.espirit.firstspirit.agency.ModuleAdminAgent; import de.espirit.firstspirit.agency.ModuleAdminAgent.ModuleResult; import de.espirit.firstspirit.agency.WebAppId; import de.espirit.firstspirit.io.FileHandle; import de.espirit.firstspirit.io.FileSystem; import de.espirit.firstspirit.module.descriptor.ComponentDescriptor; import de.espirit.firstspirit.module.descriptor.ModuleDescriptor; import de.espirit.firstspirit.module.descriptor.ProjectAppDescriptor; import de.espirit.firstspirit.server.module.WebAppType; import org.jetbrains.annotations.NotNull; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import static com.espirit.moddev.shared.webapp.WebAppIdentifier.isFs5RootWebApp; import static de.espirit.firstspirit.access.ConnectionManager.SOCKET_MODE; import static de.espirit.firstspirit.module.descriptor.ComponentDescriptor.Type.SERVICE; import static de.espirit.firstspirit.module.descriptor.ComponentDescriptor.Type.WEBAPP; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; /** * This class can install modules and module configurations. */ @SuppressWarnings("squid:S1200") public class ModuleInstaller { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ModuleInstaller.class); private static boolean setActiveWebServer(final ServerConfiguration serverConfiguration, final WebAppIdentifier webScope, final Project project) { if (webScope.isGlobal()) { return true; } final String scopeName = webScope.getScope().name(); String activeWebServer = project.getActiveWebServer(scopeName); if (StringUtils.isNullOrEmpty(project.getActiveWebServer(scopeName))) { activeWebServer = serverConfiguration.getActiveWebserverConfiguration(WebAppType.FS5ROOT.getId()); if (StringUtils.isNullOrEmpty(activeWebServer)) { LOGGER.warn("Project has no active web server. Using default webserver of global root."); } else { LOGGER.warn("Project has no active web server. Using webserver '" + activeWebServer + "' of global root."); } try { project.lock(); project.setActiveWebServer(scopeName, activeWebServer); project.save(); } catch (LockException e) { LOGGER.error("Cannot lock and save project!", e); return false; } finally { LOGGER.debug("Unlocking project"); project.unlock(); } } else { LOGGER.info("'{}' already has an active web server for scope '{}'. Active web server is: {}", project.getName(), scopeName, activeWebServer); } return true; } private final Connection _connection; private ModuleAdminAgent _moduleAdminAgent; /** * Instantiates a {@link ModuleInstaller}. Doesn't do anything else. */ public ModuleInstaller(final Connection connection) { // Nothing to do here _connection = connection; } private synchronized ModuleAdminAgent getModuleAdminAgent() { if (_moduleAdminAgent == null) { _moduleAdminAgent = _connection.getBroker().requireSpecialist(ModuleAdminAgent.TYPE); } return _moduleAdminAgent; } /** * Method for installing a given FirstSpirit module (only the module itself will be installed, no components will be added to any project). * * @param fsm The path to the FirstSpirit module file (fsm) to be installed * @return An InstallModuleResult. Result might be absent when there's an exception with the fsm file stream. * @throws IOException may be thrown server side while installing the module */ @NotNull private ModuleResult installFsm(@NotNull final File fsm, final boolean deploy) throws IOException { LOGGER.info("Starting module installation for fsm '{}'...", fsm.getName()); try (FileInputStream fsmStream = new FileInputStream(fsm)) { LOGGER.debug("Installing module in fsm '{}'...", fsm.getName()); ModuleResult result = getModuleAdminAgent().install(fsmStream, true, deploy); final String moduleName = result.getDescriptor().getModuleName(); LOGGER.debug("Module '{}' installed (fsm was '{}').", moduleName, fsm.getName()); LOGGER.debug("Setting module '{}' as trusted...", moduleName); getModuleAdminAgent().setTrusted(moduleName, true); LOGGER.debug("Module '{}' is now trusted.", moduleName); LOGGER.info("Module of fsm '{}' successfully installed.", fsm.getName()); return result; } } /** * Method for activating auto start of services of a given module * * @param descriptor the module descriptor * @param parameters the {@link ModuleInstallationParameters parameters} of the command */ private void activateServices(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final String moduleName = descriptor.getModuleName(); final ComponentDescriptor[] componentDescriptors = descriptor.getComponents(); if (componentDescriptors == null) { LOGGER.error("No components found for module '{}'!", moduleName); } else { List<ComponentDescriptor> serviceDescriptors = stream(componentDescriptors).filter(it -> it.getType().equals(SERVICE)).collect(toList()); if (!serviceDescriptors.isEmpty()) { LOGGER.info("Configuring services for module '{}'...", moduleName); serviceDescriptors.forEach(serviceDescriptor -> { LOGGER.info("Configuring service '{}:{}'...", moduleName, serviceDescriptor.getName()); File configuration = parameters.getServiceConfigurations().get(serviceDescriptor.getName()); if (configuration != null) { createConfigurationFile(SERVICE, serviceDescriptor, configuration, moduleName, parameters.getProjectName(), null); } else { LOGGER.info("No configuration file for service '{}:{}' found. Nothing to do.", moduleName, serviceDescriptor.getName()); } setAutostartAndRestartService(moduleName, serviceDescriptor); LOGGER.info("Service '{}:{}' configured.", moduleName, serviceDescriptor.getName()); }); } } } private void setAutostartAndRestartService(@NotNull final String moduleName, @NotNull final ComponentDescriptor descriptor) { final ModuleAdminAgent moduleAdminAgent = getModuleAdminAgent(); String componentDescriptorName = descriptor.getName(); LOGGER.info("Setting autostart for service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.setAutostart(componentDescriptorName, true); LOGGER.debug("Autostart for service '{}:{}' set.", moduleName, componentDescriptorName); LOGGER.info("Stopping service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.stopService(componentDescriptorName); LOGGER.debug("Service service '{}:{}' stopped.", moduleName, componentDescriptorName); LOGGER.info("Starting service '{}:{}'", moduleName, componentDescriptorName); moduleAdminAgent.startService(componentDescriptorName); LOGGER.info("Status of service '{}:{}': {}", moduleName, componentDescriptorName, moduleAdminAgent.isRunning(componentDescriptorName) ? "RUNNING" : "STOPPED"); } /** * Convenience method for copying the configuration files forProjectAndScope the module to the server-dirs * * @param type Type of the module whose configuration should be written e.g. Service, ProjectApp * @param componentDescriptor The component forProjectAndScope the module.xml to use * @param configurationFile The map forProjectAndScope the pom.xml that includes the configuration files * @param moduleName The name of the module whose configuration should be written (nullable) * @param projectName The optional project name applications shall be installed to * @param webAppId The webAppId to use - only used by webapp configurations */ private void createConfigurationFile(final ComponentDescriptor.Type type, final ComponentDescriptor componentDescriptor, final File configurationFile, final String moduleName, final String projectName, WebAppId webAppId) { final String fileName = configurationFile.getName(); LOGGER.info("Creating configuration file '{}' ( type = {} ) for '{}:{}'...", fileName, type.name(), moduleName, componentDescriptor.getName()); FileSystem<?> fileSystem = getFileSystemForConfigurationType(type, componentDescriptor, moduleName, projectName, webAppId); try { LOGGER.debug("Fetching file '{}'...", fileName); FileHandle handle = fileSystem.obtain(fileName); LOGGER.info("Saving file to '{}'...", handle.getPath()); handle.save(new FileInputStream(configurationFile)); LOGGER.debug("File {} saved.", handle.getPath()); } catch (IOException e) { LOGGER.error("Error uploading file!", e); } LOGGER.info("Configuration file '{}' ( type = {} ) for '{}:{}' created.", fileName, type.name(), moduleName, componentDescriptor.getName()); } @NotNull private FileSystem<?> getFileSystemForConfigurationType(final ComponentDescriptor.Type type, final ComponentDescriptor componentDescriptor, final String moduleName, final String projectName, final WebAppId webAppId) { ModuleAdminAgent moduleAdminAgent = getModuleAdminAgent(); final String componentName = componentDescriptor.getName(); switch (type) { case SERVICE: { LOGGER.debug("Retrieving filesystem for service '{}:{}'...", moduleName, componentName); return moduleAdminAgent.getServiceConfig(componentName); } case PROJECTAPP: { LOGGER.debug("Retrieving filesystem for project app '{}:{}:{}'...", projectName, moduleName, componentName); Project project = safelyRetrieveProject(projectName); return moduleAdminAgent.getProjectAppConfig(moduleName, componentName, project); } case WEBAPP: { LOGGER.debug("Retrieving filesystem for webapp '{}:{}:{}'...", webAppId, moduleName, componentName); return moduleAdminAgent.getWebAppConfig(moduleName, componentName, webAppId); } default: { throw new IllegalStateException(String.format("Unknown component type '%s'!", type.name())); } } } private Project safelyRetrieveProject(final String projectName) { if (StringUtils.isNullOrEmpty(projectName)) { throw new IllegalArgumentException("No project given, can't get a project app configuration!"); } Project project = _connection.getProjectByName(projectName); if (project == null) { throw new IllegalArgumentException("Cannot find project " + projectName + "!"); } return project; } /** * Method for installing the project applications of a given module into a given project * * @param descriptor the descriptor of the module whose project applications shall be installed * @param parameters the {@link ModuleInstallationParameters} of the current command */ private void installProjectApps(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { List<ComponentDescriptor> projectAppDescriptors = stream(descriptor.getComponents()).filter(it -> it instanceof ProjectAppDescriptor).collect(toList()); final String moduleName = descriptor.getModuleName(); final String projectName = parameters.getProjectName(); if (StringUtils.isNullOrEmpty(projectName)) { if (!projectAppDescriptors.isEmpty()) { LOGGER.info("Found project apps in module '{}', but cannot install project apps without a project name!", moduleName); } } else { if (!projectAppDescriptors.isEmpty()) { LOGGER.info("Installing project apps of module '{}' in project '{}'...", moduleName, projectName); projectAppDescriptors.forEach(projectAppDescriptor -> { LOGGER.info("Creating project app configuration '{}:{}' in project '{}' ...", moduleName, projectAppDescriptor.getName(), projectName); createProjectAppConfiguration(projectName, moduleName, projectAppDescriptor); LOGGER.debug("Project app configuration '{}:{}' in project '{}' created.", moduleName, projectAppDescriptor.getName(), projectName); LOGGER.info("Installing project app '{}:{}' in '{}'...", moduleName, projectAppDescriptor.getName(), projectName); Project project = safelyRetrieveProject(projectName); getModuleAdminAgent().installProjectApp(moduleName, projectAppDescriptor.getName(), project); LOGGER.debug("Project app '{}:{}' installed in '{}'.", moduleName, projectAppDescriptor.getName(), projectName); parameters.getProjectAppConfiguration().ifPresent(projectAppFile -> createConfigurationFile(ComponentDescriptor.Type.PROJECTAPP, projectAppDescriptor, projectAppFile, moduleName, projectName, null)); }); } } } private void createProjectAppConfiguration(final String projectName, final String moduleName, final ComponentDescriptor projectAppDescriptor) { FileSystem<?> projectAppConfig = null; try { projectAppConfig = getFileSystemForConfigurationType(projectAppDescriptor.getType(), projectAppDescriptor, moduleName, projectName, null); } catch (IllegalArgumentException e) { LOGGER.info("Project app configuration for '{}:{}' in project '{}' already exists - creating...", moduleName, projectAppDescriptor.getName(), projectName); LOGGER.debug("Exception: ", e); } if (projectAppConfig != null) { LOGGER.info("Project app configuration for '{}:{}' in project '{}' already exists - updating...", moduleName, projectAppDescriptor.getName(), projectName); } } private boolean installProjectWebAppsAndCreateConfig(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final String moduleName = descriptor.getModuleName(); final List<ComponentDescriptor> webappDescriptors = stream(descriptor.getComponents()).filter(it -> WEBAPP.equals(it.getType())).collect(toList()); final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); final AtomicBoolean result = new AtomicBoolean(true); if (!webappDescriptors.isEmpty() && !webAppScopes.isEmpty()) { LOGGER.info("Configuring web app components for module '{}'...", moduleName); webappDescriptors.forEach(componentDescriptor -> { for (WebAppIdentifier scope : webAppScopes) { final String componentName = componentDescriptor.getName(); LOGGER.info("Configuring web app component '{}:{}' in scope {}...", moduleName, componentName, scope.getScope()); final boolean webAppAndConfigurationsCreated = createWebAppAndConfigurations(descriptor, parameters, componentDescriptor, scope); if (webAppAndConfigurationsCreated) { LOGGER.debug("Web app component '{}:{}' in scope {} configured.", moduleName, componentName, scope.getScope()); } else { LOGGER.warn("Could not configure web app component '{}:{}' in scope {}...", moduleName, componentName, scope.getScope()); } result.set(result.get() && webAppAndConfigurationsCreated); } }); } return result.get(); } /** * Method for installing the web applications of a given module into a given project * * @param descriptor A {@link ModuleDescriptor} to describe FirstSpirit module components * @param parameters parameters containing the specific entries forProjectAndScope the config files * @return success indicator */ private boolean installProjectWebAppsAndDeploy(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { if (!installProjectWebAppsAndCreateConfig(descriptor, parameters)) { return false; } if (parameters.getDeploy()) { return deployWebAppsForScopes(descriptor, parameters); } else { return true; } } private boolean installWebAppAndActivateWebServer(final WebAppIdentifier webScope, final ModuleInstallationParameters parameters) { try { final String projectName = parameters.getProjectName(); Project projectOrNull = null; if (!StringUtils.isNullOrEmpty(projectName)) { projectOrNull = _connection.getProjectByName(projectName); } LOGGER.info("Setting active webserver for project scope: {}", webScope); boolean activeServerForProjectSet = setActiveWebServer(_connection.getServerConfiguration(), webScope, projectOrNull); LOGGER.info(activeServerForProjectSet ? "Setting active webserver was successful." : "Setting active webserver wasn't successful."); if (!activeServerForProjectSet) { return false; } return deployWebApp(webScope, projectOrNull); } catch (IllegalStateException ise) { LOGGER.error("Cannot deploy war file!", ise); return false; } } private boolean createWebAppAndConfigurations(final ModuleDescriptor moduleDescriptor, final ModuleInstallationParameters parameters, final ComponentDescriptor componentDescriptor, final WebAppIdentifier scope) { final String projectName = parameters.getProjectName(); final String moduleName = moduleDescriptor.getModuleName(); final Map<WebAppIdentifier, File> webAppConfigurations = parameters.getWebAppConfigurations(); Project projectOrNull = StringUtils.isNullOrEmpty(projectName) ? null : _connection.getProjectByName(projectName); try { WebAppId id = scope.createWebAppId(projectOrNull); getModuleAdminAgent().installWebApp(moduleName, componentDescriptor.getName(), id, parameters.getDeploy()); if (webAppConfigurations.containsKey(scope)) { createConfigurationFile(WEBAPP, componentDescriptor, webAppConfigurations.get(scope), moduleName, projectName, id); } LOGGER.info("WebAppScope: {}", scope); return true; } catch (IllegalArgumentException e) { LOGGER.error("Invalid Scope " + scope, e); return false; } } private boolean deployWebAppsForScopes(@NotNull final ModuleDescriptor descriptor, @NotNull final ModuleInstallationParameters parameters) { final ComponentDescriptor[] componentDescriptors = descriptor.getComponents(); final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); List<ComponentDescriptor> webAppDescriptors = asList(componentDescriptors).stream().filter(componentDescriptor -> WEBAPP.equals(componentDescriptor.getType())).collect(toList()); if (!webAppDescriptors.isEmpty() && !webAppScopes.isEmpty()) { LOGGER.info("Installing Project WebApps"); } for (ComponentDescriptor componentDescriptor : webAppDescriptors) { if (!deployWebApps(componentDescriptor, parameters)) { return false; } } return true; } private boolean deployWebApps(final ComponentDescriptor descriptor, final ModuleInstallationParameters parameters) { final List<WebAppIdentifier> webAppScopes = parameters.getWebAppScopes(); LOGGER.info("Going to install and activate component {} with webAppIds: {}", descriptor.getName(), webAppScopes); Optional<Boolean> failed = webAppScopes .stream() .map(it -> installWebAppAndActivateWebServer(it, parameters)) .filter(it -> !it) .findAny(); if (failed.isPresent()) { LOGGER.error("Cannot install WebApp for specific scope! IDs: {}", webAppScopes); return false; } return true; } private boolean deployWebApp(final WebAppIdentifier webScope, final Project projectOrNull) { final WebAppId webAppId = webScope.createWebAppId(projectOrNull); final boolean isRootWebAppAndNonSocketConnection = isFs5RootWebApp(webAppId) && SOCKET_MODE != _connection.getMode(); boolean successfullyDeployed = false; if (isRootWebAppAndNonSocketConnection) { LOGGER.error("Cannot use a non socket connection to deploy a web component to the FirstSpirit root WebApp. Use SOCKET as connection mode!"); } else { LOGGER.info("Deploying WebApp {}", projectOrNull == null ? webScope.toString() : (projectOrNull.getName() + '/' + webScope.getScope())); successfullyDeployed = getModuleAdminAgent().deployWebApp(webAppId); LOGGER.info("Successfully deployed: {}", successfullyDeployed); } return successfullyDeployed; } /** * Installs a module on a FirstSpirit server. Uses the given connection. * If any of the configured components is already installed, it is updated. * * @param parameters a parameter bean that defines how the module should be installed * @return the optional {@link ModuleResult}, which is empty on failure * @throws IOException may be thrown server side while installing the module */ @NotNull public ModuleResult install(@NotNull final ModuleInstallationParameters parameters, final boolean deploy) throws IOException { if (_connection == null || !_connection.isConnected()) { throw new IllegalStateException("Connection is null or not connected!"); } final ModuleResult moduleResult = installFsm(parameters.getFsm(), parameters.getDeploy()); final ModuleDescriptor moduleDescriptor = moduleResult.getDescriptor(); final String moduleName = moduleDescriptor.getName(); // activate services activateServices(moduleDescriptor, parameters); // install project apps installProjectApps(moduleDescriptor, parameters); if (deploy) { // install and deploy project web apps final boolean webAppsSuccessfullyInstalledAndDeployed = installProjectWebAppsAndDeploy(moduleDescriptor, parameters); if (!webAppsSuccessfullyInstalledAndDeployed) { LOGGER.error("WebApp installation and activation for module '{}' failed!", moduleName); } } else { // only create configurations final boolean webAppsConfigured = installProjectWebAppsAndCreateConfig(moduleDescriptor, parameters); if (!webAppsConfigured) { LOGGER.error("WebApp configuration for module '{}' failed!", moduleName); } } return moduleResult; } }
22,815
0.746
0.745255
473
47.234673
42.590855
204
false
false
0
0
0
0
0
0
3.021142
false
false
15
51b81824e8680fef5d2b34894e429b7c90a95bcf
39,307,540,710,730
b3d7a14b7cc409c34e70bd80caf809b75bceca71
/app/src/main/java/ir/altaytech/saeedmobile/Model/Customer.java
8d00408b475cd2f78a001e95b11984389971a60d
[]
no_license
AltayTech/saeedmobile
https://github.com/AltayTech/saeedmobile
203c43751ea66f0a5fd6e5e56ac19cfa2d04178f
69c35f5465f3223c4fdb43e382d761d66d808068
refs/heads/master
2022-11-21T01:54:49.119000
2019-10-06T08:00:16
2019-10-06T08:00:16
213,129,624
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.altaytech.saeedmobile.Model; import android.support.annotation.Keep; import com.google.gson.annotations.SerializedName; /** * Created by SCIT on 3/10/2017. */ @Keep public class Customer { @SerializedName("FirstName") private String FirstName; @SerializedName("LastName") private String LastName; @SerializedName("UserName") private String UserName; @SerializedName("CityId") private int CityId; @SerializedName("ProvinceId") private int ProvinceId; @SerializedName("IsActive") private String IsActive; @SerializedName("NationalCode") private String NationalCode; @SerializedName("IsEmailNewsLatterSubsciber") private Boolean IsEmailNewsLatterSubsciber; @SerializedName("IsSMSNewsLatterSubsciber") private Boolean IsSMSNewsLatterSubsciber; @SerializedName("BankCardNo") private String BankCardNo; @SerializedName("Email") private String Email; public Customer(String first_name, String lastName, String userName, int cityId, int provinceId, String isActive, String nationalCode, Boolean isEmailNewsLatterSubsciber, Boolean isSMSNewsLatterSubsciber, String bankCardNo, String email) { this.FirstName = first_name; LastName = lastName; UserName = userName; CityId = cityId; ProvinceId = provinceId; IsActive = isActive; NationalCode = nationalCode; IsEmailNewsLatterSubsciber = isEmailNewsLatterSubsciber; IsSMSNewsLatterSubsciber = isSMSNewsLatterSubsciber; BankCardNo = bankCardNo; Email = email; } public Customer(String first_name, String lastName, String userName, String isActive, String nationalCode, Boolean isEmailNewsLatterSubsciber, Boolean isSMSNewsLatterSubsciber, String bankCardNo, String email) { this.FirstName = first_name; LastName = lastName; UserName = userName; IsActive = isActive; NationalCode = nationalCode; IsEmailNewsLatterSubsciber = isEmailNewsLatterSubsciber; IsSMSNewsLatterSubsciber = isSMSNewsLatterSubsciber; BankCardNo = bankCardNo; Email = email; } public String getFirstName() { return FirstName; } public String getLastName() { return LastName; } public String getUserName() { return UserName; } public int getCityId() { return CityId; } public int getProvinceId() { return ProvinceId; } public String getIsActive() { return IsActive; } public String getNationalCode() { return NationalCode; } public Boolean getEmailNewsLatterSubsciber() { return IsEmailNewsLatterSubsciber; } public Boolean getSMSNewsLatterSubsciber() { return IsSMSNewsLatterSubsciber; } public String getBankCardNo() { return BankCardNo; } public String getEmail() { return Email; } }
UTF-8
Java
3,004
java
Customer.java
Java
[ { "context": "son.annotations.SerializedName;\n\n/**\n * Created by SCIT on 3/10/2017.\n */\n@Keep\npublic class Customer {\n\n", "end": 157, "score": 0.9935315251350403, "start": 153, "tag": "USERNAME", "value": "SCIT" }, { "context": "il;\n\n public Customer(String first_name, S...
null
[]
package ir.altaytech.saeedmobile.Model; import android.support.annotation.Keep; import com.google.gson.annotations.SerializedName; /** * Created by SCIT on 3/10/2017. */ @Keep public class Customer { @SerializedName("FirstName") private String FirstName; @SerializedName("LastName") private String LastName; @SerializedName("UserName") private String UserName; @SerializedName("CityId") private int CityId; @SerializedName("ProvinceId") private int ProvinceId; @SerializedName("IsActive") private String IsActive; @SerializedName("NationalCode") private String NationalCode; @SerializedName("IsEmailNewsLatterSubsciber") private Boolean IsEmailNewsLatterSubsciber; @SerializedName("IsSMSNewsLatterSubsciber") private Boolean IsSMSNewsLatterSubsciber; @SerializedName("BankCardNo") private String BankCardNo; @SerializedName("Email") private String Email; public Customer(String first_name, String lastName, String userName, int cityId, int provinceId, String isActive, String nationalCode, Boolean isEmailNewsLatterSubsciber, Boolean isSMSNewsLatterSubsciber, String bankCardNo, String email) { this.FirstName = first_name; LastName = lastName; UserName = userName; CityId = cityId; ProvinceId = provinceId; IsActive = isActive; NationalCode = nationalCode; IsEmailNewsLatterSubsciber = isEmailNewsLatterSubsciber; IsSMSNewsLatterSubsciber = isSMSNewsLatterSubsciber; BankCardNo = bankCardNo; Email = email; } public Customer(String first_name, String lastName, String userName, String isActive, String nationalCode, Boolean isEmailNewsLatterSubsciber, Boolean isSMSNewsLatterSubsciber, String bankCardNo, String email) { this.FirstName = first_name; LastName = lastName; UserName = userName; IsActive = isActive; NationalCode = nationalCode; IsEmailNewsLatterSubsciber = isEmailNewsLatterSubsciber; IsSMSNewsLatterSubsciber = isSMSNewsLatterSubsciber; BankCardNo = bankCardNo; Email = email; } public String getFirstName() { return FirstName; } public String getLastName() { return LastName; } public String getUserName() { return UserName; } public int getCityId() { return CityId; } public int getProvinceId() { return ProvinceId; } public String getIsActive() { return IsActive; } public String getNationalCode() { return NationalCode; } public Boolean getEmailNewsLatterSubsciber() { return IsEmailNewsLatterSubsciber; } public Boolean getSMSNewsLatterSubsciber() { return IsSMSNewsLatterSubsciber; } public String getBankCardNo() { return BankCardNo; } public String getEmail() { return Email; } }
3,004
0.678762
0.676431
108
26.814816
27.675417
215
false
false
0
0
0
0
0
0
0.583333
false
false
15
8951b554d8f62c75c925ca04fd94aeebbbf84d1f
37,572,373,932,113
5483de46e2ae873baf13200772cccf5336322e2b
/src/sample/Main.java
e7f8ae2c74a8fd9c8873315c33c1a17fbda1b3b6
[]
no_license
Spellwizard/MaybeSimpleRPG
https://github.com/Spellwizard/MaybeSimpleRPG
89a8a717996ce3d2614c46f6586845539917d25b
f68c9d6bed6e8baee3c2867544fc580eb7dfff82
refs/heads/master
2022-09-19T03:06:24.962000
2020-06-05T15:17:50
2020-06-05T15:17:50
269,680,941
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; import javax.swing.*; public class Main{ public static void main(String[]args){ System.out.println("Starting Main"); //make the class and start the initial sheet construction needed Menu frame = new Menu("Game Menu"); //make sure the window will stop program on closing window frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make the window visible frame.setVisible(true); } }
UTF-8
Java
476
java
Main.java
Java
[]
null
[]
package sample; import javax.swing.*; public class Main{ public static void main(String[]args){ System.out.println("Starting Main"); //make the class and start the initial sheet construction needed Menu frame = new Menu("Game Menu"); //make sure the window will stop program on closing window frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make the window visible frame.setVisible(true); } }
476
0.653361
0.653361
22
20.545454
23.921703
72
false
false
0
0
0
0
0
0
0.272727
false
false
15
3c1c32212716891fc0a36640c535fe70d5c87d02
37,572,373,930,719
d844d1ab64d23b2c26b4e9520bbcab141f90e0e4
/src/main/java/com/google/codeu/data/User.java
b80a9eb3d2c149fe6808e140c0c21d9166e6423d
[ "Apache-2.0" ]
permissive
prudencep/CodeU2019-Team28
https://github.com/prudencep/CodeU2019-Team28
b613a35359ed58e3d2c1ef5c6802977499fd364a
08cedb2384e27981a913a39c0ea472e285023404
refs/heads/master
2020-05-14T22:39:08.180000
2019-04-17T04:37:42
2019-04-17T04:37:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.codeu.data; /** Keeps track of user information. */ public class User { private final String email; private final String aboutMe; private final String location; private String imageUrl; /** Represents a user entity's constructor. */ public User(String email, String aboutMe, String location) { this.email = email; this.aboutMe = aboutMe; this.location = location; this.imageUrl = imageUrl; } public String getEmail() { return email; } public String getAboutMe() { return aboutMe; } public String getLocation() { return location; } public String getimageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
UTF-8
Java
750
java
User.java
Java
[]
null
[]
package com.google.codeu.data; /** Keeps track of user information. */ public class User { private final String email; private final String aboutMe; private final String location; private String imageUrl; /** Represents a user entity's constructor. */ public User(String email, String aboutMe, String location) { this.email = email; this.aboutMe = aboutMe; this.location = location; this.imageUrl = imageUrl; } public String getEmail() { return email; } public String getAboutMe() { return aboutMe; } public String getLocation() { return location; } public String getimageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } }
750
0.68
0.68
38
18.736841
16.156609
62
false
false
0
0
0
0
0
0
0.421053
false
false
15
734acc82f7f1480781668c4de0e8288dc619c58f
38,860,864,140,163
f78115542ee0afeba0ce84b93c175d3540649735
/Smart_Home/src/test/java/ru/sbt/mipt/oop/event/processors/Loaders.java
7d737ce213fca7c47161c6ae7076d437a5823b90
[]
no_license
justfeelfil/education-sbt-principles_of_software_design
https://github.com/justfeelfil/education-sbt-principles_of_software_design
83997a57c897e833c58bade77b7b33a30d883cf4
04e88e41098f9d4fd92a489a4e6e46df1ba75a4f
refs/heads/master
2020-04-12T09:55:52.080000
2018-12-19T09:25:09
2018-12-19T09:25:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.sbt.mipt.oop.event.processors; import com.google.gson.Gson; import ru.sbt.mipt.oop.event.tools.SensorEvent; import ru.sbt.mipt.oop.homecomponents.SmartHome; import ru.sbt.mipt.oop.loaders.FileSmartHomeLoader; import ru.sbt.mipt.oop.loaders.SmartHomeLoader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Loaders { public static SensorEvent[] loadEvents (String path ) throws IOException { Gson gson = new Gson(); String json = new String(Files.readAllBytes(Paths.get(path))); return gson.fromJson(json, SensorEvent[].class); } public static SmartHome loadSmartHome (String path ) throws IOException { SmartHomeLoader TestHomeLoader = new FileSmartHomeLoader(path); return TestHomeLoader.loadSmartHome(); } }
UTF-8
Java
859
java
Loaders.java
Java
[]
null
[]
package ru.sbt.mipt.oop.event.processors; import com.google.gson.Gson; import ru.sbt.mipt.oop.event.tools.SensorEvent; import ru.sbt.mipt.oop.homecomponents.SmartHome; import ru.sbt.mipt.oop.loaders.FileSmartHomeLoader; import ru.sbt.mipt.oop.loaders.SmartHomeLoader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Loaders { public static SensorEvent[] loadEvents (String path ) throws IOException { Gson gson = new Gson(); String json = new String(Files.readAllBytes(Paths.get(path))); return gson.fromJson(json, SensorEvent[].class); } public static SmartHome loadSmartHome (String path ) throws IOException { SmartHomeLoader TestHomeLoader = new FileSmartHomeLoader(path); return TestHomeLoader.loadSmartHome(); } }
859
0.717113
0.717113
26
31.038462
26.237789
79
false
false
0
0
0
0
0
0
0.576923
false
false
15
f9747bbaeaba01f8d99f61d33d044316a4e16695
39,376,260,174,583
e4f98cab2f2ea9590567d5e157c7b8c03363cc5a
/test/de/vawi/factoryCanteen/IntegrationTests.java
b30469999d319ebe03fadfd8778a8e3d67902500
[]
no_license
iface06/factoryCanteen
https://github.com/iface06/factoryCanteen
0ec9c839aad9c619c3e767e0397469f1838651b4
2198d024ee1c18ec2706d9e1fbd2105f06a53658
refs/heads/master
2021-01-23T19:45:27.771000
2013-08-15T20:09:00
2013-08-15T20:09:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.vawi.factoryCanteen; import de.vawi.factoryCanteen.persistence.dishes.ImportIntegrationTest; import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author tatsch */ @Ignore @RunWith(Suite.class) @Suite.SuiteClasses({ ImportIntegrationTest.class }) public class IntegrationTests { }
UTF-8
Java
451
java
IntegrationTests.java
Java
[ { "context": "import org.junit.runners.Suite;\n\n/**\n *\n * @author tatsch\n */\n@Ignore\n@RunWith(Suite.class)\n@Suite.SuiteCla", "end": 320, "score": 0.9993780255317688, "start": 314, "tag": "USERNAME", "value": "tatsch" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.vawi.factoryCanteen; import de.vawi.factoryCanteen.persistence.dishes.ImportIntegrationTest; import org.junit.Ignore; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author tatsch */ @Ignore @RunWith(Suite.class) @Suite.SuiteClasses({ ImportIntegrationTest.class }) public class IntegrationTests { }
451
0.749446
0.749446
23
18.608696
18.675116
71
false
false
0
0
0
0
0
0
0.304348
false
false
15
29a1a316b2f8ec0830f4cec8196684b6c567380e
39,642,548,145,212
1931f0fd8a66cf6e9f630fe1397c36f757638977
/lappo_hospital/src/main/java/db/dto/PersonDto.java
73d87be3b6a4ae53a631e35fd8add9d1835ecd7e
[]
no_license
Aktubius/epam-bravo-2010
https://github.com/Aktubius/epam-bravo-2010
a63b0eff51901890c3127c758cacf715182a0d77
b3c2488d34b98bd5c0bf0649fdfe2b635c53b70a
refs/heads/master
2021-01-13T14:36:45.668000
2011-01-17T12:51:44
2011-01-17T12:51:44
51,060,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package db.dto; import java.io.Serializable; public class PersonDto implements Serializable, AbstractDto { /** * This attribute maps to the column NAME in the PERSON table. */ protected String name; /** * This attribute maps to the column LOGIN in the PERSON table. */ protected String login; /** * This attribute maps to the column PASSWORD in the PERSON table. */ protected String password; /** * This attribute maps to the column ID_PERSON in the PERSON table. */ protected int idPerson; /** * Method 'PersonDto' * */ protected int type; public PersonDto() { } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getId() { return this.idPerson; } /** * Method 'getName' * * @return String */ public String getName() { return name; } /** * Method 'setName' * * @param name */ public void setName(String name) { this.name = name; } /** * Method 'getLogin' * * @return String */ public String getLogin() { return login; } /** * Method 'setLogin' * * @param login */ public void setLogin(String login) { this.login = login; } /** * Method 'getPassword' * * @return String */ public String getPassword() { return password; } /** * Method 'setPassword' * * @param password */ public void setPassword(String password) { this.password = password; } /** * Method 'getIdPerson' * * @return int */ public int getIdPerson() { return idPerson; } /** * Method 'setIdPerson' * * @param idPerson */ public void setIdPerson(int idPerson) { this.idPerson = idPerson; } /** * Method 'equals' * * @param _other * @return boolean */ public boolean equals(Object _other) { if (_other == null) { return false; } if (_other == this) { return true; } if (!(_other instanceof PersonDto)) { return false; } final PersonDto _cast = (PersonDto) _other; if (name == null ? _cast.name != name : !name.equals( _cast.name )) { return false; } if (login == null ? _cast.login != login : !login.equals( _cast.login )) { return false; } if (password == null ? _cast.password != password : !password.equals( _cast.password )) { return false; } if (idPerson != _cast.idPerson) { return false; } return true; } /** * Method 'hashCode' * * @return int */ public int hashCode() { int _hashCode = 0; if (name != null) { _hashCode = 29 * _hashCode + name.hashCode(); } if (login != null) { _hashCode = 29 * _hashCode + login.hashCode(); } if (password != null) { _hashCode = 29 * _hashCode + password.hashCode(); } _hashCode = 29 * _hashCode + idPerson; return _hashCode; } /** * Method 'toString' * * @return String */ public String toString() { StringBuffer ret = new StringBuffer(); ret.append( "db.dto.PersonDto: " ); ret.append( "name=" + name ); ret.append( ", login=" + login ); ret.append( ", password=" + password ); ret.append( ", idPerson=" + idPerson ); return ret.toString(); } }
UTF-8
Java
3,412
java
PersonDto.java
Java
[ { "context": " login=\" + login );\r\n\t\tret.append( \", password=\" + password );\r\n\t\tret.append( \", idPerson=\" + idPerson );\r\n\t\t", "end": 3329, "score": 0.5482948422431946, "start": 3321, "tag": "PASSWORD", "value": "password" } ]
null
[]
package db.dto; import java.io.Serializable; public class PersonDto implements Serializable, AbstractDto { /** * This attribute maps to the column NAME in the PERSON table. */ protected String name; /** * This attribute maps to the column LOGIN in the PERSON table. */ protected String login; /** * This attribute maps to the column PASSWORD in the PERSON table. */ protected String password; /** * This attribute maps to the column ID_PERSON in the PERSON table. */ protected int idPerson; /** * Method 'PersonDto' * */ protected int type; public PersonDto() { } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getId() { return this.idPerson; } /** * Method 'getName' * * @return String */ public String getName() { return name; } /** * Method 'setName' * * @param name */ public void setName(String name) { this.name = name; } /** * Method 'getLogin' * * @return String */ public String getLogin() { return login; } /** * Method 'setLogin' * * @param login */ public void setLogin(String login) { this.login = login; } /** * Method 'getPassword' * * @return String */ public String getPassword() { return password; } /** * Method 'setPassword' * * @param password */ public void setPassword(String password) { this.password = password; } /** * Method 'getIdPerson' * * @return int */ public int getIdPerson() { return idPerson; } /** * Method 'setIdPerson' * * @param idPerson */ public void setIdPerson(int idPerson) { this.idPerson = idPerson; } /** * Method 'equals' * * @param _other * @return boolean */ public boolean equals(Object _other) { if (_other == null) { return false; } if (_other == this) { return true; } if (!(_other instanceof PersonDto)) { return false; } final PersonDto _cast = (PersonDto) _other; if (name == null ? _cast.name != name : !name.equals( _cast.name )) { return false; } if (login == null ? _cast.login != login : !login.equals( _cast.login )) { return false; } if (password == null ? _cast.password != password : !password.equals( _cast.password )) { return false; } if (idPerson != _cast.idPerson) { return false; } return true; } /** * Method 'hashCode' * * @return int */ public int hashCode() { int _hashCode = 0; if (name != null) { _hashCode = 29 * _hashCode + name.hashCode(); } if (login != null) { _hashCode = 29 * _hashCode + login.hashCode(); } if (password != null) { _hashCode = 29 * _hashCode + password.hashCode(); } _hashCode = 29 * _hashCode + idPerson; return _hashCode; } /** * Method 'toString' * * @return String */ public String toString() { StringBuffer ret = new StringBuffer(); ret.append( "db.dto.PersonDto: " ); ret.append( "name=" + name ); ret.append( ", login=" + login ); ret.append( ", password=" + <PASSWORD> ); ret.append( ", idPerson=" + idPerson ); return ret.toString(); } }
3,414
0.546893
0.544256
209
14.325358
16.653214
91
false
false
0
0
0
0
0
0
1.363636
false
false
15
6dfa4dc79a4fac701154e941a716f4ae95bd4e7b
13,554,916,850,702
275ec30cd19b72d7570b51232f7e462f5ff807e6
/Exercícios/expressão.java
b7f8fcad9a04c6043d6a707bf8657349f7717d47
[]
no_license
Miguelcutri/Exercicios-Java-Variaveis-e-operadores
https://github.com/Miguelcutri/Exercicios-Java-Variaveis-e-operadores
df992c7ab5a834ebec74cd6dad625d844920db81
acf6f3f17b627bbe477936d76dca0093fcc22a3e
refs/heads/main
2023-01-10T06:33:55.772000
2020-11-13T14:19:25
2020-11-13T14:19:25
312,594,553
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package PacoteJava; import java.util.Scanner; public class expressão { public static void main(String args[]) { int a,b,c, r, s, d; Scanner ler = new Scanner(System.in); System.out.println("Entre com A: "); a = ler.nextInt(); System.out.println("Entre com B: "); b =ler.nextInt(); System.out.println("Entre com C: "); c = ler.nextInt(); r= a+b*a+b; s= b+c*b+c; d= r+s/2; System.out.println(d); } }
ISO-8859-1
Java
434
java
expressão.java
Java
[]
null
[]
package PacoteJava; import java.util.Scanner; public class expressão { public static void main(String args[]) { int a,b,c, r, s, d; Scanner ler = new Scanner(System.in); System.out.println("Entre com A: "); a = ler.nextInt(); System.out.println("Entre com B: "); b =ler.nextInt(); System.out.println("Entre com C: "); c = ler.nextInt(); r= a+b*a+b; s= b+c*b+c; d= r+s/2; System.out.println(d); } }
434
0.6097
0.60739
21
19.619047
13.214264
41
false
false
0
0
0
0
0
0
2.428571
false
false
15
e6ba702ef06b3448fd904c1f8b596cab91a6ad7e
37,769,942,431,937
8670f5a428eb46c41bb9dccaf149753ba5392726
/Viidensuora/test/vihjeToiminto/VihjeTest.java
8be3c321dba830e249077bacaebcd8033805c0c6
[]
no_license
aapomalk/OhHa
https://github.com/aapomalk/OhHa
77805f434e3d33cf1c4a43ebf111e4bf024748fb
03c8280eca92964120ecd1ae81bfa96c716c5496
refs/heads/master
2016-09-09T23:27:04.873000
2013-08-29T10:01:22
2013-08-29T10:01:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vihjeToiminto; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import viidensuora.RistiNollaMuistio; import viidensuora.Laatu; /** * * @author aapomalk */ public class VihjeTest { private Vihje vihje; private RistiNollaMuistio ruudukko; public VihjeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { vihje = new Vihje(); ruudukko = new RistiNollaMuistio(); } @After public void tearDown() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // @Test public void kokeillaan() { ruudukko.lisaaRisti(0, 0); ruudukko.lisaaNolla(1, 1); ruudukko.lisaaRisti(1, 0); ruudukko.lisaaNolla(2, 0); ruudukko.lisaaRisti(0, 2); ruudukko.lisaaNolla(0, 1); ruudukko.lisaaRisti(-1, 1); ruudukko.lisaaNolla(2, 1); ruudukko.lisaaRisti(-2, 0); ruudukko.lisaaNolla(1, 3); ruudukko.lisaaRisti(2, 2); ruudukko.lisaaNolla(1, 2); ruudukko.lisaaRisti(-2, 2); ruudukko.lisaaNolla(1, -1); ruudukko.lisaaRisti(3, 1); ruudukko.lisaaNolla(1, 4); ruudukko.lisaaRisti(-2, 1); System.out.println("tarkasta seuraavat tulokset kasin: (nollalle)"); vihje.lisaaVihjeetListoihin(ruudukko.getMerkit(), Laatu.NOLLA); System.out.println("sininen1: " + vihje.getEhkaHyodyllinen()); System.out.println("turkoosi: " + vihje.getRakennaHyokkays()); System.out.println("vihrea: " + vihje.getVarmaVoitto()); System.out.println("sininen2: " + vihje.getHairitseVastustajaa()); System.out.println("violetti: " + vihje.getVaroVastustajaa()); System.out.println("punainen: " + vihje.getTaytyyEstaa()); System.out.println("\nseuraavat vastaavasti ristille:"); vihje.lisaaVihjeetListoihin(ruudukko.getMerkit(), Laatu.RISTI); System.out.println("sininen1: " + vihje.getEhkaHyodyllinen()); System.out.println("turkoosi: " + vihje.getRakennaHyokkays()); System.out.println("vihrea: " + vihje.getVarmaVoitto()); System.out.println("sininen2: " + vihje.getHairitseVastustajaa()); System.out.println("violetti: " + vihje.getVaroVastustajaa()); System.out.println("punainen: " + vihje.getTaytyyEstaa()); } }
UTF-8
Java
2,799
java
VihjeTest.java
Java
[ { "context": "stio;\nimport viidensuora.Laatu;\n\n/**\n *\n * @author aapomalk\n */\npublic class VihjeTest {\n private Vihje vi", "end": 380, "score": 0.9994049072265625, "start": 372, "tag": "USERNAME", "value": "aapomalk" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package vihjeToiminto; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import viidensuora.RistiNollaMuistio; import viidensuora.Laatu; /** * * @author aapomalk */ public class VihjeTest { private Vihje vihje; private RistiNollaMuistio ruudukko; public VihjeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { vihje = new Vihje(); ruudukko = new RistiNollaMuistio(); } @After public void tearDown() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // @Test public void kokeillaan() { ruudukko.lisaaRisti(0, 0); ruudukko.lisaaNolla(1, 1); ruudukko.lisaaRisti(1, 0); ruudukko.lisaaNolla(2, 0); ruudukko.lisaaRisti(0, 2); ruudukko.lisaaNolla(0, 1); ruudukko.lisaaRisti(-1, 1); ruudukko.lisaaNolla(2, 1); ruudukko.lisaaRisti(-2, 0); ruudukko.lisaaNolla(1, 3); ruudukko.lisaaRisti(2, 2); ruudukko.lisaaNolla(1, 2); ruudukko.lisaaRisti(-2, 2); ruudukko.lisaaNolla(1, -1); ruudukko.lisaaRisti(3, 1); ruudukko.lisaaNolla(1, 4); ruudukko.lisaaRisti(-2, 1); System.out.println("tarkasta seuraavat tulokset kasin: (nollalle)"); vihje.lisaaVihjeetListoihin(ruudukko.getMerkit(), Laatu.NOLLA); System.out.println("sininen1: " + vihje.getEhkaHyodyllinen()); System.out.println("turkoosi: " + vihje.getRakennaHyokkays()); System.out.println("vihrea: " + vihje.getVarmaVoitto()); System.out.println("sininen2: " + vihje.getHairitseVastustajaa()); System.out.println("violetti: " + vihje.getVaroVastustajaa()); System.out.println("punainen: " + vihje.getTaytyyEstaa()); System.out.println("\nseuraavat vastaavasti ristille:"); vihje.lisaaVihjeetListoihin(ruudukko.getMerkit(), Laatu.RISTI); System.out.println("sininen1: " + vihje.getEhkaHyodyllinen()); System.out.println("turkoosi: " + vihje.getRakennaHyokkays()); System.out.println("vihrea: " + vihje.getVarmaVoitto()); System.out.println("sininen2: " + vihje.getHairitseVastustajaa()); System.out.println("violetti: " + vihje.getVaroVastustajaa()); System.out.println("punainen: " + vihje.getTaytyyEstaa()); } }
2,799
0.618792
0.605216
89
30.449438
23.361359
77
false
false
0
0
0
0
0
0
0.752809
false
false
15
21ffc8404fa680474b65e119d408178d8e4ed2eb
35,278,861,421,244
f1fb1b33b9f09a26fe2b34351e4c52fd87753219
/window/window/src/main/java/androidx/window/WindowLayoutInfo.java
d19f91c0d2ce2cddd014efc22398d59318380185
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
raduschirliu/androidx
https://github.com/raduschirliu/androidx
eaafb061fdff733239f84a43b3b7682d5fe12aaa
772c0f9a2bf3a8b06ea3a839a4e4475b37908420
refs/heads/androidx-main
2023-03-19T16:27:33.078000
2021-03-11T16:40:33
2021-03-11T16:40:33
330,486,798
0
0
Apache-2.0
true
2021-02-13T16:04:50
2021-01-17T21:06:14
2021-02-05T15:53:46
2021-02-13T16:04:50
596,931
0
0
0
Java
false
false
/* * Copyright 2020 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 androidx.window; import androidx.annotation.NonNull; import androidx.core.util.Consumer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; /** * Contains the list of {@link DisplayFeature}-s located within the window. For example, a hinge or * display fold can go across the window, in which case it might make sense to separate the * visual content and interactive elements into two groups, e.g. list-detail or view-controls. * <p>Only the features that are present within the current window bounds are reported. Their * positions and sizes can change if the window is moved or resized on screen. * @see WindowManager#registerLayoutChangeCallback(Executor, Consumer) for tracking changes in * display feature list and positions. */ public final class WindowLayoutInfo { private final List<DisplayFeature> mDisplayFeatures; WindowLayoutInfo(@NonNull List<DisplayFeature> displayFeatures) { mDisplayFeatures = Collections.unmodifiableList(displayFeatures); } /** * Gets the list of physical display features within the window. */ @NonNull public List<DisplayFeature> getDisplayFeatures() { return mDisplayFeatures; } @NonNull @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("WindowLayoutInfo{ DisplayFeatures["); for (int i = 0; i < mDisplayFeatures.size(); i++) { DisplayFeature feature = mDisplayFeatures.get(i); sb.append(feature); if (i < mDisplayFeatures.size() - 1) { sb.append(", "); } } sb.append("] }"); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WindowLayoutInfo that = (WindowLayoutInfo) o; return mDisplayFeatures.equals(that.mDisplayFeatures); } @Override public int hashCode() { return mDisplayFeatures.hashCode(); } /** * Builder for {@link WindowLayoutInfo} objects. */ public static final class Builder { private List<DisplayFeature> mDisplayFeatures = new ArrayList<>(); /** * Creates an initially empty builder. */ public Builder() { } /** * Sets the display features for the {@link WindowLayoutInfo} instance. */ @NonNull public Builder setDisplayFeatures(@NonNull List<DisplayFeature> displayFeatures) { mDisplayFeatures.clear(); mDisplayFeatures.addAll(displayFeatures); return this; } /** * Creates a {@link WindowLayoutInfo} instance with the specified fields. * @return A WindowLayoutInfo instance. */ @NonNull public WindowLayoutInfo build() { return new WindowLayoutInfo(mDisplayFeatures); } } }
UTF-8
Java
3,664
java
WindowLayoutInfo.java
Java
[]
null
[]
/* * Copyright 2020 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 androidx.window; import androidx.annotation.NonNull; import androidx.core.util.Consumer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Executor; /** * Contains the list of {@link DisplayFeature}-s located within the window. For example, a hinge or * display fold can go across the window, in which case it might make sense to separate the * visual content and interactive elements into two groups, e.g. list-detail or view-controls. * <p>Only the features that are present within the current window bounds are reported. Their * positions and sizes can change if the window is moved or resized on screen. * @see WindowManager#registerLayoutChangeCallback(Executor, Consumer) for tracking changes in * display feature list and positions. */ public final class WindowLayoutInfo { private final List<DisplayFeature> mDisplayFeatures; WindowLayoutInfo(@NonNull List<DisplayFeature> displayFeatures) { mDisplayFeatures = Collections.unmodifiableList(displayFeatures); } /** * Gets the list of physical display features within the window. */ @NonNull public List<DisplayFeature> getDisplayFeatures() { return mDisplayFeatures; } @NonNull @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("WindowLayoutInfo{ DisplayFeatures["); for (int i = 0; i < mDisplayFeatures.size(); i++) { DisplayFeature feature = mDisplayFeatures.get(i); sb.append(feature); if (i < mDisplayFeatures.size() - 1) { sb.append(", "); } } sb.append("] }"); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; WindowLayoutInfo that = (WindowLayoutInfo) o; return mDisplayFeatures.equals(that.mDisplayFeatures); } @Override public int hashCode() { return mDisplayFeatures.hashCode(); } /** * Builder for {@link WindowLayoutInfo} objects. */ public static final class Builder { private List<DisplayFeature> mDisplayFeatures = new ArrayList<>(); /** * Creates an initially empty builder. */ public Builder() { } /** * Sets the display features for the {@link WindowLayoutInfo} instance. */ @NonNull public Builder setDisplayFeatures(@NonNull List<DisplayFeature> displayFeatures) { mDisplayFeatures.clear(); mDisplayFeatures.addAll(displayFeatures); return this; } /** * Creates a {@link WindowLayoutInfo} instance with the specified fields. * @return A WindowLayoutInfo instance. */ @NonNull public WindowLayoutInfo build() { return new WindowLayoutInfo(mDisplayFeatures); } } }
3,664
0.659662
0.656932
113
31.424778
28.299225
99
false
false
0
0
0
0
0
0
0.362832
false
false
15
1c7dd2691b1eec28f5f084ab6110963269c336a3
35,278,861,421,140
909cd0053a1e2a5e6e281d01493d2620053d465d
/obd-api-android/src/main/java/com/github/zanderman/obd/receivers/OBDReceiver.java
e5045ca1835d1a1988db8d4d37175210e6c15d01
[]
no_license
zanderman/obd-api-android
https://github.com/zanderman/obd-api-android
bc0fb0cb1d73e826956f03e4e941ac6d69b5396e
0507749247024c1769fabb38418d81f7c9c33e36
refs/heads/master
2021-01-21T12:57:56.081000
2016-04-29T19:09:05
2016-04-29T19:09:05
52,851,623
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.zanderman.obd.receivers; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.github.zanderman.obd.R; import com.github.zanderman.obd.interfaces.BluetoothCallbackInterface; import com.github.zanderman.obd.interfaces.CommunicationCallbackInterface; /** * Class: * OBDReceiver * * Description: * Primary broadcast receiver representation for all OBD Bluetooth actions. */ public class OBDReceiver extends BroadcastReceiver { /** * Private members. */ final BluetoothCallbackInterface bluetoothCallbackInterface; final CommunicationCallbackInterface communicationCallbackInterface; /** * Custom Broadcasts. */ public static final String COMMUNICATION_RECEIVE = "com.github.zanderman.obd.custom.intent.communication.receive"; public static final String COMMUNICATION_TRANSMIT = "com.github.zanderman.obd.custom.intent.communication.transmit"; /** * Default Constructor: * OBDReceiver( ) * * Description: * Creates a new OBDReceiver object with initialized members. */ public OBDReceiver() { super(); this.bluetoothCallbackInterface = null; this.communicationCallbackInterface = null; } /** * Constructor: * OBDReceiver( final BluetoothCallbackInterface ) * * Description: * Creates a new OBDReceiver object with a specific Bluetooth callback interface. * * @param bluetoothCallbackInterface Primary callback interface used. */ public OBDReceiver(final BluetoothCallbackInterface bluetoothCallbackInterface) { super(); /** * Initialize members. */ this.bluetoothCallbackInterface = bluetoothCallbackInterface; this.communicationCallbackInterface = null; } /** * Constructor: * OBDReceiver( final CommunicationCallbackInterface ) * * Description: * Creates a new OBDReceiver object with a specific Communication callback interface to * with which to send communication actions to. * * @param communicationCallbackInterface Primary callback interface used. */ public OBDReceiver(final CommunicationCallbackInterface communicationCallbackInterface) { super(); /** * Initialize members. */ this.communicationCallbackInterface = communicationCallbackInterface; this.bluetoothCallbackInterface= null; } /** * Method: * onReceive( Context, Intent ) * * Description: * Catches all app-wide broadcasts and interprets them based on this class's needs. * * @param context The context in which the broadcast originated. * @param intent The intent that was packaged with the broadcast. */ @Override public void onReceive(Context context, Intent intent) { /** * Check for different actions. */ switch ( intent.getAction() ) { case BluetoothAdapter.ACTION_DISCOVERY_STARTED: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryStarted(); case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryFinished(); case BluetoothDevice.ACTION_FOUND: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryFound((BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); case OBDReceiver.COMMUNICATION_RECEIVE: if ( this.communicationCallbackInterface != null ) this.communicationCallbackInterface.receive( ); case OBDReceiver.COMMUNICATION_TRANSMIT: if ( this.communicationCallbackInterface != null ) this.communicationCallbackInterface.transmit( context.getString(R.string.OutgoingData) ); } } }
UTF-8
Java
4,261
java
OBDReceiver.java
Java
[ { "context": "package com.github.zanderman.obd.receivers;\n\nimport android.bluetooth.Bluetoot", "end": 28, "score": 0.9975703358650208, "start": 19, "tag": "USERNAME", "value": "zanderman" }, { "context": "import android.content.Intent;\n\nimport com.github.zanderman.obd.R;\nimport ...
null
[]
package com.github.zanderman.obd.receivers; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.github.zanderman.obd.R; import com.github.zanderman.obd.interfaces.BluetoothCallbackInterface; import com.github.zanderman.obd.interfaces.CommunicationCallbackInterface; /** * Class: * OBDReceiver * * Description: * Primary broadcast receiver representation for all OBD Bluetooth actions. */ public class OBDReceiver extends BroadcastReceiver { /** * Private members. */ final BluetoothCallbackInterface bluetoothCallbackInterface; final CommunicationCallbackInterface communicationCallbackInterface; /** * Custom Broadcasts. */ public static final String COMMUNICATION_RECEIVE = "com.github.zanderman.obd.custom.intent.communication.receive"; public static final String COMMUNICATION_TRANSMIT = "com.github.zanderman.obd.custom.intent.communication.transmit"; /** * Default Constructor: * OBDReceiver( ) * * Description: * Creates a new OBDReceiver object with initialized members. */ public OBDReceiver() { super(); this.bluetoothCallbackInterface = null; this.communicationCallbackInterface = null; } /** * Constructor: * OBDReceiver( final BluetoothCallbackInterface ) * * Description: * Creates a new OBDReceiver object with a specific Bluetooth callback interface. * * @param bluetoothCallbackInterface Primary callback interface used. */ public OBDReceiver(final BluetoothCallbackInterface bluetoothCallbackInterface) { super(); /** * Initialize members. */ this.bluetoothCallbackInterface = bluetoothCallbackInterface; this.communicationCallbackInterface = null; } /** * Constructor: * OBDReceiver( final CommunicationCallbackInterface ) * * Description: * Creates a new OBDReceiver object with a specific Communication callback interface to * with which to send communication actions to. * * @param communicationCallbackInterface Primary callback interface used. */ public OBDReceiver(final CommunicationCallbackInterface communicationCallbackInterface) { super(); /** * Initialize members. */ this.communicationCallbackInterface = communicationCallbackInterface; this.bluetoothCallbackInterface= null; } /** * Method: * onReceive( Context, Intent ) * * Description: * Catches all app-wide broadcasts and interprets them based on this class's needs. * * @param context The context in which the broadcast originated. * @param intent The intent that was packaged with the broadcast. */ @Override public void onReceive(Context context, Intent intent) { /** * Check for different actions. */ switch ( intent.getAction() ) { case BluetoothAdapter.ACTION_DISCOVERY_STARTED: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryStarted(); case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryFinished(); case BluetoothDevice.ACTION_FOUND: if ( this.bluetoothCallbackInterface != null ) this.bluetoothCallbackInterface.discoveryFound((BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)); case OBDReceiver.COMMUNICATION_RECEIVE: if ( this.communicationCallbackInterface != null ) this.communicationCallbackInterface.receive( ); case OBDReceiver.COMMUNICATION_TRANSMIT: if ( this.communicationCallbackInterface != null ) this.communicationCallbackInterface.transmit( context.getString(R.string.OutgoingData) ); } } }
4,261
0.668388
0.668388
125
33.088001
32.276558
142
false
false
0
0
0
0
0
0
0.232
false
false
15
e9a58e8c0285dd9d957adc6f5a8b4bf3d7063c75
38,113,539,818,980
1331855a8794aa5ea8c54935f941fe9e0d618b35
/Java/Java_Course_Assignments/Contact/src/com/kevin/contact/obsolete/build4/storagemanage/StorageManage.java
af1dc88621cb6df3731ef81ccdcd414c9535adb3
[ "MIT" ]
permissive
kevinkda/Java_Course_Assignments
https://github.com/kevinkda/Java_Course_Assignments
9abf31e2729afd9bbec22fd5555878f164a4aaf5
9f649aa82b5835e0eb89cb613994029da2d1172b
refs/heads/master
2020-08-02T03:59:37.032000
2020-06-28T03:48:07
2020-06-28T03:48:07
211,130,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2019 Kevin KDA. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.kevin.contact.obsolete.build4.storagemanage; import com.kevin.contact.obsolete.build4.ManageControl; import com.kevin.contact.obsolete.build4.contact.Contact; import java.io.*; import java.util.ArrayList; /** * @author Kevin KDA * @version 1.0 * @project Java_Course_Assignments * @package com.kevin.contact.newbuild.storagemanage * @classname StorageManage * @description TODO * @date 2019/10/23 19:47 * @interface * @enum */ public class StorageManage extends ManageControl implements Serializable { public StorageManage() throws Exception { } private static final long serialVersionUID = -8402795596948954371L; public static void storage(ArrayList<Contact> arrayListData) throws IOException { String filepath = "./Contact/resource/Data.txt";//注意filepath的内容; // File file = new File(filepath); // ObjectOutputStream objectOutputStream; // objectOutputStream = new ObjectOutputStream(fileOutputStream); // objectOutputStream.writeUnshared(arrayListData); // objectOutputStream.writeObject(arrayListData); // objectOutputStream.close(); // File file = new File("./test.txt"); // if(!file.exists()) { // file.createNewFile(); // System.out.println("创建文件成功"); // } // File directory = new File("");//参数为空 // String courseFile = directory.getCanonicalPath() ; // System.out.println(courseFile); // try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath),false))) { // try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath)))) { // objectOutputStream.writeObject(arrayListData); // objectOutputStream.close(); // }catch (FileNotFoundException e) { // System.out.println("文件不存在或者文件不可读或者文件是目录"); // } catch (IOException e) { // System.out.println("读取过程存在异常"); // } ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath))); objectOutputStream.writeObject(arrayListData); objectOutputStream.close(); // DataOutputStream os = new DataOutputStream(new FileOutputStream(new File(filepath))); // os.writeUTF(String.valueOf(arrayListData)); // try (FileOutputStream fos = new FileOutputStream(new File(filepath))) { // for (Iterator it = arrayListData.iterator(); it.hasNext(); ) { //便利arrylist // String str = (String) it.next(); //将list中的元素转为str遍历给String // fos.write(str.getBytes()); //字节流转为byte数组写入 // fos.write("\r\n".getBytes()); //代表windows系统的换行。 // } // fos.close(); // } // FileWriter fileWriter = new FileWriter(filepath); // fileWriter.write(String.valueOf(arrayListData)); // fileWriter.close(); } static ArrayList<Contact> arrayList = new ArrayList<Contact>(); public void read() throws Exception { // FileInputStream fileInputStream = new FileInputStream("resource/1.txt"); // ObjectInputStream objectInputStream 1= new ObjectInputStream(fileInputStream); // // String filepath = "./Contact/resource/Data.txt"; // ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filepath))); // arrayList=(ArrayList<Contact>)objectInputStream.readObject(); // //// arrayList = (ArrayList) objectInputStream.readObject(); // // for (Contact c:arrayList // ) { // createDataItem(c); // } // objectInputStream.close(); // System.out.println(arrayListData.get(0).getStrName()); String filepath = "./Contact/resource/Data.txt"; ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filepath))); arrayListData = (ArrayList<Contact>) objectInputStream.readObject(); objectInputStream.close(); System.out.println(arrayListData.get(0).getStrName()); // Object one = objectInputStream.readObject(); // Object twObject = objectInputStream.readObject(); // Student sone = (Student)one; // Student stwo = (Student)twObject; // System.out.println("name: "+sone.getName()+" age:"+sone.getAge()); // System.out.println("name: "+stwo.getName()+" age:"+stwo.getAge()); // ObjectInputStream ois=new ObjectInputStream(new FileInputStream("record.txt")); // Contact s1=(Contact) ois.readObject(); // System.out.println(s1); // ois.close(); } }
UTF-8
Java
5,218
java
StorageManage.java
Java
[ { "context": "/*\n * Copyright (c) 2019 Kevin KDA. Lorem ipsum dolor sit amet, consectetur adipisci", "end": 34, "score": 0.9997633099555969, "start": 25, "tag": "NAME", "value": "Kevin KDA" }, { "context": ".io.*;\nimport java.util.ArrayList;\n\n/**\n * @author Kevin KDA\n * @versio...
null
[]
/* * Copyright (c) 2019 <NAME>. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.kevin.contact.obsolete.build4.storagemanage; import com.kevin.contact.obsolete.build4.ManageControl; import com.kevin.contact.obsolete.build4.contact.Contact; import java.io.*; import java.util.ArrayList; /** * @author <NAME> * @version 1.0 * @project Java_Course_Assignments * @package com.kevin.contact.newbuild.storagemanage * @classname StorageManage * @description TODO * @date 2019/10/23 19:47 * @interface * @enum */ public class StorageManage extends ManageControl implements Serializable { public StorageManage() throws Exception { } private static final long serialVersionUID = -8402795596948954371L; public static void storage(ArrayList<Contact> arrayListData) throws IOException { String filepath = "./Contact/resource/Data.txt";//注意filepath的内容; // File file = new File(filepath); // ObjectOutputStream objectOutputStream; // objectOutputStream = new ObjectOutputStream(fileOutputStream); // objectOutputStream.writeUnshared(arrayListData); // objectOutputStream.writeObject(arrayListData); // objectOutputStream.close(); // File file = new File("./test.txt"); // if(!file.exists()) { // file.createNewFile(); // System.out.println("创建文件成功"); // } // File directory = new File("");//参数为空 // String courseFile = directory.getCanonicalPath() ; // System.out.println(courseFile); // try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath),false))) { // try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath)))) { // objectOutputStream.writeObject(arrayListData); // objectOutputStream.close(); // }catch (FileNotFoundException e) { // System.out.println("文件不存在或者文件不可读或者文件是目录"); // } catch (IOException e) { // System.out.println("读取过程存在异常"); // } ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(filepath))); objectOutputStream.writeObject(arrayListData); objectOutputStream.close(); // DataOutputStream os = new DataOutputStream(new FileOutputStream(new File(filepath))); // os.writeUTF(String.valueOf(arrayListData)); // try (FileOutputStream fos = new FileOutputStream(new File(filepath))) { // for (Iterator it = arrayListData.iterator(); it.hasNext(); ) { //便利arrylist // String str = (String) it.next(); //将list中的元素转为str遍历给String // fos.write(str.getBytes()); //字节流转为byte数组写入 // fos.write("\r\n".getBytes()); //代表windows系统的换行。 // } // fos.close(); // } // FileWriter fileWriter = new FileWriter(filepath); // fileWriter.write(String.valueOf(arrayListData)); // fileWriter.close(); } static ArrayList<Contact> arrayList = new ArrayList<Contact>(); public void read() throws Exception { // FileInputStream fileInputStream = new FileInputStream("resource/1.txt"); // ObjectInputStream objectInputStream 1= new ObjectInputStream(fileInputStream); // // String filepath = "./Contact/resource/Data.txt"; // ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filepath))); // arrayList=(ArrayList<Contact>)objectInputStream.readObject(); // //// arrayList = (ArrayList) objectInputStream.readObject(); // // for (Contact c:arrayList // ) { // createDataItem(c); // } // objectInputStream.close(); // System.out.println(arrayListData.get(0).getStrName()); String filepath = "./Contact/resource/Data.txt"; ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filepath))); arrayListData = (ArrayList<Contact>) objectInputStream.readObject(); objectInputStream.close(); System.out.println(arrayListData.get(0).getStrName()); // Object one = objectInputStream.readObject(); // Object twObject = objectInputStream.readObject(); // Student sone = (Student)one; // Student stwo = (Student)twObject; // System.out.println("name: "+sone.getName()+" age:"+sone.getAge()); // System.out.println("name: "+stwo.getName()+" age:"+stwo.getAge()); // ObjectInputStream ois=new ObjectInputStream(new FileInputStream("record.txt")); // Contact s1=(Contact) ois.readObject(); // System.out.println(s1); // ois.close(); } }
5,212
0.664564
0.655499
126
39.26984
32.759445
128
false
false
0
0
0
0
0
0
0.507937
false
false
15
83773a9aac0f5ecacbfeb3c0b5da8e49e8aaf19d
39,024,072,895,736
87b4a070f3e6106cf552dfe62d8bcb8d587c4c2b
/src/main/java/com/shoppingsocieties/repository/ProductRepository.java
da30bb54ce627a69e959b22f9fd89f0d384e72c3
[]
no_license
shashimal/shoppingsocieties
https://github.com/shashimal/shoppingsocieties
f33c6b31f3f184da6c1213c999d5ac3840be9360
3149ad8ed38fad8a6e48740e6be77a44c69140c1
refs/heads/master
2021-08-08T19:41:21.571000
2020-04-17T03:45:21
2020-04-17T03:45:21
157,310,503
0
0
null
false
2020-04-17T03:45:22
2018-11-13T02:49:17
2018-11-13T03:00:46
2020-04-17T03:45:22
1,058
0
0
0
Java
false
false
package com.shoppingsocieties.repository; import com.shoppingsocieties.entity.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * * Responsible for handling all the database operations of product entity * */ @Repository public interface ProductRepository extends JpaRepository<Product,Long> { }
UTF-8
Java
376
java
ProductRepository.java
Java
[]
null
[]
package com.shoppingsocieties.repository; import com.shoppingsocieties.entity.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * * Responsible for handling all the database operations of product entity * */ @Repository public interface ProductRepository extends JpaRepository<Product,Long> { }
376
0.819149
0.819149
14
25.857143
28.08115
73
false
false
0
0
0
0
0
0
0.357143
false
false
15
3fe310f88a1484b74ce5098bd851d47249875c1d
39,573,828,672,166
b70050f4c7ee1b0960d441ada5a3f7d1abc1f760
/Temario/T_00/Networking/src/fileserver/FileServer.java
8942e257b4944bd6be35357b99b6daad9c781416
[]
no_license
ebtineo/2-DAW-Desarrollo-web-en-entorno-servidor
https://github.com/ebtineo/2-DAW-Desarrollo-web-en-entorno-servidor
254dbfdb3df1ba6ccacea33c1bc7dce3a21abc96
b2463d6ab666b27d4f7c6c67b8d24471d77dc749
refs/heads/master
2021-01-30T19:35:59.197000
2020-02-27T11:41:13
2020-02-27T11:41:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package fileserver; import java.net.*; import java.io.*; /** * * @author jose */ public class FileServer { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(2222); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(-1); } System.out.println("FileServer: Atendiendo peticiones de conexión en el puerto 2222"); // Socket para conectarse al cliente Socket clientSocket = null; while (true) { try { clientSocket = serverSocket.accept(); ConexionCliente conexion = new ConexionCliente(clientSocket); conexion.start(); System.out.println("Aceptando conexión desde " + clientSocket.getInetAddress() + ":" + clientSocket.getPort()); } catch (Exception e) { System.err.println(e.getMessage()); } } } public static class ConexionCliente extends Thread { private Socket socket; public ConexionCliente(Socket socket) { this.socket = socket; } @Override public void run() { BufferedReader entrada; OutputStream salida; try { entrada = new BufferedReader(new InputStreamReader(socket.getInputStream())); salida = socket.getOutputStream(); File fichero = new File(entrada.readLine()); System.out.println("Transfiriendo :" + fichero.getAbsolutePath()); FileInputStream entradaFichero = new FileInputStream(fichero); int dato; while ((dato = entradaFichero.read())!=-1) salida.write(dato); entradaFichero.close(); salida.close(); entrada.close(); socket.close(); } catch (IOException e) { System.err.println(e.getMessage()); try { socket.close(); } catch (IOException ex) {} } } } }
UTF-8
Java
2,296
java
FileServer.java
Java
[ { "context": "t java.net.*;\nimport java.io.*;\n\n/**\n *\n * @author jose\n */\npublic class FileServer {\n public static v", "end": 182, "score": 0.9951805472373962, "start": 178, "tag": "USERNAME", "value": "jose" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package fileserver; import java.net.*; import java.io.*; /** * * @author jose */ public class FileServer { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(2222); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(-1); } System.out.println("FileServer: Atendiendo peticiones de conexión en el puerto 2222"); // Socket para conectarse al cliente Socket clientSocket = null; while (true) { try { clientSocket = serverSocket.accept(); ConexionCliente conexion = new ConexionCliente(clientSocket); conexion.start(); System.out.println("Aceptando conexión desde " + clientSocket.getInetAddress() + ":" + clientSocket.getPort()); } catch (Exception e) { System.err.println(e.getMessage()); } } } public static class ConexionCliente extends Thread { private Socket socket; public ConexionCliente(Socket socket) { this.socket = socket; } @Override public void run() { BufferedReader entrada; OutputStream salida; try { entrada = new BufferedReader(new InputStreamReader(socket.getInputStream())); salida = socket.getOutputStream(); File fichero = new File(entrada.readLine()); System.out.println("Transfiriendo :" + fichero.getAbsolutePath()); FileInputStream entradaFichero = new FileInputStream(fichero); int dato; while ((dato = entradaFichero.read())!=-1) salida.write(dato); entradaFichero.close(); salida.close(); entrada.close(); socket.close(); } catch (IOException e) { System.err.println(e.getMessage()); try { socket.close(); } catch (IOException ex) {} } } } }
2,296
0.534002
0.529643
74
30
25.894276
127
false
false
0
0
0
0
0
0
0.445946
false
false
15
dfef8230c411df96b3c20285dc3fb78020b330f0
35,424,890,290,125
b135723e0924c9f31f5450c00bce26d0a1ce0f7f
/SPRING-EXAMEN-JAVA2-VRAAG2-START/src/main/java/edu/ap/spring/ExamApplication.java
bd68e0c55d882c9661acf2bed85e473ae001b641
[]
no_license
daankennes/Examen-Java-Advanced
https://github.com/daankennes/Examen-Java-Advanced
696b8e7d31931bc6d572364e5ac14ff0ac6b1356
2ff338b99b5c0eedc59c35dc9c02067c8e7eaf2e
refs/heads/master
2020-03-11T14:19:11.208000
2018-04-18T14:06:48
2018-04-18T14:06:48
130,049,946
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ap.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ExamApplication { @Autowired private Exam exam; @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return (args) -> { //test opgave 1 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; int[] res0 = exam.getPrimes(numbers); for (int i : res0) { System.out.print(", "); System.out.print(i); } System.out.println(""); //test opgave 2 int res1 = exam.countLowercaseCharacters("WiE hEEft ER examENstress?"); System.out.println(res1); //14 //test opgave 3 int res2 = exam.sumOfX(exam.generatePoints()); System.out.println(res2); //4 //test opgave 4 String res3 = exam.getXOverTwo(exam.generatePoints()); System.out.println(res3); }; } public static void main(String[] args) { SpringApplication.run(ExamApplication.class, args); } }
UTF-8
Java
1,283
java
ExamApplication.java
Java
[]
null
[]
package edu.ap.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ExamApplication { @Autowired private Exam exam; @Bean public CommandLineRunner commandLineRunner(ApplicationContext ctx) { return (args) -> { //test opgave 1 int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; int[] res0 = exam.getPrimes(numbers); for (int i : res0) { System.out.print(", "); System.out.print(i); } System.out.println(""); //test opgave 2 int res1 = exam.countLowercaseCharacters("WiE hEEft ER examENstress?"); System.out.println(res1); //14 //test opgave 3 int res2 = exam.sumOfX(exam.generatePoints()); System.out.println(res2); //4 //test opgave 4 String res3 = exam.getXOverTwo(exam.generatePoints()); System.out.println(res3); }; } public static void main(String[] args) { SpringApplication.run(ExamApplication.class, args); } }
1,283
0.705378
0.669525
46
26.913044
23.745779
91
false
false
0
0
0
0
0
0
2.630435
false
false
15
3805db6b9456bf19bd8fea2f3d67ce6e5d17ffdb
37,589,553,790,261
e1ccd5edee55f48b315d7d4d263474c9dce4c19e
/src/services/restlet/api/ClientinfoResource.java
a1d24a776ae2bb6931ce0a5f28b83b2178a451b7
[]
no_license
wenhsiaoyi/ss3cpm
https://github.com/wenhsiaoyi/ss3cpm
fdd5e3c03d93b0205660bb77cb3d5e8ca86e4f40
28dfd02025e9c904a8ec46a67298c4409748cab7
refs/heads/master
2016-08-08T16:19:07.312000
2015-07-22T09:09:00
2015-07-22T09:09:00
39,484,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package services.restlet.api; import host.application.service.ApplicationConstant; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import system.util.JsonTK; import data.database.dao.ClientinfoDao; import data.database.vo.ClientinfoVo; import edu.lib.common.primitive.NullTK; import edu.lib.common.primitive.StringTK; import edu.lib.common.util.DateConverter; /** * @author wenhsiaoyi * * * * {"sys": "PM", "uid": 3150, "userid": "wenhsiaoyi", "username": "文孝義", "internetip": "60.248.131.1", "intranetip": "192.168.1.215", "longitude": "120.3", "latitude": "21.3", "address": "", "lasttm": "2015-04-17T06:21:37.516Z" //ISO-8601 calendar system toJSON() } */ public class ClientinfoResource extends ServerResource { private static final Log logger = LogFactory.getLog(ClientinfoResource.class); /** * 交易處理 * @param entity JsonRepresentation * @return Representation */ @Post("json") public Representation doTransaction(JsonRepresentation entity) { Representation resp = null; JSONObject message = null; JSONObject response = new JSONObject(); //String json = ""; String status = ""; try{ if(NullTK.isNull(entity)) { throw new Exception("EH001:HTTP 內容異常"); } // 取出內文 message = entity.getJsonObject(); if(NullTK.isNull(message)) { throw new Exception("EH002:上行訊息內容異常:JsonObject Parse Error"); } //logger.info("JSON:" + message.toString()); String sys = JsonTK.getString(message, "sys"); if(!StringTK.equals("PM", sys)) { throw new Exception("資料格式有誤 sys"); } //解析內文 ClientinfoVo vo = parse(message); ClientinfoDao dao = new ClientinfoDao(); if(!NullTK.isNull(vo)) { dao.insert(vo); }else{ throw new Exception("資料格式有誤"); } JsonTK.putString(response, "status", ApplicationConstant.TX_SUCCESS); }catch(Exception e){ logger.error("doTransaction error:" + e.getMessage()); status = e.getMessage(); JsonTK.putString(response, "status", status); JsonTK.putString(response, "message", status); } //建立回傳訊息內容格式 resp = blockResponseRepresentation(response); return resp; } private JsonRepresentation blockResponseRepresentation(JSONObject message) { JsonRepresentation jr = new JsonRepresentation(message); return jr; } private ClientinfoVo parse(JSONObject message) throws Exception { ClientinfoVo vo = new ClientinfoVo(); Timestamp ts = null; try{ long uid = JsonTK.getLong(message, "uid"); String userid = JsonTK.getString(message, "userid"); String username = JsonTK.getString(message, "username"); String internetip = JsonTK.getString(message, "internetip"); String intranetip = JsonTK.getString(message, "intranetip"); String longitude = JsonTK.getString(message, "longitude"); String latitude = JsonTK.getString(message, "latitude"); String lasttm = JsonTK.getString(message, "lasttm"); try{ if(!StringTK.isEmpty(lasttm)) { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); LocalDateTime ldt = LocalDateTime.parse(lasttm, df); ts = Timestamp.valueOf(ldt); //logger.info("ts:" + ts.toString()); } }catch(Exception e){ logger.warn("ISO8610 Err:" + e.getMessage()); } if(NullTK.isNull(ts)){ ts = DateConverter.getTimestamp(); } vo.setUid(uid); vo.setUserid(userid); vo.setUsername(username); vo.setInternetip(internetip); vo.setIntranetip(intranetip); vo.setLongitude(longitude); vo.setLatitude(latitude); vo.setLasttm(ts); vo.setAddress(""); //logger.info("vo:" + vo); }catch(Exception e){ logger.error("Clientinfo error: " + e); throw e; } return vo; } }
UTF-8
Java
4,266
java
ClientinfoResource.java
Java
[ { "context": "edu.lib.common.util.DateConverter;\n\n/**\n * @author wenhsiaoyi\n * \n * \n * \n * \n {\"sys\": \"PM\",\n \"uid\": 3150,\n ", "end": 783, "score": 0.9996508359909058, "start": 773, "tag": "USERNAME", "value": "wenhsiaoyi" }, { "context": " \n * \n {\"sys\": \"PM\",...
null
[]
package services.restlet.api; import host.application.service.ApplicationConstant; import java.sql.Timestamp; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; import org.restlet.ext.json.JsonRepresentation; import org.restlet.representation.Representation; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import system.util.JsonTK; import data.database.dao.ClientinfoDao; import data.database.vo.ClientinfoVo; import edu.lib.common.primitive.NullTK; import edu.lib.common.primitive.StringTK; import edu.lib.common.util.DateConverter; /** * @author wenhsiaoyi * * * * {"sys": "PM", "uid": 3150, "userid": "wenhsiaoyi", "username": "文孝義", "internetip": "172.16.17.32", "intranetip": "192.168.1.215", "longitude": "120.3", "latitude": "21.3", "address": "", "lasttm": "2015-04-17T06:21:37.516Z" //ISO-8601 calendar system toJSON() } */ public class ClientinfoResource extends ServerResource { private static final Log logger = LogFactory.getLog(ClientinfoResource.class); /** * 交易處理 * @param entity JsonRepresentation * @return Representation */ @Post("json") public Representation doTransaction(JsonRepresentation entity) { Representation resp = null; JSONObject message = null; JSONObject response = new JSONObject(); //String json = ""; String status = ""; try{ if(NullTK.isNull(entity)) { throw new Exception("EH001:HTTP 內容異常"); } // 取出內文 message = entity.getJsonObject(); if(NullTK.isNull(message)) { throw new Exception("EH002:上行訊息內容異常:JsonObject Parse Error"); } //logger.info("JSON:" + message.toString()); String sys = JsonTK.getString(message, "sys"); if(!StringTK.equals("PM", sys)) { throw new Exception("資料格式有誤 sys"); } //解析內文 ClientinfoVo vo = parse(message); ClientinfoDao dao = new ClientinfoDao(); if(!NullTK.isNull(vo)) { dao.insert(vo); }else{ throw new Exception("資料格式有誤"); } JsonTK.putString(response, "status", ApplicationConstant.TX_SUCCESS); }catch(Exception e){ logger.error("doTransaction error:" + e.getMessage()); status = e.getMessage(); JsonTK.putString(response, "status", status); JsonTK.putString(response, "message", status); } //建立回傳訊息內容格式 resp = blockResponseRepresentation(response); return resp; } private JsonRepresentation blockResponseRepresentation(JSONObject message) { JsonRepresentation jr = new JsonRepresentation(message); return jr; } private ClientinfoVo parse(JSONObject message) throws Exception { ClientinfoVo vo = new ClientinfoVo(); Timestamp ts = null; try{ long uid = JsonTK.getLong(message, "uid"); String userid = JsonTK.getString(message, "userid"); String username = JsonTK.getString(message, "username"); String internetip = JsonTK.getString(message, "internetip"); String intranetip = JsonTK.getString(message, "intranetip"); String longitude = JsonTK.getString(message, "longitude"); String latitude = JsonTK.getString(message, "latitude"); String lasttm = JsonTK.getString(message, "lasttm"); try{ if(!StringTK.isEmpty(lasttm)) { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); LocalDateTime ldt = LocalDateTime.parse(lasttm, df); ts = Timestamp.valueOf(ldt); //logger.info("ts:" + ts.toString()); } }catch(Exception e){ logger.warn("ISO8610 Err:" + e.getMessage()); } if(NullTK.isNull(ts)){ ts = DateConverter.getTimestamp(); } vo.setUid(uid); vo.setUserid(userid); vo.setUsername(username); vo.setInternetip(internetip); vo.setIntranetip(intranetip); vo.setLongitude(longitude); vo.setLatitude(latitude); vo.setLasttm(ts); vo.setAddress(""); //logger.info("vo:" + vo); }catch(Exception e){ logger.error("Clientinfo error: " + e); throw e; } return vo; } }
4,266
0.683301
0.668666
171
23.374269
21.37524
86
false
false
0
0
0
0
0
0
2.321637
false
false
15
9c0fb2d5497d0b55ca68ae12e8706bce361afe8b
19,439,022,052,454
037a637a60d6049a01ac50f6aaa6e28da7565fbe
/docs/assets/src/main/java/com/orange/srs/refreport/model/TO/inventory/ExportSpecificInventoryGkTO.java
30eefe2f8f9211ab46bde39b68b1bd721a73692b
[]
no_license
binazon/angular
https://github.com/binazon/angular
3e9006880f023a37205d8d2a6e5439d54ef28b0d
fdaaf36b60bd06a99c3076838bf3a50ad308533e
refs/heads/master
2022-12-02T02:46:15.327000
2019-07-30T10:05:09
2019-07-30T10:05:09
197,146,414
1
0
null
false
2022-11-24T05:22:55
2019-07-16T07:47:53
2021-01-14T11:26:50
2022-11-24T05:22:52
88,877
1
0
7
TypeScript
false
false
package com.orange.srs.refreport.model.TO.inventory; public class ExportSpecificInventoryGkTO { public String entityId; public String label; public ExportSpecificInventoryGkTO(String entityId, String label) { super(); this.entityId = entityId; this.label = label; } @Override public String toString() { return "ExportSpecificInventoryGkTO [entityId=" + entityId + ", label=" + label + "]"; } }
UTF-8
Java
414
java
ExportSpecificInventoryGkTO.java
Java
[]
null
[]
package com.orange.srs.refreport.model.TO.inventory; public class ExportSpecificInventoryGkTO { public String entityId; public String label; public ExportSpecificInventoryGkTO(String entityId, String label) { super(); this.entityId = entityId; this.label = label; } @Override public String toString() { return "ExportSpecificInventoryGkTO [entityId=" + entityId + ", label=" + label + "]"; } }
414
0.731884
0.731884
19
20.789474
24.867182
88
false
false
0
0
0
0
0
0
1.263158
false
false
15
54d05f1dbade0cada3439345cd21133496bd87ab
9,199,820,010,350
8f4eec46d2d76692a2fb6260df310d0975407e6f
/puc/integracao/src/test/java/br/com/pucminas/integracao/BaralhoTest.java
1c2caba07fb6645dcaf5858003444396d5d46ef9
[]
no_license
Pongelupe/javaEE_studies
https://github.com/Pongelupe/javaEE_studies
6557259c9280834c63ad8ec2a980b37b73741af2
edcf915c5561785137f168378f231d7326663bf4
refs/heads/master
2022-12-20T13:44:33.735000
2020-01-03T01:08:40
2020-01-03T01:08:40
99,395,536
1
0
null
false
2022-12-16T04:25:18
2017-08-05T03:09:26
2020-01-08T17:57:05
2022-12-16T04:25:15
11,213
1
0
9
Java
false
false
package br.com.pucminas.integracao; import org.junit.Assert; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class BaralhoTest { GeradorNumeroAleatorio mock; Baralho baralho = new Baralho(); /** Fixture initialization (common initialization * for all tests). **/ @Before public void setUp() { //Gera Mock que devolve 1� carta mock = new GeradorMock(0); //Cria Baralho e seta o objeto falso baralho = new Baralho(); baralho.setGerador(mock); } @Test public void testDevolveCartaAleatoriaERetiraDoBaralho() throws Exception { //Sabendo que no nosso baralho a 1� carta � o A de Copas assertEquals(new Carta(1, Carta.naipes.COPAS), baralho.devolveCarta()); //Como a carta foi retirada, e sabendo que nosso baralho tem o 2 de Copas na seq��ncia assertEquals(new Carta(2, Carta.naipes.COPAS), baralho.devolveCarta()); } }
UTF-8
Java
960
java
BaralhoTest.java
Java
[]
null
[]
package br.com.pucminas.integracao; import org.junit.Assert; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class BaralhoTest { GeradorNumeroAleatorio mock; Baralho baralho = new Baralho(); /** Fixture initialization (common initialization * for all tests). **/ @Before public void setUp() { //Gera Mock que devolve 1� carta mock = new GeradorMock(0); //Cria Baralho e seta o objeto falso baralho = new Baralho(); baralho.setGerador(mock); } @Test public void testDevolveCartaAleatoriaERetiraDoBaralho() throws Exception { //Sabendo que no nosso baralho a 1� carta � o A de Copas assertEquals(new Carta(1, Carta.naipes.COPAS), baralho.devolveCarta()); //Como a carta foi retirada, e sabendo que nosso baralho tem o 2 de Copas na seq��ncia assertEquals(new Carta(2, Carta.naipes.COPAS), baralho.devolveCarta()); } }
960
0.689474
0.683158
32
28.71875
25.878605
91
false
false
0
0
0
0
0
0
0.59375
false
false
15
05a466f46cf475a60cdc69430a1de2acf4f4c42f
36,249,524,010,704
e2e2eb674909acd642a2103676d909e175a406f5
/LeetCode/src/tree/RecoverTree.java
40ad585e3a94d0071889133e9f1dccfce7981591
[]
no_license
MrZhengWeiCN/leetcode
https://github.com/MrZhengWeiCN/leetcode
fd7b7f5960dd469a60e7dada3037478a85e0bc96
dde928e02f2413bfcc44dd1e754b068abd399c31
refs/heads/master
2021-09-07T08:46:18.644000
2018-02-20T14:55:58
2018-02-20T14:55:58
112,304,494
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tree; /** * 恢復搜索树出错的两个节点 Title: Description: Company: * * @author 郑伟 * @date 2018年1月21日下午7:55:15 */ public class RecoverTree { TreeNode one = null; TreeNode two = null; TreeNode preNode = new TreeNode(Integer.MIN_VALUE); public void recoverTree(TreeNode root) { doInorder(root); int temp = one.val; one.val = two.val; two.val = temp; } private void doInorder(TreeNode root) { if(root==null) return; doInorder(root.left); if(one==null&&preNode.val>root.val){ one = preNode; } if(one!=null&&preNode.val>root.val){ two = root; } preNode = root; doInorder(root.right); } }
GB18030
Java
665
java
RecoverTree.java
Java
[ { "context": "的两个节点 Title: Description: Company:\n * \n * @author 郑伟\n * @date 2018年1月21日下午7:55:15\n */\npublic class Rec", "end": 81, "score": 0.9986000061035156, "start": 79, "tag": "NAME", "value": "郑伟" } ]
null
[]
package tree; /** * 恢復搜索树出错的两个节点 Title: Description: Company: * * @author 郑伟 * @date 2018年1月21日下午7:55:15 */ public class RecoverTree { TreeNode one = null; TreeNode two = null; TreeNode preNode = new TreeNode(Integer.MIN_VALUE); public void recoverTree(TreeNode root) { doInorder(root); int temp = one.val; one.val = two.val; two.val = temp; } private void doInorder(TreeNode root) { if(root==null) return; doInorder(root.left); if(one==null&&preNode.val>root.val){ one = preNode; } if(one!=null&&preNode.val>root.val){ two = root; } preNode = root; doInorder(root.right); } }
665
0.657097
0.637959
34
17.441177
14.23581
52
false
false
0
0
0
0
0
0
1.617647
false
false
15
4fef485d8da99095c1fdf3ef70cb2d63cd2209a8
37,915,971,301,412
1b11c103d2cbb8aaa6e3f731bc505de5d8a95b23
/src/main/java/br/com/unitri/redes2/networksimulator/EthernetInterface.java
f29f3217d8f4104604b4b179b381caa2b90ee17d
[]
no_license
emiliodias/redes2
https://github.com/emiliodias/redes2
ef23a9063708121bc2dc53bf5374d028143ac37d
70f3b31fd0999374c6053430ec02baa3b9053547
refs/heads/master
2020-12-26T21:44:05.935000
2016-09-24T00:18:14
2016-09-24T00:18:14
68,411,781
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.unitri.redes2.networksimulator; import br.com.unitri.redes2.networksimulator.arp.ARPTable; public class EthernetInterface extends NetworkInterface { private ARPTable arpTable = new ARPTable(); private Hub hub; public void setHub(Hub hub) { this.hub = hub; } public void sendMessage(int port, Object message) { IPDatagram datagram = (IPDatagram) message; EthernetFrame frame = new EthernetFrame(); //Configurando o endereço MAC de origem frame.setSourceMacAddress(getMacAddress()); String macAddress = arpTable.getMacAddress(datagram.getDestinationAddress()); if(macAddress == null) { /* * TODO: NECESSÁRIO IMPLEMENTAR O PROTOCOLO ARP PARA QUE SEJA POSSÍVEL * DESCOBRIR O ENDEREÇO MAC DE DESTINO */ } else { /* * TODO: IMPLEMENTAR MECANISMO DE TIMEOUT DO ARP */ frame.setDestinationMacAddress(macAddress); } frame.setPayLoad(message); hub.recieve(port, frame); } }
UTF-8
Java
981
java
EthernetInterface.java
Java
[]
null
[]
package br.com.unitri.redes2.networksimulator; import br.com.unitri.redes2.networksimulator.arp.ARPTable; public class EthernetInterface extends NetworkInterface { private ARPTable arpTable = new ARPTable(); private Hub hub; public void setHub(Hub hub) { this.hub = hub; } public void sendMessage(int port, Object message) { IPDatagram datagram = (IPDatagram) message; EthernetFrame frame = new EthernetFrame(); //Configurando o endereço MAC de origem frame.setSourceMacAddress(getMacAddress()); String macAddress = arpTable.getMacAddress(datagram.getDestinationAddress()); if(macAddress == null) { /* * TODO: NECESSÁRIO IMPLEMENTAR O PROTOCOLO ARP PARA QUE SEJA POSSÍVEL * DESCOBRIR O ENDEREÇO MAC DE DESTINO */ } else { /* * TODO: IMPLEMENTAR MECANISMO DE TIMEOUT DO ARP */ frame.setDestinationMacAddress(macAddress); } frame.setPayLoad(message); hub.recieve(port, frame); } }
981
0.706244
0.704197
45
20.711111
23.000118
79
false
false
0
0
0
0
0
0
2
false
false
15
2bb4f949dcb0b48f692c0432ec33645473cd96e3
37,245,956,413,319
462b3dbfada95378e1c88deb7f8dc5ae4b528880
/Ex3/app/src/main/java/Service/SearchCriteria.java
8a2b8cf3d64f75629c8b8f5a881a173ff11cf555
[]
no_license
tpthanhan/Unnamed-Group
https://github.com/tpthanhan/Unnamed-Group
45f270da233fd5268748d7bddbcddc648f28e4cb
48c39739ef274d66e10bae91fa3ec6645d7cb548
refs/heads/master
2021-01-25T13:11:30.821000
2018-05-23T15:53:10
2018-05-23T15:53:10
123,538,444
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Service; public class SearchCriteria { private String name; private String location; private boolean fullTime; public SearchCriteria(String name, String location, boolean fullTime) { super(); this.name = name; this.location = location.replace(" ", "+"); this.fullTime = fullTime; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the location */ public String getLocation() { return location; } /** * @param location * the location to set */ public void setLocation(String location) { this.location = location; } /** * @return the fullTime */ public boolean isFullTime() { return fullTime; } /** * @param fullTime * the fullTime to set */ public void setFullTime(boolean fullTime) { this.fullTime = fullTime; } }
UTF-8
Java
1,023
java
SearchCriteria.java
Java
[]
null
[]
package Service; public class SearchCriteria { private String name; private String location; private boolean fullTime; public SearchCriteria(String name, String location, boolean fullTime) { super(); this.name = name; this.location = location.replace(" ", "+"); this.fullTime = fullTime; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the location */ public String getLocation() { return location; } /** * @param location * the location to set */ public void setLocation(String location) { this.location = location; } /** * @return the fullTime */ public boolean isFullTime() { return fullTime; } /** * @param fullTime * the fullTime to set */ public void setFullTime(boolean fullTime) { this.fullTime = fullTime; } }
1,023
0.587488
0.587488
60
15.05
15.126605
72
false
false
0
0
0
0
0
0
1.25
false
false
15
9ff4c44bee4f6591f388a24b4fb38ac141344049
34,754,875,408,809
c349a8b764b77c93e7074666106edc92307a560c
/src/minus_on_Fp/main.java
4598137b01110432644037c0dd80866a182a3a14
[]
no_license
luumanhquan1/ThuatToanATTTJava
https://github.com/luumanhquan1/ThuatToanATTTJava
eb7467f186c922d475856adc231e3ecbaac7990d
c8e192681bbc64981a0b3d699fd769f86231cf6d
refs/heads/master
2023-06-13T23:03:40.714000
2021-08-03T00:39:17
2021-08-03T00:39:17
371,281,954
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 minus_on_Fp; /** * * @author ASUS TUF */ public class main { public static void main(String[] args) { MinusOnFp minusOnFp=new MinusOnFp(); minusOnFp.inPut(); minusOnFp.minus(); } }
UTF-8
Java
410
java
main.java
Java
[ { "context": "ditor.\n */\npackage minus_on_Fp;\n\n/**\n *\n * @author ASUS TUF\n */\npublic class main {\n public static void ma", "end": 233, "score": 0.9998553991317749, "start": 225, "tag": "NAME", "value": "ASUS TUF" } ]
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 minus_on_Fp; /** * * @author <NAME> */ public class main { public static void main(String[] args) { MinusOnFp minusOnFp=new MinusOnFp(); minusOnFp.inPut(); minusOnFp.minus(); } }
408
0.656098
0.656098
18
21.777779
22.212498
79
false
false
0
0
0
0
0
0
0.388889
false
false
15
2996896ae50e409717313a7d1eadcc4e62c5fe19
34,754,875,406,600
25771557f46cc24c263e2bbd69500b3e4027cfcb
/test/gameServer/UserInfoTest.java
7ca857f275b144566f6351fa1f97b9347cd28073
[]
no_license
sumitkaul/Game-Maker-Application-Version-2
https://github.com/sumitkaul/Game-Maker-Application-Version-2
69944796dea8c19332a38bb0b5c04d5d29cfb279
e11c82bb3f8c8ca812163242ee12a600351fadc7
refs/heads/master
2016-09-16T02:12:07.156000
2014-04-11T21:08:16
2014-04-11T21:08:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gameServer; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.Mockito; public class UserInfoTest { UserInfo userInfo = Mockito.mock(UserInfo.class); @Test public void testUserId() throws Exception{ Mockito.when(userInfo.getUserid()).thenReturn(10); assertEquals(10, userInfo.getUserid()); } @Test public void testGameId() throws Exception{ Mockito.when(userInfo.getUsername()).thenReturn("username"); assertEquals("username", userInfo.getUsername()); } @Test public void testPassword() throws Exception{ Mockito.when(userInfo.getPassword()).thenReturn("password"); assertEquals("password", userInfo.getPassword()); } }
UTF-8
Java
685
java
UserInfoTest.java
Java
[ { "context": "\tMockito.when(userInfo.getUsername()).thenReturn(\"username\");\n\t\tassertEquals(\"username\", userInfo.getUsernam", "end": 449, "score": 0.9989693760871887, "start": 441, "tag": "USERNAME", "value": "username" }, { "context": "ername()).thenReturn(\"username\");\n\t\...
null
[]
package gameServer; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.Mockito; public class UserInfoTest { UserInfo userInfo = Mockito.mock(UserInfo.class); @Test public void testUserId() throws Exception{ Mockito.when(userInfo.getUserid()).thenReturn(10); assertEquals(10, userInfo.getUserid()); } @Test public void testGameId() throws Exception{ Mockito.when(userInfo.getUsername()).thenReturn("username"); assertEquals("username", userInfo.getUsername()); } @Test public void testPassword() throws Exception{ Mockito.when(userInfo.getPassword()).thenReturn("<PASSWORD>"); assertEquals("<PASSWORD>", userInfo.getPassword()); } }
689
0.745985
0.740146
29
22.620689
22.11009
62
false
false
0
0
0
0
0
0
1.344828
false
false
15
4386ba01d6c2e1a13c0d9e2c8dbea1d6447583c2
28,595,892,318,583
65e81a6007d28a628299d7bd59a3540f30ae893d
/src/leetcode/SortColors.java
f6740a712f13c1b4498f1a47bb79984cbf089215
[]
no_license
wiyee/coder
https://github.com/wiyee/coder
cd97d5b9b3869540fcb9e019b00685674675b043
5e196f80c6eae4551594706b50eb457a01cef646
refs/heads/master
2020-03-17T17:06:17.836000
2018-09-27T10:56:04
2018-09-27T10:56:04
133,775,197
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package leetcode; import java.util.Arrays; /** * Created by wiyee on 2018/5/9. * Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. * <p> * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. * <p> * Note: * You are not suppose to use the library's sort function for this problem. * <p> * click to show follow up. * <p> * Follow up: * A rather straight forward solution is a two-pass algorithm using counting sort. * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. * <p> * Could you come up with an one-pass algorithm using only constant space? */ public class SortColors { public static void main(String[] args) { int[] A = new int[]{1, 2, 0, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2}; SortColors sortColors = new SortColors(); sortColors.sortColors(A); for (int i : A) { System.out.println(i); } } public void sortColors(int[] A) { int indexZero = 0; int indexTwo = A.length - 1; int j = 0; while (j < indexTwo + 1) { if (A[j] == 0) { int tmp = A[indexZero]; A[indexZero] = A[j]; A[j] = tmp; j++; indexZero++; } else if (A[j] == 2) { int tmp = A[indexTwo]; A[indexTwo] = A[j]; A[j] = tmp; indexTwo--; } else { j++; } } } // public void sortColors(int[] A) { // int[] count = new int[]{0,0,0}; // for (int i = 0; i < A.length; i ++){ // if (A[i] == 0) // count[0] ++; // if (A[i] == 1) // count[1] ++; // if (A[i] == 2) // count[2] ++; // } // for (int i = 0; i < count[0]; i ++){ // A[i] = 0; // } // for (int i = count[0]; i < count[0] + count[1]; i ++){ // A[i] = 1; // } // for (int i = count[1] + count[0]; i < count[0] + count[1] + count[2]; i ++){ // A[i] = 2; // } // } }
UTF-8
Java
2,353
java
SortColors.java
Java
[ { "context": "code;\n\nimport java.util.Arrays;\n\n/**\n * Created by wiyee on 2018/5/9.\n * Given an array with n objects col", "end": 68, "score": 0.9995693564414978, "start": 63, "tag": "USERNAME", "value": "wiyee" } ]
null
[]
package leetcode; import java.util.Arrays; /** * Created by wiyee on 2018/5/9. * Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. * <p> * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. * <p> * Note: * You are not suppose to use the library's sort function for this problem. * <p> * click to show follow up. * <p> * Follow up: * A rather straight forward solution is a two-pass algorithm using counting sort. * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. * <p> * Could you come up with an one-pass algorithm using only constant space? */ public class SortColors { public static void main(String[] args) { int[] A = new int[]{1, 2, 0, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2}; SortColors sortColors = new SortColors(); sortColors.sortColors(A); for (int i : A) { System.out.println(i); } } public void sortColors(int[] A) { int indexZero = 0; int indexTwo = A.length - 1; int j = 0; while (j < indexTwo + 1) { if (A[j] == 0) { int tmp = A[indexZero]; A[indexZero] = A[j]; A[j] = tmp; j++; indexZero++; } else if (A[j] == 2) { int tmp = A[indexTwo]; A[indexTwo] = A[j]; A[j] = tmp; indexTwo--; } else { j++; } } } // public void sortColors(int[] A) { // int[] count = new int[]{0,0,0}; // for (int i = 0; i < A.length; i ++){ // if (A[i] == 0) // count[0] ++; // if (A[i] == 1) // count[1] ++; // if (A[i] == 2) // count[2] ++; // } // for (int i = 0; i < count[0]; i ++){ // A[i] = 0; // } // for (int i = count[0]; i < count[0] + count[1]; i ++){ // A[i] = 1; // } // for (int i = count[1] + count[0]; i < count[0] + count[1] + count[2]; i ++){ // A[i] = 2; // } // } }
2,353
0.467063
0.441139
74
30.797297
30.027906
168
false
false
0
0
0
0
0
0
0.891892
false
false
15
2db657ab5ce19e74a741e6739c4c70a6aeba4d30
5,394,478,924,647
035723209cc5fd50acf5ff1c841966a1dac8ce1b
/qcloudapi-base/src/main/java/org/wtb/qcloudapi/base/QcloudApiConf.java
9f8f59fe3745f66c5494cd86284df307cd6471de
[ "MIT" ]
permissive
chinafzy/qcloudapi
https://github.com/chinafzy/qcloudapi
ab81b52a90fa05b0e8400045bc9281d9aba0de13
905afb21d62a4ba373ebc5c77e1885321fedddda
refs/heads/master
2021-01-20T22:29:27.264000
2019-04-02T09:41:15
2019-04-02T09:41:15
64,127,786
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.wtb.qcloudapi.base; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Random; import org.wtb.qcloudapi.base.util.Args; import org.wtb.qcloudapi.base.util.ChainMap; import org.wtb.qcloudapi.base.util.QcloudSigners; /** * (ThreadSafe)QQ云平台客户端API配置信息 * * @author 19781971@qq.com */ public class QcloudApiConf { private static interface Action { String asGet(); String[] asPost(); } // global inputs. private String host, path; private String secretId, secretKey; private String region; // internal temps. private Random rnd = new Random(); private static final int rnd_max = Integer.MAX_VALUE; public QcloudApiConf(String host, String path, String secretId, String secretKey, String region) { this.host = Args.notNullEmpty(host, "host"); this.path = Args.notNullEmpty(path, "path"); this.secretId = Args.notNullEmpty(secretId, "secretId"); this.secretKey = Args.notNullEmpty(secretKey, "secretKey"); this.region = Args.notNullEmpty(region, "region"); } public String reqGet(String action, Map<String, Object> pars) { Args.notNullEmpty(action, "action"); Args.notNull(pars, "pars"); return action(action, pars).asGet(); } public String[] reqPost(String action, Map<String, Object> pars) { Args.notNullEmpty(action, "action"); Args.notNull(pars, "pars"); return action(action, pars).asPost(); } private Action action(final String action, final Map<String, Object> pars) { return new Action() { public String asGet() { String entity = calEntity("GET"); return "https://" + host + path + "?" + entity; } public String[] asPost() { String url = "https://" + host + path; String entity = calEntity("POST"); return new String[] {url, entity}; } private String calEntity(String method) { ChainMap<String, Object> allPars = new ChainMap<String, Object>(pars) // .add("Action", action) // .add("Timestamp", System.currentTimeMillis() / 1000) // .add("Nonce", rnd.nextInt(rnd_max) + 1) // .add("SecretId", secretId) // .add("Region", region) // ; String signature = QcloudSigners.sign(host, path, method, secretKey, allPars); allPars.put("Signature", signature); return join(allPars); } }; } private static String enc(String s) { try { return URLEncoder.encode(s, "utf8"); } catch (UnsupportedEncodingException e) { // fail on such exception. throw new RuntimeException(e); } } private static String join(Map<String, Object> pars) { StringBuffer ret = new StringBuffer(1024); boolean first = true; for (Map.Entry<String, Object> ent : pars.entrySet()) { if (first) first = false; else ret.append("&"); ret.append(enc(ent.getKey())).append("=").append(enc("" + ent.getValue())); } return ret.toString(); } }
UTF-8
Java
3,446
java
QcloudApiConf.java
Java
[ { "context": "**\n * (ThreadSafe)QQ云平台客户端API配置信息 \n * \n * @author 19781971@qq.com\n */\npublic class QcloudApiConf {\n\n private sta", "end": 357, "score": 0.9998970031738281, "start": 342, "tag": "EMAIL", "value": "19781971@qq.com" } ]
null
[]
package org.wtb.qcloudapi.base; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Random; import org.wtb.qcloudapi.base.util.Args; import org.wtb.qcloudapi.base.util.ChainMap; import org.wtb.qcloudapi.base.util.QcloudSigners; /** * (ThreadSafe)QQ云平台客户端API配置信息 * * @author <EMAIL> */ public class QcloudApiConf { private static interface Action { String asGet(); String[] asPost(); } // global inputs. private String host, path; private String secretId, secretKey; private String region; // internal temps. private Random rnd = new Random(); private static final int rnd_max = Integer.MAX_VALUE; public QcloudApiConf(String host, String path, String secretId, String secretKey, String region) { this.host = Args.notNullEmpty(host, "host"); this.path = Args.notNullEmpty(path, "path"); this.secretId = Args.notNullEmpty(secretId, "secretId"); this.secretKey = Args.notNullEmpty(secretKey, "secretKey"); this.region = Args.notNullEmpty(region, "region"); } public String reqGet(String action, Map<String, Object> pars) { Args.notNullEmpty(action, "action"); Args.notNull(pars, "pars"); return action(action, pars).asGet(); } public String[] reqPost(String action, Map<String, Object> pars) { Args.notNullEmpty(action, "action"); Args.notNull(pars, "pars"); return action(action, pars).asPost(); } private Action action(final String action, final Map<String, Object> pars) { return new Action() { public String asGet() { String entity = calEntity("GET"); return "https://" + host + path + "?" + entity; } public String[] asPost() { String url = "https://" + host + path; String entity = calEntity("POST"); return new String[] {url, entity}; } private String calEntity(String method) { ChainMap<String, Object> allPars = new ChainMap<String, Object>(pars) // .add("Action", action) // .add("Timestamp", System.currentTimeMillis() / 1000) // .add("Nonce", rnd.nextInt(rnd_max) + 1) // .add("SecretId", secretId) // .add("Region", region) // ; String signature = QcloudSigners.sign(host, path, method, secretKey, allPars); allPars.put("Signature", signature); return join(allPars); } }; } private static String enc(String s) { try { return URLEncoder.encode(s, "utf8"); } catch (UnsupportedEncodingException e) { // fail on such exception. throw new RuntimeException(e); } } private static String join(Map<String, Object> pars) { StringBuffer ret = new StringBuffer(1024); boolean first = true; for (Map.Entry<String, Object> ent : pars.entrySet()) { if (first) first = false; else ret.append("&"); ret.append(enc(ent.getKey())).append("=").append(enc("" + ent.getValue())); } return ret.toString(); } }
3,438
0.565966
0.560712
117
28.282051
25.642796
102
false
false
0
0
0
0
0
0
0.709402
false
false
15