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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82f9dd5541a9b90bdb7f5380f99c4165582c12d1 | 28,329,604,287,963 | bb7b57ca16993166a88aa93be6894956f63d9f33 | /microservice-simple-consumer-movie/src/main/java/com/chengchengkeji/microservicetest/controller/MovieController.java | dc019c20050116ffbc1ab29c2108ef7e7123dc93 | []
| no_license | helloCodeke/microservice-test | https://github.com/helloCodeke/microservice-test | e08450775677e9cbf41ba7fc49d9504ed92a9e3e | ebe6e0e41764abfeb7b10f3083f31d71609100ac | refs/heads/master | 2020-03-13T20:38:58.992000 | 2018-05-07T09:57:31 | 2018-05-07T09:57:31 | 131,279,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chengchengkeji.microservicetest.controller;
import com.chengchengkeji.microservicetest.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @company: 甘肃诚诚网络技术有限公司
* @author: codeke
* @date: 2018-04-27 9:19
* @description
*/
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject(userServiceUrl + "user/" + id, User.class);
}
}
| UTF-8 | Java | 944 | java | MovieController.java | Java | [
{
"context": "mplate;\n\n/**\n * @company: 甘肃诚诚网络技术有限公司\n * @author: codeke\n * @date: 2018-04-27 9:19\n * @description\n */\n@Re",
"end": 519,
"score": 0.9996452927589417,
"start": 513,
"tag": "USERNAME",
"value": "codeke"
}
]
| null | []
| package com.chengchengkeji.microservicetest.controller;
import com.chengchengkeji.microservicetest.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @company: 甘肃诚诚网络技术有限公司
* @author: codeke
* @date: 2018-04-27 9:19
* @description
*/
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject(userServiceUrl + "user/" + id, User.class);
}
}
| 944 | 0.772826 | 0.76087 | 30 | 29.666666 | 24.823824 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 0 |
c2d233904d5b17ceeb2cb482f5a0407acba601d7 | 28,561,532,570,635 | 64d299ef26e2b18b2faab62ebadce8b63158b1ba | /src/algorithm/studyGroup/study0/달력_실패.java | 646de321208f021ddc97f11f350024d5398ba9b3 | []
| no_license | NaKyouTae/algorithm | https://github.com/NaKyouTae/algorithm | 7cb530ce2161ac6be5ae4fd4c31fd88e422932c2 | eedb6a012782e58f504d79498d2b39ce140830e5 | refs/heads/master | 2023-08-29T16:15:02.066000 | 2021-11-01T02:21:56 | 2021-11-01T02:21:56 | 367,398,692 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algorithm.studyGroup.study0;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
//7
//2 4
//4 5
//5 6
//5 7
//7 9
//11 12
//12 12
//https://www.acmicpc.net/problem/20207
public class 달력_실패 {
public static class Node {
int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int sum = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
List<Node> rq = new ArrayList<>();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
min = Math.min(min, Math.min(x, y));
max = Math.max(max, Math.max(x, y));
rq.add(new Node(x, y));
}
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i <= max + 1; i++) list.add(new ArrayList<>());
for (int i = 0; i < rq.size(); i++) {
list.get(rq.get(i).x).add(rq.get(i).y);
}
Map<Integer, Integer> map = new HashMap<>();
int idx = min, x = 0, y = 0;
while (true) {
if (list.size() <= idx + 2) break;
if (list.get(idx).size() == 0) {
map.put(idx, y);
x = 0;
y = 0;
idx++;
} else {
int m = Integer.MIN_VALUE;
for (int i = 0; i < list.get(idx).size(); i++) {
m = Math.max(m, list.get(idx).get(i));
}
idx = m;
}
y = Math.max(y, list.get(idx).size());
}
map.entrySet().forEach(item -> {
sum += item.getKey() * item.getValue();
});
System.out.println(sum);
}
}
| UTF-8 | Java | 2,243 | java | 달력_실패.java | Java | []
| null | []
| package algorithm.studyGroup.study0;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
//7
//2 4
//4 5
//5 6
//5 7
//7 9
//11 12
//12 12
//https://www.acmicpc.net/problem/20207
public class 달력_실패 {
public static class Node {
int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int sum = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
List<Node> rq = new ArrayList<>();
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
min = Math.min(min, Math.min(x, y));
max = Math.max(max, Math.max(x, y));
rq.add(new Node(x, y));
}
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i <= max + 1; i++) list.add(new ArrayList<>());
for (int i = 0; i < rq.size(); i++) {
list.get(rq.get(i).x).add(rq.get(i).y);
}
Map<Integer, Integer> map = new HashMap<>();
int idx = min, x = 0, y = 0;
while (true) {
if (list.size() <= idx + 2) break;
if (list.get(idx).size() == 0) {
map.put(idx, y);
x = 0;
y = 0;
idx++;
} else {
int m = Integer.MIN_VALUE;
for (int i = 0; i < list.get(idx).size(); i++) {
m = Math.max(m, list.get(idx).get(i));
}
idx = m;
}
y = Math.max(y, list.get(idx).size());
}
map.entrySet().forEach(item -> {
sum += item.getKey() * item.getValue();
});
System.out.println(sum);
}
}
| 2,243 | 0.491275 | 0.47472 | 89 | 24.11236 | 21.047533 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707865 | false | false | 0 |
b72eec039e683b2ce189868609c4f8b2a241d0fa | 18,399,639,929,096 | 174a20d706ec5b513e6c7fbfa5a95ec45b6da816 | /src/ss/pku/re/rule/util/domain/Scene.java | ea9c6ced95a6cd6774f0f1aa9b17d6dc2c6d3da1 | []
| no_license | qhwang0427/RuleEngine | https://github.com/qhwang0427/RuleEngine | 6e848c78fdf9d439d50e67c3dfd4e9c015dedcc9 | 2de4a92f9fbf20fac54b9d060d6025104344f312 | refs/heads/master | 2016-09-05T16:42:28.413000 | 2013-03-26T02:56:11 | 2013-03-26T02:56:11 | 5,850,168 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ss.pku.re.rule.util.domain;
import java.util.List;
/**
* 这个表示一个场景,后续补充
* @author lqs
*
*/
public class Scene {
private String sceneId;
private List<Field> fields;
private List<Rule> rules;
public String getSceneId() {
return sceneId;
}
public void setSceneId(String sceneId) {
this.sceneId = sceneId;
}
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
| UTF-8 | Java | 601 | java | Scene.java | Java | [
{
"context": "t java.util.List;\n\n/**\n * 这个表示一个场景,后续补充\n * @author lqs\n *\n */\npublic class Scene {\n\tprivate String scene",
"end": 96,
"score": 0.999663233757019,
"start": 93,
"tag": "USERNAME",
"value": "lqs"
}
]
| null | []
| package ss.pku.re.rule.util.domain;
import java.util.List;
/**
* 这个表示一个场景,后续补充
* @author lqs
*
*/
public class Scene {
private String sceneId;
private List<Field> fields;
private List<Rule> rules;
public String getSceneId() {
return sceneId;
}
public void setSceneId(String sceneId) {
this.sceneId = sceneId;
}
public List<Field> getFields() {
return fields;
}
public void setFields(List<Field> fields) {
this.fields = fields;
}
public List<Rule> getRules() {
return rules;
}
public void setRules(List<Rule> rules) {
this.rules = rules;
}
}
| 601 | 0.686957 | 0.686957 | 32 | 16.9375 | 13.713446 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.1875 | false | false | 0 |
87fc2e035cc6469841f639abdbfd0040a07690cb | 11,098,195,496,604 | 947fc9eef832e937f09f04f1abd82819cd4f97d3 | /src/apk/com/touchin/vtb/api/BankConnectStatusesBody$$JsonObjectMapper.java | 8eb27b74bd7eda55c6a3b02e636c91e93c8d8539 | []
| no_license | thistehneisen/cifra | https://github.com/thistehneisen/cifra | 04f4ac1b230289f8262a0b9cf7448a1172d8f979 | d46c6f4764c9d4f64e45c56fa42fddee9b44ff5a | refs/heads/master | 2020-09-22T09:35:57.739000 | 2019-12-01T19:39:59 | 2019-12-01T19:39:59 | 225,136,583 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.touchin.vtb.api;
import com.bluelinelabs.logansquare.JsonMapper;
import com.bluelinelabs.logansquare.LoganSquare;
import com.fasterxml.jackson.core.c;
import com.fasterxml.jackson.core.e;
import com.fasterxml.jackson.core.g;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class BankConnectStatusesBody$$JsonObjectMapper extends JsonMapper<BankConnectStatusesBody> {
private static final JsonMapper<SessionIdBody> parentObjectMapper = LoganSquare.mapperFor(SessionIdBody.class);
public BankConnectStatusesBody parse(e eVar) throws IOException {
BankConnectStatusesBody bankConnectStatusesBody = new BankConnectStatusesBody();
if (eVar.d() == null) {
eVar.F();
}
if (eVar.d() != g.START_OBJECT) {
eVar.G();
return null;
}
while (eVar.F() != g.END_OBJECT) {
String c2 = eVar.c();
eVar.F();
parseField(bankConnectStatusesBody, c2, eVar);
eVar.G();
}
return bankConnectStatusesBody;
}
public void parseField(BankConnectStatusesBody bankConnectStatusesBody, String str, e eVar) throws IOException {
if (!"bankIdsList".equals(str)) {
parentObjectMapper.parseField(bankConnectStatusesBody, str, eVar);
} else if (eVar.d() == g.START_ARRAY) {
ArrayList arrayList = new ArrayList();
while (eVar.F() != g.END_ARRAY) {
arrayList.add(eVar.c(null));
}
bankConnectStatusesBody.a(arrayList);
} else {
bankConnectStatusesBody.a(null);
}
}
public void serialize(BankConnectStatusesBody bankConnectStatusesBody, c cVar, boolean z) throws IOException {
if (z) {
cVar.f();
}
List<String> c2 = bankConnectStatusesBody.c();
if (c2 != null) {
cVar.c("bankIdsList");
cVar.e();
for (String str : c2) {
if (str != null) {
cVar.f(str);
}
}
cVar.b();
}
parentObjectMapper.serialize(bankConnectStatusesBody, cVar, false);
if (z) {
cVar.c();
}
}
}
| UTF-8 | Java | 2,275 | java | BankConnectStatusesBody$$JsonObjectMapper.java | Java | []
| null | []
| package com.touchin.vtb.api;
import com.bluelinelabs.logansquare.JsonMapper;
import com.bluelinelabs.logansquare.LoganSquare;
import com.fasterxml.jackson.core.c;
import com.fasterxml.jackson.core.e;
import com.fasterxml.jackson.core.g;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public final class BankConnectStatusesBody$$JsonObjectMapper extends JsonMapper<BankConnectStatusesBody> {
private static final JsonMapper<SessionIdBody> parentObjectMapper = LoganSquare.mapperFor(SessionIdBody.class);
public BankConnectStatusesBody parse(e eVar) throws IOException {
BankConnectStatusesBody bankConnectStatusesBody = new BankConnectStatusesBody();
if (eVar.d() == null) {
eVar.F();
}
if (eVar.d() != g.START_OBJECT) {
eVar.G();
return null;
}
while (eVar.F() != g.END_OBJECT) {
String c2 = eVar.c();
eVar.F();
parseField(bankConnectStatusesBody, c2, eVar);
eVar.G();
}
return bankConnectStatusesBody;
}
public void parseField(BankConnectStatusesBody bankConnectStatusesBody, String str, e eVar) throws IOException {
if (!"bankIdsList".equals(str)) {
parentObjectMapper.parseField(bankConnectStatusesBody, str, eVar);
} else if (eVar.d() == g.START_ARRAY) {
ArrayList arrayList = new ArrayList();
while (eVar.F() != g.END_ARRAY) {
arrayList.add(eVar.c(null));
}
bankConnectStatusesBody.a(arrayList);
} else {
bankConnectStatusesBody.a(null);
}
}
public void serialize(BankConnectStatusesBody bankConnectStatusesBody, c cVar, boolean z) throws IOException {
if (z) {
cVar.f();
}
List<String> c2 = bankConnectStatusesBody.c();
if (c2 != null) {
cVar.c("bankIdsList");
cVar.e();
for (String str : c2) {
if (str != null) {
cVar.f(str);
}
}
cVar.b();
}
parentObjectMapper.serialize(bankConnectStatusesBody, cVar, false);
if (z) {
cVar.c();
}
}
}
| 2,275 | 0.592527 | 0.59033 | 67 | 32.955223 | 28.072632 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.626866 | false | false | 0 |
6a652ed1dff015a11b2f0cb1c455d7ce49213d9c | 27,797,028,402,643 | e1832d4c4a736c095c17b3bd671c0dbdf96df8c4 | /src/main/java/org/jboss/bot/HTMLStreamWriter.java | 18dc0dce4010ac2aa58f009470a36899dd932ded | []
| no_license | zhfeng/jbossbot | https://github.com/zhfeng/jbossbot | cf873fe56fbc6f28368ea8a451a7cf7438cb1101 | 365d4a8e532fac52d87e1e0d45f7a077ee0f09f9 | refs/heads/master | 2020-12-25T00:50:04.337000 | 2013-04-11T17:13:33 | 2013-04-11T17:13:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.bot;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayDeque;
import java.util.Deque;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class HTMLStreamWriter implements XMLStreamWriter {
public HTMLStreamWriter(final Writer target) {
this.target = target;
}
final Writer target;
final Deque<Element> stack = new ArrayDeque<Element>();
enum State {
INITIAL,
START_ATTRIBUTES,
EMPTY_ATTRIBUTES,
}
private State state;
private void toInitial() throws XMLStreamException {
final State oldState = state;
if (oldState == State.INITIAL) {
return;
}
try {
target.write('>');
state = State.INITIAL;
} catch (IOException e) {
throw new XMLStreamException(e);
}
if (oldState == State.EMPTY_ATTRIBUTES) {
if (stack.getFirst().getEnd() == Presence.REQUIRED) {
writeEndElement();
} else {
stack.pop();
}
}
}
public void writeStartElement(final Element element) throws XMLStreamException {
toInitial();
try {
target.write('<');
target.write(element.name().toLowerCase());
state = State.START_ATTRIBUTES;
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeStartElement(final String localName) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final Element element) throws XMLStreamException {
toInitial();
try {
target.write('<');
target.write(element.name().toLowerCase());
state = State.EMPTY_ATTRIBUTES;
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final String localName) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEndElement() throws XMLStreamException {
toInitial();
final Element element = stack.pop();
if (element.getEnd() == Presence.REQUIRED) {
try {
target.write("</");
target.write(element.name().toLowerCase());
target.write('>');
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
}
public void writeEndDocument() throws XMLStreamException {
}
public void close() throws XMLStreamException {
try {
target.close();
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void flush() throws XMLStreamException {
try {
target.flush();
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeAttribute(final String localName, final String value) throws XMLStreamException {
if (state == State.INITIAL) {
throw new XMLStreamException("Invalid state");
}
try {
target.write(' ');
writeString(localName);
target.write("=\"");
writeString(value);
target.write('\"');
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
writeAttribute(localName, value);
}
public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
writeAttribute(localName, value);
}
public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
// no op
}
public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
// no op
}
public void writeComment(final String data) throws XMLStreamException {
// no op
}
public void writeProcessingInstruction(final String target) throws XMLStreamException {
// no op
}
public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
// no op
}
public void writeCData(final String data) throws XMLStreamException {
try {
writeString(data);
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeDTD(final String dtd) throws XMLStreamException {
}
public void writeEntityRef(final String name) throws XMLStreamException {
}
public void writeStartDocument() throws XMLStreamException {
}
public void writeStartDocument(final String version) throws XMLStreamException {
}
public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
}
public void writeCharacters(final String text) throws XMLStreamException {
try {
writeString(text);
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
try {
writeString(new String(text, start, len));
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public String getPrefix(final String uri) throws XMLStreamException {
return null;
}
public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
}
public void setDefaultNamespace(final String uri) throws XMLStreamException {
}
public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
}
public NamespaceContext getNamespaceContext() {
return null;
}
public Object getProperty(final String name) throws IllegalArgumentException {
return null;
}
private void writeString(final String s) throws IOException {
final Writer target = this.target;
final int len = s.length();
int ch;
for (int i = 0; i < len; i += Character.charCount(ch)) {
ch = s.codePointAt(i);
switch (ch) {
case 160:
target.write("&#nbsp;");
break;
case 161:
target.write("&#iexcl;");
break;
case 162:
target.write("&#cent;");
break;
case 163:
target.write("&#pound;");
break;
case 164:
target.write("&#curren;");
break;
case 165:
target.write("&#yen;");
break;
case 166:
target.write("&#brvbar;");
break;
case 167:
target.write("&#sect;");
break;
case 168:
target.write("&#uml;");
break;
case 169:
target.write("&#copy;");
break;
case 170:
target.write("&#ordf;");
break;
case 171:
target.write("&#laquo;");
break;
case 172:
target.write("&#not;");
break;
case 173:
target.write("&#shy;");
break;
case 174:
target.write("&#reg;");
break;
case 175:
target.write("&#macr;");
break;
case 176:
target.write("&#deg;");
break;
case 177:
target.write("&#plusmn;");
break;
case 178:
target.write("&#sup2;");
break;
case 179:
target.write("&#sup3;");
break;
case 180:
target.write("&#acute;");
break;
case 181:
target.write("&#micro;");
break;
case 182:
target.write("&#para;");
break;
case 183:
target.write("&#middot;");
break;
case 184:
target.write("&#cedil;");
break;
case 185:
target.write("&#sup1;");
break;
case 186:
target.write("&#ordm;");
break;
case 187:
target.write("&#raquo;");
break;
case 188:
target.write("&#frac14;");
break;
case 189:
target.write("&#frac12;");
break;
case 190:
target.write("&#frac34;");
break;
case 191:
target.write("&#iquest;");
break;
case 192:
target.write("&#Agrave;");
break;
case 193:
target.write("&#Aacute;");
break;
case 194:
target.write("&#Acirc;");
break;
case 195:
target.write("&#Atilde;");
break;
case 196:
target.write("&#Auml;");
break;
case 197:
target.write("&#Aring;");
break;
case 198:
target.write("&#AElig;");
break;
case 199:
target.write("&#Ccedil;");
break;
case 200:
target.write("&#Egrave;");
break;
case 201:
target.write("&#Eacute;");
break;
case 202:
target.write("&#Ecirc;");
break;
case 203:
target.write("&#Euml;");
break;
case 204:
target.write("&#Igrave;");
break;
case 205:
target.write("&#Iacute;");
break;
case 206:
target.write("&#Icirc;");
break;
case 207:
target.write("&#Iuml;");
break;
case 208:
target.write("&#ETH;");
break;
case 209:
target.write("&#Ntilde;");
break;
case 210:
target.write("&#Ograve;");
break;
case 211:
target.write("&#Oacute;");
break;
case 212:
target.write("&#Ocirc;");
break;
case 213:
target.write("&#Otilde;");
break;
case 214:
target.write("&#Ouml;");
break;
case 215:
target.write("&#times;");
break;
case 216:
target.write("&#Oslash;");
break;
case 217:
target.write("&#Ugrave;");
break;
case 218:
target.write("&#Uacute;");
break;
case 219:
target.write("&#Ucirc;");
break;
case 220:
target.write("&#Uuml;");
break;
case 221:
target.write("&#Yacute;");
break;
case 222:
target.write("&#THORN;");
break;
case 223:
target.write("&#szlig;");
break;
case 224:
target.write("&#agrave;");
break;
case 225:
target.write("&#aacute;");
break;
case 226:
target.write("&#acirc;");
break;
case 227:
target.write("&#atilde;");
break;
case 228:
target.write("&#auml;");
break;
case 229:
target.write("&#aring;");
break;
case 230:
target.write("&#aelig;");
break;
case 231:
target.write("&#ccedil;");
break;
case 232:
target.write("&#egrave;");
break;
case 233:
target.write("&#eacute;");
break;
case 234:
target.write("&#ecirc;");
break;
case 235:
target.write("&#euml;");
break;
case 236:
target.write("&#igrave;");
break;
case 237:
target.write("&#iacute;");
break;
case 238:
target.write("&#icirc;");
break;
case 239:
target.write("&#iuml;");
break;
case 240:
target.write("&#eth;");
break;
case 241:
target.write("&#ntilde;");
break;
case 242:
target.write("&#ograve;");
break;
case 243:
target.write("&#oacute;");
break;
case 244:
target.write("&#ocirc;");
break;
case 245:
target.write("&#otilde;");
break;
case 246:
target.write("&#ouml;");
break;
case 247:
target.write("&#divide;");
break;
case 248:
target.write("&#oslash;");
break;
case 249:
target.write("&#ugrave;");
break;
case 250:
target.write("&#uacute;");
break;
case 251:
target.write("&#ucirc;");
break;
case 252:
target.write("&#uuml;");
break;
case 253:
target.write("&#yacute;");
break;
case 254:
target.write("&#thorn;");
break;
case 255:
target.write("&#yuml;");
break;
case 402:
target.write("&#fnof;");
break;
case 913:
target.write("&#Alpha;");
break;
case 914:
target.write("&#Beta;");
break;
case 915:
target.write("&#Gamma;");
break;
case 916:
target.write("&#Delta;");
break;
case 917:
target.write("&#Epsilon;");
break;
case 918:
target.write("&#Zeta;");
break;
case 919:
target.write("&#Eta;");
break;
case 920:
target.write("&#Theta;");
break;
case 921:
target.write("&#Iota;");
break;
case 922:
target.write("&#Kappa;");
break;
case 923:
target.write("&#Lambda;");
break;
case 924:
target.write("&#Mu;");
break;
case 925:
target.write("&#Nu;");
break;
case 926:
target.write("&#Xi;");
break;
case 927:
target.write("&#Omicron;");
break;
case 928:
target.write("&#Pi;");
break;
case 929:
target.write("&#Rho;");
break;
case 931:
target.write("&#Sigma;");
break;
case 932:
target.write("&#Tau;");
break;
case 933:
target.write("&#Upsilon;");
break;
case 934:
target.write("&#Phi;");
break;
case 935:
target.write("&#Chi;");
break;
case 936:
target.write("&#Psi;");
break;
case 937:
target.write("&#Omega;");
break;
case 945:
target.write("&#alpha;");
break;
case 946:
target.write("&#beta;");
break;
case 947:
target.write("&#gamma;");
break;
case 948:
target.write("&#delta;");
break;
case 949:
target.write("&#epsilon;");
break;
case 950:
target.write("&#zeta;");
break;
case 951:
target.write("&#eta;");
break;
case 952:
target.write("&#theta;");
break;
case 953:
target.write("&#iota;");
break;
case 954:
target.write("&#kappa;");
break;
case 955:
target.write("&#lambda;");
break;
case 956:
target.write("&#mu;");
break;
case 957:
target.write("&#nu;");
break;
case 958:
target.write("&#xi;");
break;
case 959:
target.write("&#omicron;");
break;
case 960:
target.write("&#pi;");
break;
case 961:
target.write("&#rho;");
break;
case 962:
target.write("&#sigmaf;");
break;
case 963:
target.write("&#sigma;");
break;
case 964:
target.write("&#tau;");
break;
case 965:
target.write("&#upsilon;");
break;
case 966:
target.write("&#phi;");
break;
case 967:
target.write("&#chi;");
break;
case 968:
target.write("&#psi;");
break;
case 969:
target.write("&#omega;");
break;
case 977:
target.write("&#thetasym;");
break;
case 978:
target.write("&#upsih;");
break;
case 982:
target.write("&#piv;");
break;
case 8226:
target.write("&#bull;");
break;
case 8230:
target.write("&#hellip;");
break;
case 8242:
target.write("&#prime;");
break;
case 8243:
target.write("&#Prime;");
break;
case 8254:
target.write("&#oline;");
break;
case 8260:
target.write("&#frasl;");
break;
case 8472:
target.write("&#weierp;");
break;
case 8465:
target.write("&#image;");
break;
case 8476:
target.write("&#real;");
break;
case 8482:
target.write("&#trade;");
break;
case 8501:
target.write("&#alefsym;");
break;
case 8592:
target.write("&#larr;");
break;
case 8593:
target.write("&#uarr;");
break;
case 8594:
target.write("&#rarr;");
break;
case 8595:
target.write("&#darr;");
break;
case 8596:
target.write("&#harr;");
break;
case 8629:
target.write("&#crarr;");
break;
case 8656:
target.write("&#lArr;");
break;
case 8657:
target.write("&#uArr;");
break;
case 8658:
target.write("&#rArr;");
break;
case 8659:
target.write("&#dArr;");
break;
case 8660:
target.write("&#hArr;");
break;
case 8704:
target.write("&#forall;");
break;
case 8706:
target.write("&#part;");
break;
case 8707:
target.write("&#exist;");
break;
case 8709:
target.write("&#empty;");
break;
case 8711:
target.write("&#nabla;");
break;
case 8712:
target.write("&#isin;");
break;
case 8713:
target.write("&#notin;");
break;
case 8715:
target.write("&#ni;");
break;
case 8719:
target.write("&#prod;");
break;
case 8721:
target.write("&#sum;");
break;
case 8722:
target.write("&#minus;");
break;
case 8727:
target.write("&#lowast;");
break;
case 8730:
target.write("&#radic;");
break;
case 8733:
target.write("&#prop;");
break;
case 8734:
target.write("&#infin;");
break;
case 8736:
target.write("&#ang;");
break;
case 8743:
target.write("&#and;");
break;
case 8744:
target.write("&#or;");
break;
case 8745:
target.write("&#cap;");
break;
case 8746:
target.write("&#cup;");
break;
case 8747:
target.write("&#int;");
break;
case 8756:
target.write("&#there4;");
break;
case 8764:
target.write("&#sim;");
break;
case 8773:
target.write("&#cong;");
break;
case 8776:
target.write("&#asymp;");
break;
case 8800:
target.write("&#ne;");
break;
case 8801:
target.write("&#equiv;");
break;
case 8804:
target.write("&#le;");
break;
case 8805:
target.write("&#ge;");
break;
case 8834:
target.write("&#sub;");
break;
case 8835:
target.write("&#sup;");
break;
case 8836:
target.write("&#nsub;");
break;
case 8838:
target.write("&#sube;");
break;
case 8839:
target.write("&#supe;");
break;
case 8853:
target.write("&#oplus;");
break;
case 8855:
target.write("&#otimes;");
break;
case 8869:
target.write("&#perp;");
break;
case 8901:
target.write("&#sdot;");
break;
case 8968:
target.write("&#lceil;");
break;
case 8969:
target.write("&#rceil;");
break;
case 8970:
target.write("&#lfloor;");
break;
case 8971:
target.write("&#rfloor;");
break;
case 9001:
target.write("&#lang;");
break;
case 9002:
target.write("&#rang;");
break;
case 9674:
target.write("&#loz;");
break;
case 9824:
target.write("&#spades;");
break;
case 9827:
target.write("&#clubs;");
break;
case 9829:
target.write("&#hearts;");
break;
case 9830:
target.write("&#diams;");
break;
case 34:
target.write("&#quot;");
break;
case 38:
target.write("&#amp;");
break;
case 60:
target.write("&#lt;");
break;
case 62:
target.write("&#gt;");
break;
case 338:
target.write("&#OElig;");
break;
case 339:
target.write("&#oelig;");
break;
case 352:
target.write("&#Scaron;");
break;
case 353:
target.write("&#scaron;");
break;
case 376:
target.write("&#Yuml;");
break;
case 710:
target.write("&#circ;");
break;
case 732:
target.write("&#tilde;");
break;
case 8194:
target.write("&#ensp;");
break;
case 8195:
target.write("&#emsp;");
break;
case 8201:
target.write("&#thinsp;");
break;
case 8204:
target.write("&#zwnj;");
break;
case 8205:
target.write("&#zwj;");
break;
case 8206:
target.write("&#lrm;");
break;
case 8207:
target.write("&#rlm;");
break;
case 8211:
target.write("&#ndash;");
break;
case 8212:
target.write("&#mdash;");
break;
case 8216:
target.write("&#lsquo;");
break;
case 8217:
target.write("&#rsquo;");
break;
case 8218:
target.write("&#sbquo;");
break;
case 8220:
target.write("&#ldquo;");
break;
default: {
if (Character.isWhitespace(ch)) {
target.write(ch);
} else if (Character.isISOControl(ch)) {
target.write("&#");
target.write(Integer.toString(ch));
target.write(';');
} else {
target.write(ch);
}
}
}
}
}
public enum Presence {
REQUIRED,
OPTIONAL,
FORBIDDEN,
;
}
public enum Element {
A,
ABBR,
ACRONYM,
ADDRESS,
@Deprecated
APPLET,
AREA(true),
B,
BASE(true),
@Deprecated
BASEFONT(true),
BDO,
BIG,
BLOCKQUOTE,
BODY(Presence.OPTIONAL, Presence.OPTIONAL),
BR(true),
BUTTON,
CAPTION,
@Deprecated
CENTER,
CITE,
CODE,
COL(true),
COLGROUP(Presence.REQUIRED, Presence.OPTIONAL),
DD(Presence.REQUIRED, Presence.OPTIONAL),
DEL,
DFN,
DIR,
DIV,
DL,
DT(Presence.REQUIRED, Presence.OPTIONAL),
EM,
FIELDSET,
@Deprecated
FONT,
FORM,
FRAME(true),
FRAMESET,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD(Presence.OPTIONAL, Presence.OPTIONAL),
HR(true),
HTML(Presence.OPTIONAL, Presence.OPTIONAL),
I,
IFRAME,
IMG(true),
INPUT(true),
INS,
@Deprecated
ISINDEX(true),
KBD,
LABEL,
LEGEND,
LI(Presence.REQUIRED, Presence.OPTIONAL),
LINK(true),
MAP,
@Deprecated
MENU,
META(true),
NOFRAMES,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION(Presence.REQUIRED, Presence.OPTIONAL),
P(Presence.REQUIRED, Presence.OPTIONAL),
PARAM(true),
PRE,
Q,
@Deprecated
S,
SAMP,
SCRIPT,
SELECT,
SMALL,
SPAN,
@Deprecated
STRIKE,
STRONG,
STYLE,
SUB,
SUP,
TABLE,
TBODY(Presence.OPTIONAL, Presence.OPTIONAL),
TD(Presence.REQUIRED, Presence.OPTIONAL),
TEXTAREA,
TFOOT(Presence.REQUIRED, Presence.OPTIONAL),
TH(Presence.REQUIRED, Presence.OPTIONAL),
THEAD(Presence.REQUIRED, Presence.OPTIONAL),
TITLE,
TR(Presence.REQUIRED, Presence.OPTIONAL),
TT,
@Deprecated
U,
UL,
VAR,
;
private final boolean empty;
private final Presence start;
private final Presence end;
Element() {
this(false, Presence.REQUIRED, Presence.REQUIRED);
}
Element(final boolean empty) {
this(empty, Presence.REQUIRED, Presence.FORBIDDEN);
}
Element(final Presence start, final Presence end) {
this(false, start, end);
}
Element(boolean empty, Presence start, Presence end) {
this.empty = empty;
this.start = start;
this.end = end;
}
public boolean isEmpty() {
return empty;
}
public Presence getStart() {
return start;
}
public Presence getEnd() {
return end;
}
}
}
| UTF-8 | Java | 36,198 | java | HTMLStreamWriter.java | Java | [
{
"context": ".XMLStreamWriter;\n\n/**\n * @author <a href=\"mailto:david.lloyd@redhat.com\">David M. Lloyd</a>\n */\npublic final class HTMLSt",
"end": 1346,
"score": 0.9999222159385681,
"start": 1324,
"tag": "EMAIL",
"value": "david.lloyd@redhat.com"
},
{
"context": "* @author <a href=\"mailto:david.lloyd@redhat.com\">David M. Lloyd</a>\n */\npublic final class HTMLStreamWriter imple",
"end": 1362,
"score": 0.9998671412467957,
"start": 1348,
"tag": "NAME",
"value": "David M. Lloyd"
}
]
| null | []
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.bot;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayDeque;
import java.util.Deque;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public final class HTMLStreamWriter implements XMLStreamWriter {
public HTMLStreamWriter(final Writer target) {
this.target = target;
}
final Writer target;
final Deque<Element> stack = new ArrayDeque<Element>();
enum State {
INITIAL,
START_ATTRIBUTES,
EMPTY_ATTRIBUTES,
}
private State state;
private void toInitial() throws XMLStreamException {
final State oldState = state;
if (oldState == State.INITIAL) {
return;
}
try {
target.write('>');
state = State.INITIAL;
} catch (IOException e) {
throw new XMLStreamException(e);
}
if (oldState == State.EMPTY_ATTRIBUTES) {
if (stack.getFirst().getEnd() == Presence.REQUIRED) {
writeEndElement();
} else {
stack.pop();
}
}
}
public void writeStartElement(final Element element) throws XMLStreamException {
toInitial();
try {
target.write('<');
target.write(element.name().toLowerCase());
state = State.START_ATTRIBUTES;
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeStartElement(final String localName) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
writeStartElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final Element element) throws XMLStreamException {
toInitial();
try {
target.write('<');
target.write(element.name().toLowerCase());
state = State.EMPTY_ATTRIBUTES;
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEmptyElement(final String localName) throws XMLStreamException {
writeEmptyElement(Element.valueOf(localName.toUpperCase()));
}
public void writeEndElement() throws XMLStreamException {
toInitial();
final Element element = stack.pop();
if (element.getEnd() == Presence.REQUIRED) {
try {
target.write("</");
target.write(element.name().toLowerCase());
target.write('>');
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
}
public void writeEndDocument() throws XMLStreamException {
}
public void close() throws XMLStreamException {
try {
target.close();
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void flush() throws XMLStreamException {
try {
target.flush();
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeAttribute(final String localName, final String value) throws XMLStreamException {
if (state == State.INITIAL) {
throw new XMLStreamException("Invalid state");
}
try {
target.write(' ');
writeString(localName);
target.write("=\"");
writeString(value);
target.write('\"');
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
writeAttribute(localName, value);
}
public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
writeAttribute(localName, value);
}
public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
// no op
}
public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
// no op
}
public void writeComment(final String data) throws XMLStreamException {
// no op
}
public void writeProcessingInstruction(final String target) throws XMLStreamException {
// no op
}
public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
// no op
}
public void writeCData(final String data) throws XMLStreamException {
try {
writeString(data);
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeDTD(final String dtd) throws XMLStreamException {
}
public void writeEntityRef(final String name) throws XMLStreamException {
}
public void writeStartDocument() throws XMLStreamException {
}
public void writeStartDocument(final String version) throws XMLStreamException {
}
public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
}
public void writeCharacters(final String text) throws XMLStreamException {
try {
writeString(text);
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
try {
writeString(new String(text, start, len));
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
public String getPrefix(final String uri) throws XMLStreamException {
return null;
}
public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
}
public void setDefaultNamespace(final String uri) throws XMLStreamException {
}
public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
}
public NamespaceContext getNamespaceContext() {
return null;
}
public Object getProperty(final String name) throws IllegalArgumentException {
return null;
}
private void writeString(final String s) throws IOException {
final Writer target = this.target;
final int len = s.length();
int ch;
for (int i = 0; i < len; i += Character.charCount(ch)) {
ch = s.codePointAt(i);
switch (ch) {
case 160:
target.write("&#nbsp;");
break;
case 161:
target.write("&#iexcl;");
break;
case 162:
target.write("&#cent;");
break;
case 163:
target.write("&#pound;");
break;
case 164:
target.write("&#curren;");
break;
case 165:
target.write("&#yen;");
break;
case 166:
target.write("&#brvbar;");
break;
case 167:
target.write("&#sect;");
break;
case 168:
target.write("&#uml;");
break;
case 169:
target.write("&#copy;");
break;
case 170:
target.write("&#ordf;");
break;
case 171:
target.write("&#laquo;");
break;
case 172:
target.write("&#not;");
break;
case 173:
target.write("&#shy;");
break;
case 174:
target.write("&#reg;");
break;
case 175:
target.write("&#macr;");
break;
case 176:
target.write("&#deg;");
break;
case 177:
target.write("&#plusmn;");
break;
case 178:
target.write("&#sup2;");
break;
case 179:
target.write("&#sup3;");
break;
case 180:
target.write("&#acute;");
break;
case 181:
target.write("&#micro;");
break;
case 182:
target.write("&#para;");
break;
case 183:
target.write("&#middot;");
break;
case 184:
target.write("&#cedil;");
break;
case 185:
target.write("&#sup1;");
break;
case 186:
target.write("&#ordm;");
break;
case 187:
target.write("&#raquo;");
break;
case 188:
target.write("&#frac14;");
break;
case 189:
target.write("&#frac12;");
break;
case 190:
target.write("&#frac34;");
break;
case 191:
target.write("&#iquest;");
break;
case 192:
target.write("&#Agrave;");
break;
case 193:
target.write("&#Aacute;");
break;
case 194:
target.write("&#Acirc;");
break;
case 195:
target.write("&#Atilde;");
break;
case 196:
target.write("&#Auml;");
break;
case 197:
target.write("&#Aring;");
break;
case 198:
target.write("&#AElig;");
break;
case 199:
target.write("&#Ccedil;");
break;
case 200:
target.write("&#Egrave;");
break;
case 201:
target.write("&#Eacute;");
break;
case 202:
target.write("&#Ecirc;");
break;
case 203:
target.write("&#Euml;");
break;
case 204:
target.write("&#Igrave;");
break;
case 205:
target.write("&#Iacute;");
break;
case 206:
target.write("&#Icirc;");
break;
case 207:
target.write("&#Iuml;");
break;
case 208:
target.write("&#ETH;");
break;
case 209:
target.write("&#Ntilde;");
break;
case 210:
target.write("&#Ograve;");
break;
case 211:
target.write("&#Oacute;");
break;
case 212:
target.write("&#Ocirc;");
break;
case 213:
target.write("&#Otilde;");
break;
case 214:
target.write("&#Ouml;");
break;
case 215:
target.write("&#times;");
break;
case 216:
target.write("&#Oslash;");
break;
case 217:
target.write("&#Ugrave;");
break;
case 218:
target.write("&#Uacute;");
break;
case 219:
target.write("&#Ucirc;");
break;
case 220:
target.write("&#Uuml;");
break;
case 221:
target.write("&#Yacute;");
break;
case 222:
target.write("&#THORN;");
break;
case 223:
target.write("&#szlig;");
break;
case 224:
target.write("&#agrave;");
break;
case 225:
target.write("&#aacute;");
break;
case 226:
target.write("&#acirc;");
break;
case 227:
target.write("&#atilde;");
break;
case 228:
target.write("&#auml;");
break;
case 229:
target.write("&#aring;");
break;
case 230:
target.write("&#aelig;");
break;
case 231:
target.write("&#ccedil;");
break;
case 232:
target.write("&#egrave;");
break;
case 233:
target.write("&#eacute;");
break;
case 234:
target.write("&#ecirc;");
break;
case 235:
target.write("&#euml;");
break;
case 236:
target.write("&#igrave;");
break;
case 237:
target.write("&#iacute;");
break;
case 238:
target.write("&#icirc;");
break;
case 239:
target.write("&#iuml;");
break;
case 240:
target.write("&#eth;");
break;
case 241:
target.write("&#ntilde;");
break;
case 242:
target.write("&#ograve;");
break;
case 243:
target.write("&#oacute;");
break;
case 244:
target.write("&#ocirc;");
break;
case 245:
target.write("&#otilde;");
break;
case 246:
target.write("&#ouml;");
break;
case 247:
target.write("&#divide;");
break;
case 248:
target.write("&#oslash;");
break;
case 249:
target.write("&#ugrave;");
break;
case 250:
target.write("&#uacute;");
break;
case 251:
target.write("&#ucirc;");
break;
case 252:
target.write("&#uuml;");
break;
case 253:
target.write("&#yacute;");
break;
case 254:
target.write("&#thorn;");
break;
case 255:
target.write("&#yuml;");
break;
case 402:
target.write("&#fnof;");
break;
case 913:
target.write("&#Alpha;");
break;
case 914:
target.write("&#Beta;");
break;
case 915:
target.write("&#Gamma;");
break;
case 916:
target.write("&#Delta;");
break;
case 917:
target.write("&#Epsilon;");
break;
case 918:
target.write("&#Zeta;");
break;
case 919:
target.write("&#Eta;");
break;
case 920:
target.write("&#Theta;");
break;
case 921:
target.write("&#Iota;");
break;
case 922:
target.write("&#Kappa;");
break;
case 923:
target.write("&#Lambda;");
break;
case 924:
target.write("&#Mu;");
break;
case 925:
target.write("&#Nu;");
break;
case 926:
target.write("&#Xi;");
break;
case 927:
target.write("&#Omicron;");
break;
case 928:
target.write("&#Pi;");
break;
case 929:
target.write("&#Rho;");
break;
case 931:
target.write("&#Sigma;");
break;
case 932:
target.write("&#Tau;");
break;
case 933:
target.write("&#Upsilon;");
break;
case 934:
target.write("&#Phi;");
break;
case 935:
target.write("&#Chi;");
break;
case 936:
target.write("&#Psi;");
break;
case 937:
target.write("&#Omega;");
break;
case 945:
target.write("&#alpha;");
break;
case 946:
target.write("&#beta;");
break;
case 947:
target.write("&#gamma;");
break;
case 948:
target.write("&#delta;");
break;
case 949:
target.write("&#epsilon;");
break;
case 950:
target.write("&#zeta;");
break;
case 951:
target.write("&#eta;");
break;
case 952:
target.write("&#theta;");
break;
case 953:
target.write("&#iota;");
break;
case 954:
target.write("&#kappa;");
break;
case 955:
target.write("&#lambda;");
break;
case 956:
target.write("&#mu;");
break;
case 957:
target.write("&#nu;");
break;
case 958:
target.write("&#xi;");
break;
case 959:
target.write("&#omicron;");
break;
case 960:
target.write("&#pi;");
break;
case 961:
target.write("&#rho;");
break;
case 962:
target.write("&#sigmaf;");
break;
case 963:
target.write("&#sigma;");
break;
case 964:
target.write("&#tau;");
break;
case 965:
target.write("&#upsilon;");
break;
case 966:
target.write("&#phi;");
break;
case 967:
target.write("&#chi;");
break;
case 968:
target.write("&#psi;");
break;
case 969:
target.write("&#omega;");
break;
case 977:
target.write("&#thetasym;");
break;
case 978:
target.write("&#upsih;");
break;
case 982:
target.write("&#piv;");
break;
case 8226:
target.write("&#bull;");
break;
case 8230:
target.write("&#hellip;");
break;
case 8242:
target.write("&#prime;");
break;
case 8243:
target.write("&#Prime;");
break;
case 8254:
target.write("&#oline;");
break;
case 8260:
target.write("&#frasl;");
break;
case 8472:
target.write("&#weierp;");
break;
case 8465:
target.write("&#image;");
break;
case 8476:
target.write("&#real;");
break;
case 8482:
target.write("&#trade;");
break;
case 8501:
target.write("&#alefsym;");
break;
case 8592:
target.write("&#larr;");
break;
case 8593:
target.write("&#uarr;");
break;
case 8594:
target.write("&#rarr;");
break;
case 8595:
target.write("&#darr;");
break;
case 8596:
target.write("&#harr;");
break;
case 8629:
target.write("&#crarr;");
break;
case 8656:
target.write("&#lArr;");
break;
case 8657:
target.write("&#uArr;");
break;
case 8658:
target.write("&#rArr;");
break;
case 8659:
target.write("&#dArr;");
break;
case 8660:
target.write("&#hArr;");
break;
case 8704:
target.write("&#forall;");
break;
case 8706:
target.write("&#part;");
break;
case 8707:
target.write("&#exist;");
break;
case 8709:
target.write("&#empty;");
break;
case 8711:
target.write("&#nabla;");
break;
case 8712:
target.write("&#isin;");
break;
case 8713:
target.write("&#notin;");
break;
case 8715:
target.write("&#ni;");
break;
case 8719:
target.write("&#prod;");
break;
case 8721:
target.write("&#sum;");
break;
case 8722:
target.write("&#minus;");
break;
case 8727:
target.write("&#lowast;");
break;
case 8730:
target.write("&#radic;");
break;
case 8733:
target.write("&#prop;");
break;
case 8734:
target.write("&#infin;");
break;
case 8736:
target.write("&#ang;");
break;
case 8743:
target.write("&#and;");
break;
case 8744:
target.write("&#or;");
break;
case 8745:
target.write("&#cap;");
break;
case 8746:
target.write("&#cup;");
break;
case 8747:
target.write("&#int;");
break;
case 8756:
target.write("&#there4;");
break;
case 8764:
target.write("&#sim;");
break;
case 8773:
target.write("&#cong;");
break;
case 8776:
target.write("&#asymp;");
break;
case 8800:
target.write("&#ne;");
break;
case 8801:
target.write("&#equiv;");
break;
case 8804:
target.write("&#le;");
break;
case 8805:
target.write("&#ge;");
break;
case 8834:
target.write("&#sub;");
break;
case 8835:
target.write("&#sup;");
break;
case 8836:
target.write("&#nsub;");
break;
case 8838:
target.write("&#sube;");
break;
case 8839:
target.write("&#supe;");
break;
case 8853:
target.write("&#oplus;");
break;
case 8855:
target.write("&#otimes;");
break;
case 8869:
target.write("&#perp;");
break;
case 8901:
target.write("&#sdot;");
break;
case 8968:
target.write("&#lceil;");
break;
case 8969:
target.write("&#rceil;");
break;
case 8970:
target.write("&#lfloor;");
break;
case 8971:
target.write("&#rfloor;");
break;
case 9001:
target.write("&#lang;");
break;
case 9002:
target.write("&#rang;");
break;
case 9674:
target.write("&#loz;");
break;
case 9824:
target.write("&#spades;");
break;
case 9827:
target.write("&#clubs;");
break;
case 9829:
target.write("&#hearts;");
break;
case 9830:
target.write("&#diams;");
break;
case 34:
target.write("&#quot;");
break;
case 38:
target.write("&#amp;");
break;
case 60:
target.write("&#lt;");
break;
case 62:
target.write("&#gt;");
break;
case 338:
target.write("&#OElig;");
break;
case 339:
target.write("&#oelig;");
break;
case 352:
target.write("&#Scaron;");
break;
case 353:
target.write("&#scaron;");
break;
case 376:
target.write("&#Yuml;");
break;
case 710:
target.write("&#circ;");
break;
case 732:
target.write("&#tilde;");
break;
case 8194:
target.write("&#ensp;");
break;
case 8195:
target.write("&#emsp;");
break;
case 8201:
target.write("&#thinsp;");
break;
case 8204:
target.write("&#zwnj;");
break;
case 8205:
target.write("&#zwj;");
break;
case 8206:
target.write("&#lrm;");
break;
case 8207:
target.write("&#rlm;");
break;
case 8211:
target.write("&#ndash;");
break;
case 8212:
target.write("&#mdash;");
break;
case 8216:
target.write("&#lsquo;");
break;
case 8217:
target.write("&#rsquo;");
break;
case 8218:
target.write("&#sbquo;");
break;
case 8220:
target.write("&#ldquo;");
break;
default: {
if (Character.isWhitespace(ch)) {
target.write(ch);
} else if (Character.isISOControl(ch)) {
target.write("&#");
target.write(Integer.toString(ch));
target.write(';');
} else {
target.write(ch);
}
}
}
}
}
public enum Presence {
REQUIRED,
OPTIONAL,
FORBIDDEN,
;
}
public enum Element {
A,
ABBR,
ACRONYM,
ADDRESS,
@Deprecated
APPLET,
AREA(true),
B,
BASE(true),
@Deprecated
BASEFONT(true),
BDO,
BIG,
BLOCKQUOTE,
BODY(Presence.OPTIONAL, Presence.OPTIONAL),
BR(true),
BUTTON,
CAPTION,
@Deprecated
CENTER,
CITE,
CODE,
COL(true),
COLGROUP(Presence.REQUIRED, Presence.OPTIONAL),
DD(Presence.REQUIRED, Presence.OPTIONAL),
DEL,
DFN,
DIR,
DIV,
DL,
DT(Presence.REQUIRED, Presence.OPTIONAL),
EM,
FIELDSET,
@Deprecated
FONT,
FORM,
FRAME(true),
FRAMESET,
H1,
H2,
H3,
H4,
H5,
H6,
HEAD(Presence.OPTIONAL, Presence.OPTIONAL),
HR(true),
HTML(Presence.OPTIONAL, Presence.OPTIONAL),
I,
IFRAME,
IMG(true),
INPUT(true),
INS,
@Deprecated
ISINDEX(true),
KBD,
LABEL,
LEGEND,
LI(Presence.REQUIRED, Presence.OPTIONAL),
LINK(true),
MAP,
@Deprecated
MENU,
META(true),
NOFRAMES,
NOSCRIPT,
OBJECT,
OL,
OPTGROUP,
OPTION(Presence.REQUIRED, Presence.OPTIONAL),
P(Presence.REQUIRED, Presence.OPTIONAL),
PARAM(true),
PRE,
Q,
@Deprecated
S,
SAMP,
SCRIPT,
SELECT,
SMALL,
SPAN,
@Deprecated
STRIKE,
STRONG,
STYLE,
SUB,
SUP,
TABLE,
TBODY(Presence.OPTIONAL, Presence.OPTIONAL),
TD(Presence.REQUIRED, Presence.OPTIONAL),
TEXTAREA,
TFOOT(Presence.REQUIRED, Presence.OPTIONAL),
TH(Presence.REQUIRED, Presence.OPTIONAL),
THEAD(Presence.REQUIRED, Presence.OPTIONAL),
TITLE,
TR(Presence.REQUIRED, Presence.OPTIONAL),
TT,
@Deprecated
U,
UL,
VAR,
;
private final boolean empty;
private final Presence start;
private final Presence end;
Element() {
this(false, Presence.REQUIRED, Presence.REQUIRED);
}
Element(final boolean empty) {
this(empty, Presence.REQUIRED, Presence.FORBIDDEN);
}
Element(final Presence start, final Presence end) {
this(false, start, end);
}
Element(boolean empty, Presence start, Presence end) {
this.empty = empty;
this.start = start;
this.end = end;
}
public boolean isEmpty() {
return empty;
}
public Presence getStart() {
return start;
}
public Presence getEnd() {
return end;
}
}
}
| 36,175 | 0.38538 | 0.362009 | 1,181 | 29.650297 | 18.423391 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.829805 | false | false | 0 |
f186102a8aa9cc218d82fe82f7ce7c7863106da0 | 26,388,279,109,013 | 16504a03630a0986521fb05528ef6200b4c1da35 | /platform/platform-middle/platform-middle-servlet/src/main/java/com/sunny/maven/middle/druid/api/DruidStatController.java | 52408587d128f5cafa24e0412451d672df33c170 | []
| no_license | ltybjeagle/project-ltydemo | https://github.com/ltybjeagle/project-ltydemo | 6e7f1a34454c4da8b56db5f6afb668a095c8b49f | 6bbb2ea24ea93ffdec33505d6cfaf20e39bb6c68 | refs/heads/master | 2023-09-02T18:24:03.740000 | 2023-08-19T11:54:54 | 2023-08-19T11:54:54 | 153,546,679 | 3 | 2 | null | false | 2023-01-30T06:16:51 | 2018-10-18T01:40:29 | 2023-01-13T15:24:39 | 2023-01-30T06:15:44 | 14,744 | 2 | 2 | 20 | Java | false | false | package com.sunny.maven.middle.druid.api;
import com.alibaba.druid.stat.DruidStatManagerFacade;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author SUNNY
* @description: DruidStatController
* @create: 2023-04-06 21:58
*/
@RestController
@RequestMapping(value = "/druid")
public class DruidStatController {
@GetMapping("/stat")
public Object druidStat() {
// 获取数据源的监控数据
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}
| UTF-8 | Java | 647 | java | DruidStatController.java | Java | [
{
"context": "eb.bind.annotation.RestController;\n\n/**\n * @author SUNNY\n * @description: DruidStatController\n * @create: ",
"end": 303,
"score": 0.9995719790458679,
"start": 298,
"tag": "USERNAME",
"value": "SUNNY"
}
]
| null | []
| package com.sunny.maven.middle.druid.api;
import com.alibaba.druid.stat.DruidStatManagerFacade;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author SUNNY
* @description: DruidStatController
* @create: 2023-04-06 21:58
*/
@RestController
@RequestMapping(value = "/druid")
public class DruidStatController {
@GetMapping("/stat")
public Object druidStat() {
// 获取数据源的监控数据
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}
| 647 | 0.76236 | 0.743222 | 21 | 28.857143 | 23.178984 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 0 |
55148ba54105e34692b91e4647d2cabeb5407bb1 | 28,887,950,096,396 | 87481a4a36b141df92e9fc2a7818c7c80e21cbba | /src/com/hejiascm/domains/org/_OrgInfo.java | 80ceb1319a859b5ca3401c616531994f1fb2e05c | []
| no_license | glucoding/hjbc | https://github.com/glucoding/hjbc | 31cb4ab67499b01d4031c052c7b63a8e849033b8 | e4099e7035308256cbfcdfe74a7c570875dd72bd | refs/heads/master | 2021-01-20T02:46:57.773000 | 2018-01-30T09:44:02 | 2018-01-30T09:44:02 | 89,453,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hejiascm.domains.org;
import com.ibm.crl.bc.hejia.sdk.organization.OrgInfo;
public class _OrgInfo extends OrgInfo {
private String orgType;
private String orgAddress;
private String orgRep;
private String establishDate;
private String validityTerm;
private String businessScope;
private String registrationId;
private String orgCode;
private String taxCode;
private String tel;
private String registrationAmount;
private String admin;
private String email;
private String mobile;
private String password;
private String opid;
private String submitTime;
private String approveTime;
private String quitTime;
private String orgCat;
private String invitingMobile;
private String authCode;
private String mobileAuthCode;
private String orgCodeTerm;
private String openApprovAuthNum;
private String orgTrustCode;
private String repCerType;
private String repCerNum;
private String repCerTerm;
private String agentName;
private String agentType;
private String agentCerNum;
private String agentCerTerm;
private String agentEmail;
private String regAddr;
private String comAddr;
private String financeGrantNo;
private String certStatus;
public _OrgInfo() {
// TODO Auto-generated constructor stub
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getOrgAddress() {
return orgAddress;
}
public void setOrgAddress(String orgAddress) {
this.orgAddress = orgAddress;
}
public String getOrgRep() {
return orgRep;
}
public void setOrgRep(String orgRep) {
this.orgRep = orgRep;
}
public String getEstablishDate() {
return establishDate;
}
public void setEstablishDate(String establishDate) {
this.establishDate = establishDate;
}
public String getValidityTerm() {
return validityTerm;
}
public void setValidityTerm(String validityTerm) {
this.validityTerm = validityTerm;
}
public String getBusinessScope() {
return businessScope;
}
public void setBusinessScope(String businessScope) {
this.businessScope = businessScope;
}
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getRegistrationAmount() {
return registrationAmount;
}
public void setRegistrationAmount(String registrationAmount) {
this.registrationAmount = registrationAmount;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getOpid() {
return opid;
}
public void setOpid(String opid) {
this.opid = opid;
}
public String getSubmitTime() {
return submitTime;
}
public void setSubmitTime(String submitTime) {
this.submitTime = submitTime;
}
public String getApproveTime() {
return approveTime;
}
public void setApproveTime(String approveTime) {
this.approveTime = approveTime;
}
public String getQuitTime() {
return quitTime;
}
public void setQuitTime(String quitTime) {
this.quitTime = quitTime;
}
public String getOrgCat() {
return orgCat;
}
public void setOrgCat(String orgCat) {
this.orgCat = orgCat;
}
public String getInvitingMobile() {
return invitingMobile;
}
public void setInvitingMobile(String invitingMobile) {
this.invitingMobile = invitingMobile;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getMobileAuthCode() {
return mobileAuthCode;
}
public void setMobileAuthCode(String mobileAuthCode) {
this.mobileAuthCode = mobileAuthCode;
}
public String getOrgCodeTerm() {
return orgCodeTerm;
}
public void setOrgCodeTerm(String orgCodeTerm) {
this.orgCodeTerm = orgCodeTerm;
}
public String getOpenApprovAuthNum() {
return openApprovAuthNum;
}
public void setOpenApprovAuthNum(String openApprovAuthNum) {
this.openApprovAuthNum = openApprovAuthNum;
}
public String getOrgTrustCode() {
return orgTrustCode;
}
public void setOrgTrustCode(String orgTrustCode) {
this.orgTrustCode = orgTrustCode;
}
public String getRepCerType() {
return repCerType;
}
public void setRepCerType(String repCerType) {
this.repCerType = repCerType;
}
public String getRepCerNum() {
return repCerNum;
}
public void setRepCerNum(String repCerNum) {
this.repCerNum = repCerNum;
}
public String getRepCerTerm() {
return repCerTerm;
}
public void setRepCerTerm(String repCerTerm) {
this.repCerTerm = repCerTerm;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentType() {
return agentType;
}
public void setAgentType(String agentType) {
this.agentType = agentType;
}
public String getAgentCerNum() {
return agentCerNum;
}
public void setAgentCerNum(String agentCerNum) {
this.agentCerNum = agentCerNum;
}
public String getAgentCerTerm() {
return agentCerTerm;
}
public void setAgentCerTerm(String agentCerTerm) {
this.agentCerTerm = agentCerTerm;
}
public String getAgentEmail() {
return agentEmail;
}
public void setAgentEmail(String agentEmail) {
this.agentEmail = agentEmail;
}
public String getRegAddr() {
return regAddr;
}
public void setRegAddr(String regAddr) {
this.regAddr = regAddr;
}
public String getComAddr() {
return comAddr;
}
public void setComAddr(String comAddr) {
this.comAddr = comAddr;
}
public String getFinanceGrantNo() {
return financeGrantNo;
}
public void setFinanceGrantNo(String financeGrantNo) {
this.financeGrantNo = financeGrantNo;
}
public String getCertStatus() {
return certStatus;
}
public void setCertStatus(String certStatus) {
this.certStatus = certStatus;
}
}
| UTF-8 | Java | 6,921 | java | _OrgInfo.java | Java | [
{
"context": " setPassword(String password) {\r\n\t\tthis.password = password;\r\n\t}\r\n\r\n\tpublic String getOpid() {\r\n\t\treturn opid",
"end": 3442,
"score": 0.9825137257575989,
"start": 3434,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.hejiascm.domains.org;
import com.ibm.crl.bc.hejia.sdk.organization.OrgInfo;
public class _OrgInfo extends OrgInfo {
private String orgType;
private String orgAddress;
private String orgRep;
private String establishDate;
private String validityTerm;
private String businessScope;
private String registrationId;
private String orgCode;
private String taxCode;
private String tel;
private String registrationAmount;
private String admin;
private String email;
private String mobile;
private String password;
private String opid;
private String submitTime;
private String approveTime;
private String quitTime;
private String orgCat;
private String invitingMobile;
private String authCode;
private String mobileAuthCode;
private String orgCodeTerm;
private String openApprovAuthNum;
private String orgTrustCode;
private String repCerType;
private String repCerNum;
private String repCerTerm;
private String agentName;
private String agentType;
private String agentCerNum;
private String agentCerTerm;
private String agentEmail;
private String regAddr;
private String comAddr;
private String financeGrantNo;
private String certStatus;
public _OrgInfo() {
// TODO Auto-generated constructor stub
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getOrgAddress() {
return orgAddress;
}
public void setOrgAddress(String orgAddress) {
this.orgAddress = orgAddress;
}
public String getOrgRep() {
return orgRep;
}
public void setOrgRep(String orgRep) {
this.orgRep = orgRep;
}
public String getEstablishDate() {
return establishDate;
}
public void setEstablishDate(String establishDate) {
this.establishDate = establishDate;
}
public String getValidityTerm() {
return validityTerm;
}
public void setValidityTerm(String validityTerm) {
this.validityTerm = validityTerm;
}
public String getBusinessScope() {
return businessScope;
}
public void setBusinessScope(String businessScope) {
this.businessScope = businessScope;
}
public String getRegistrationId() {
return registrationId;
}
public void setRegistrationId(String registrationId) {
this.registrationId = registrationId;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(String taxCode) {
this.taxCode = taxCode;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getRegistrationAmount() {
return registrationAmount;
}
public void setRegistrationAmount(String registrationAmount) {
this.registrationAmount = registrationAmount;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getOpid() {
return opid;
}
public void setOpid(String opid) {
this.opid = opid;
}
public String getSubmitTime() {
return submitTime;
}
public void setSubmitTime(String submitTime) {
this.submitTime = submitTime;
}
public String getApproveTime() {
return approveTime;
}
public void setApproveTime(String approveTime) {
this.approveTime = approveTime;
}
public String getQuitTime() {
return quitTime;
}
public void setQuitTime(String quitTime) {
this.quitTime = quitTime;
}
public String getOrgCat() {
return orgCat;
}
public void setOrgCat(String orgCat) {
this.orgCat = orgCat;
}
public String getInvitingMobile() {
return invitingMobile;
}
public void setInvitingMobile(String invitingMobile) {
this.invitingMobile = invitingMobile;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getMobileAuthCode() {
return mobileAuthCode;
}
public void setMobileAuthCode(String mobileAuthCode) {
this.mobileAuthCode = mobileAuthCode;
}
public String getOrgCodeTerm() {
return orgCodeTerm;
}
public void setOrgCodeTerm(String orgCodeTerm) {
this.orgCodeTerm = orgCodeTerm;
}
public String getOpenApprovAuthNum() {
return openApprovAuthNum;
}
public void setOpenApprovAuthNum(String openApprovAuthNum) {
this.openApprovAuthNum = openApprovAuthNum;
}
public String getOrgTrustCode() {
return orgTrustCode;
}
public void setOrgTrustCode(String orgTrustCode) {
this.orgTrustCode = orgTrustCode;
}
public String getRepCerType() {
return repCerType;
}
public void setRepCerType(String repCerType) {
this.repCerType = repCerType;
}
public String getRepCerNum() {
return repCerNum;
}
public void setRepCerNum(String repCerNum) {
this.repCerNum = repCerNum;
}
public String getRepCerTerm() {
return repCerTerm;
}
public void setRepCerTerm(String repCerTerm) {
this.repCerTerm = repCerTerm;
}
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentType() {
return agentType;
}
public void setAgentType(String agentType) {
this.agentType = agentType;
}
public String getAgentCerNum() {
return agentCerNum;
}
public void setAgentCerNum(String agentCerNum) {
this.agentCerNum = agentCerNum;
}
public String getAgentCerTerm() {
return agentCerTerm;
}
public void setAgentCerTerm(String agentCerTerm) {
this.agentCerTerm = agentCerTerm;
}
public String getAgentEmail() {
return agentEmail;
}
public void setAgentEmail(String agentEmail) {
this.agentEmail = agentEmail;
}
public String getRegAddr() {
return regAddr;
}
public void setRegAddr(String regAddr) {
this.regAddr = regAddr;
}
public String getComAddr() {
return comAddr;
}
public void setComAddr(String comAddr) {
this.comAddr = comAddr;
}
public String getFinanceGrantNo() {
return financeGrantNo;
}
public void setFinanceGrantNo(String financeGrantNo) {
this.financeGrantNo = financeGrantNo;
}
public String getCertStatus() {
return certStatus;
}
public void setCertStatus(String certStatus) {
this.certStatus = certStatus;
}
}
| 6,923 | 0.705678 | 0.705678 | 352 | 17.661932 | 16.783443 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.315341 | false | false | 0 |
de7cfef8608a1f2e994d4820430f82bee8cc755f | 18,975,165,574,675 | 9fd6fd95b3a8a01d3c84a8d2e47e03c218dd3fcc | /DVIR/SVN/src/com/iana/dvir/action/IEPFlagUpdateAdminAction.java | 0588728a784521afca29f097a2133ae42b01cc27 | []
| no_license | chauhanvipul87/web_jsp_servlet_iic_dvir | https://github.com/chauhanvipul87/web_jsp_servlet_iic_dvir | 72e15cdb54f0b7e623ac8d580746f0fea48636e8 | 7338a128be6247b7b481cbce8f8195a616eec4e3 | refs/heads/master | 2016-09-07T02:49:20.494000 | 2014-08-21T11:39:36 | 2014-08-21T11:39:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author 256126
*
*/
package com.iana.dvir.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.iana.dvir.exception.DVIRException;
import com.iana.dvir.formbean.DVIRConfigurationFormBean;
import com.iana.dvir.sessionfacade.DVIRConfigSessionFacade;
public class IEPFlagUpdateAdminAction extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(IEPFlagUpdateAdminAction.class);
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
log.info("Entering IEPFlagUpdateAdminAction class");
String url="/pages/IEPConfigUpdate.jsp";
DVIRConfigurationFormBean form = new DVIRConfigurationFormBean();
DVIRConfigSessionFacade iepflagdet = new DVIRConfigSessionFacade();
int updateStatus = 0;
if(req.getParameter("id")!=null && !(req.getParameter("id").toString().equals("")))
{
req.setAttribute("userID", req.getParameter("id"));
form.setUserID(req.getParameter("id"));
}
if(req.getParameter("mode")!=null && !(req.getParameter("mode").toString().equals("")) && (req.getParameter("mode").toString().equalsIgnoreCase("update")))
{
log.info("Inside IEP Flage Update");
if(req.getParameter("dvirSenderReceiver")!=null)
{
log.info("FLAG :"+req.getParameter("dvirSenderReceiver"));
form.setSenderReceiverFlag(req.getParameter("dvirSenderReceiver"));
}
if(req.getParameter("userID")!=null && !(req.getParameter("userID").toString().equals("")))
{
form.setUserID(req.getParameter("userID"));
}
req.setAttribute("formBean", form);
try
{
updateStatus=iepflagdet.updateIEPConfiguration(form);
if(updateStatus==1)
{
log.info("Data Updated Sucessfully");
req.setAttribute("update", "success");
}
else
{
log.error("Error occured while updating the record");
req.setAttribute("update", "error");
}
}
catch (DVIRException e)
{
log.error("Caught Exception");
req.setAttribute("update", "error");
e.printStackTrace();
}
}
try
{
log.info("Getting Flag details for IEP id :" + form.getUserID());
DVIRConfigurationFormBean formdata = new DVIRConfigurationFormBean();
formdata=iepflagdet.getIEPDetails(form.getUserID());
if(formdata!=null)
{
req.setAttribute("formBean", formdata);
}
else
{
log.error("Error occured while fetching details from database");
req.setAttribute("error", "errorGetDetails");
}
}
catch (DVIRException e)
{
log.error("Caught Exception while retrieving details");
req.setAttribute("error", "errorGetDetails");
e.printStackTrace();
}
log.info("Exiting IEPFlagUpdateAdminAction class");
RequestDispatcher dispatch = req.getRequestDispatcher(url);
dispatch.forward(req, resp);
}
}
| UTF-8 | Java | 3,274 | java | IEPFlagUpdateAdminAction.java | Java | [
{
"context": "/**\n * @author 256126\n * \n */\n\npackage com.iana.dvir.action;\n\nimport ja",
"end": 21,
"score": 0.998656690120697,
"start": 15,
"tag": "USERNAME",
"value": "256126"
}
]
| null | []
| /**
* @author 256126
*
*/
package com.iana.dvir.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.iana.dvir.exception.DVIRException;
import com.iana.dvir.formbean.DVIRConfigurationFormBean;
import com.iana.dvir.sessionfacade.DVIRConfigSessionFacade;
public class IEPFlagUpdateAdminAction extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(IEPFlagUpdateAdminAction.class);
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
log.info("Entering IEPFlagUpdateAdminAction class");
String url="/pages/IEPConfigUpdate.jsp";
DVIRConfigurationFormBean form = new DVIRConfigurationFormBean();
DVIRConfigSessionFacade iepflagdet = new DVIRConfigSessionFacade();
int updateStatus = 0;
if(req.getParameter("id")!=null && !(req.getParameter("id").toString().equals("")))
{
req.setAttribute("userID", req.getParameter("id"));
form.setUserID(req.getParameter("id"));
}
if(req.getParameter("mode")!=null && !(req.getParameter("mode").toString().equals("")) && (req.getParameter("mode").toString().equalsIgnoreCase("update")))
{
log.info("Inside IEP Flage Update");
if(req.getParameter("dvirSenderReceiver")!=null)
{
log.info("FLAG :"+req.getParameter("dvirSenderReceiver"));
form.setSenderReceiverFlag(req.getParameter("dvirSenderReceiver"));
}
if(req.getParameter("userID")!=null && !(req.getParameter("userID").toString().equals("")))
{
form.setUserID(req.getParameter("userID"));
}
req.setAttribute("formBean", form);
try
{
updateStatus=iepflagdet.updateIEPConfiguration(form);
if(updateStatus==1)
{
log.info("Data Updated Sucessfully");
req.setAttribute("update", "success");
}
else
{
log.error("Error occured while updating the record");
req.setAttribute("update", "error");
}
}
catch (DVIRException e)
{
log.error("Caught Exception");
req.setAttribute("update", "error");
e.printStackTrace();
}
}
try
{
log.info("Getting Flag details for IEP id :" + form.getUserID());
DVIRConfigurationFormBean formdata = new DVIRConfigurationFormBean();
formdata=iepflagdet.getIEPDetails(form.getUserID());
if(formdata!=null)
{
req.setAttribute("formBean", formdata);
}
else
{
log.error("Error occured while fetching details from database");
req.setAttribute("error", "errorGetDetails");
}
}
catch (DVIRException e)
{
log.error("Caught Exception while retrieving details");
req.setAttribute("error", "errorGetDetails");
e.printStackTrace();
}
log.info("Exiting IEPFlagUpdateAdminAction class");
RequestDispatcher dispatch = req.getRequestDispatcher(url);
dispatch.forward(req, resp);
}
}
| 3,274 | 0.701894 | 0.698839 | 115 | 27.469564 | 28.742128 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.026087 | false | false | 0 |
a1dbd1dc8a3d087fc47dcab1713897d23a369196 | 24,034,637,047,357 | 4c64f35c63fa2b1a17a3e997f91d61b0b2eacfd5 | /JavaTutorial/src/main/java/Practical_Code/Generic_Programming/not_parameterized.java | 737df0ac54ebb90685cdb636e2e1ead27491a1e7 | []
| no_license | MohamedElhoseny/JavaSE | https://github.com/MohamedElhoseny/JavaSE | 7d0951467263157656e0fc94b34b2d98221f5d40 | f41d45a4125a1dbcaa60fc3b895f3f3df33b7e1f | refs/heads/master | 2020-04-17T09:24:08.669000 | 2019-01-19T08:14:52 | 2019-01-19T08:14:52 | 166,456,159 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Practical_Code.Generic_Programming;
public class not_parameterized
{
Object o;
public void set(Object o)
{
this.o = o;
}
public Object get()
{
return this.o;
}
}
| UTF-8 | Java | 199 | java | not_parameterized.java | Java | []
| null | []
| package Practical_Code.Generic_Programming;
public class not_parameterized
{
Object o;
public void set(Object o)
{
this.o = o;
}
public Object get()
{
return this.o;
}
}
| 199 | 0.623116 | 0.623116 | 14 | 13.214286 | 13.006474 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 0 |
d0c901f402710264b3d031e9d9f11efc60981313 | 31,379,031,126,142 | c31ebb4e8e7b3a3f211d666c8f3f1063bdadb9d9 | /src/main/java/com/punwire/brain/Axiom.java | bf7ce2077e440773b770805043682d45046c7ae5 | []
| no_license | singh72641/Brain | https://github.com/singh72641/Brain | 15b5a73c6385e2268b881e5a53e5b936ce60b1c5 | 12731caaa0bac64fd353b5c33f7c7e81131b50d8 | refs/heads/master | 2021-06-21T06:47:24.618000 | 2017-08-14T18:51:21 | 2017-08-14T18:51:21 | 100,299,536 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.punwire.brain;
/**
* Created by admin on 7/14/2017.
*/
public class Axiom {
float value = 0.0f;
}
| UTF-8 | Java | 117 | java | Axiom.java | Java | [
{
"context": "package com.punwire.brain;\n\n/**\n * Created by admin on 7/14/2017.\n */\npublic class Axiom {\n float ",
"end": 51,
"score": 0.998273491859436,
"start": 46,
"tag": "USERNAME",
"value": "admin"
}
]
| null | []
| package com.punwire.brain;
/**
* Created by admin on 7/14/2017.
*/
public class Axiom {
float value = 0.0f;
}
| 117 | 0.632479 | 0.555556 | 8 | 13.625 | 12.388881 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
2b9c3227b95d50fcb604da1a9f4c40b9161dba5e | 6,459,630,843,495 | 43aa135f1d0983b5a8a8455857931c720d8787df | /oms/web3-NewDc/plugin/web3-sle-gateway/java/webbroker3/slegateway/service/delegate/WEB3SleSendqProcessorManagerService.java | 4644d6ddf2569d7c16a618b306a963bdca1edaaa | [
"Apache-2.0",
"W3C-19980720",
"Apache-1.1",
"BSD-2-Clause"
]
| permissive | leegine/COMS | https://github.com/leegine/COMS | d8637ee07d0d0cc83187cf216c5b423d19ce9c43 | f8d9027ca0b6f3656843d908b0c6b95600266193 | refs/heads/master | 2020-04-18T05:37:41.079000 | 2019-01-29T08:31:38 | 2019-01-29T08:31:38 | 167,285,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | head 1.1;
access;
symbols;
locks; strict;
comment @// @;
1.1
date 2011.03.14.07.02.11; author che-jin; state Exp;
branches;
next ;
deltatype text;
kopt kv;
permissions 666;
commitid 5744d7dbcbd3406;
filename WEB3SleSendqProcessorManagerService.java;
desc
@@
1.1
log
@*** empty log message ***
@
text
@/**
Copyright : (株)大和総研 証券ソリューションシステム第二部
File Name : SleSendqProcessorManagerServiceクラス
Author Name : Daiwa Institute of Research
Revision History : 2006/04/24 呉 新規作成
@ @ @ @ @ @ @ @ @ 2006/09/20 李 WEB3実装方針にあわせ
*/
package webbroker3.slegateway.service.delegate;
import webbroker3.common.service.delegate.WEB3BusinessService;
import webbroker3.common.WEB3BaseException;
import webbroker3.common.message.WEB3GenRequest;
import webbroker3.common.message.WEB3GenResponse;
/**
* SEND_Q送信管理クラスのインタフェース
*/
public interface WEB3SleSendqProcessorManagerService extends WEB3BusinessService{
/**
* send_q送信管理処理を実施する。<BR>
* @@param l_request - (リクエストデータ)<BR>
* リクエストデータ<BR>
*
* @@return WEB3GenResponse
* @@throws WEB3BaseException
*/
public WEB3GenResponse execute(WEB3GenRequest l_request) throws WEB3BaseException;
}
@
| SHIFT_JIS | Java | 1,346 | java | WEB3SleSendqProcessorManagerService.java | Java | [
{
"context": "ment\t@// @;\n\n\n1.1\ndate\t2011.03.14.07.02.11;\tauthor che-jin;\tstate Exp;\nbranches;\nnext\t;\ndeltatype\ttext;\nkopt",
"end": 103,
"score": 0.9996634125709534,
"start": 96,
"tag": "USERNAME",
"value": "che-jin"
}
]
| null | []
| head 1.1;
access;
symbols;
locks; strict;
comment @// @;
1.1
date 2011.03.14.07.02.11; author che-jin; state Exp;
branches;
next ;
deltatype text;
kopt kv;
permissions 666;
commitid 5744d7dbcbd3406;
filename WEB3SleSendqProcessorManagerService.java;
desc
@@
1.1
log
@*** empty log message ***
@
text
@/**
Copyright : (株)大和総研 証券ソリューションシステム第二部
File Name : SleSendqProcessorManagerServiceクラス
Author Name : Daiwa Institute of Research
Revision History : 2006/04/24 呉 新規作成
@ @ @ @ @ @ @ @ @ 2006/09/20 李 WEB3実装方針にあわせ
*/
package webbroker3.slegateway.service.delegate;
import webbroker3.common.service.delegate.WEB3BusinessService;
import webbroker3.common.WEB3BaseException;
import webbroker3.common.message.WEB3GenRequest;
import webbroker3.common.message.WEB3GenResponse;
/**
* SEND_Q送信管理クラスのインタフェース
*/
public interface WEB3SleSendqProcessorManagerService extends WEB3BusinessService{
/**
* send_q送信管理処理を実施する。<BR>
* @@param l_request - (リクエストデータ)<BR>
* リクエストデータ<BR>
*
* @@return WEB3GenResponse
* @@throws WEB3BaseException
*/
public WEB3GenResponse execute(WEB3GenRequest l_request) throws WEB3BaseException;
}
@
| 1,346 | 0.740137 | 0.683533 | 56 | 19.821428 | 21.985472 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
fbd48f26db6becbccfe464e9731dc4076f7e1db9 | 36,498,632,085,004 | 3813cbb3abce251b98612116208b8796fa0572cc | /src/main/java/com/packt/webstore/dao/ProductDAOImpl.java | f7ee92120646c1d8ffb92a647bfb7e3fffb96ff3 | []
| no_license | dbaluguri/SpringMVC | https://github.com/dbaluguri/SpringMVC | dc940b17b73d83ca48d6a933b0b9a71b27038ff6 | 79a6844d355fc86a5b663e8c63715f6643f6bc4d | refs/heads/master | 2020-05-09T16:07:34.033000 | 2015-09-25T18:59:28 | 2015-09-25T18:59:28 | 41,447,019 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.packt.webstore.dao;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
@Repository
public class ProductDAOImpl implements ProductDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
Session session = sessionFactory.getCurrentSession();
return session;
}
public Product getProductById(String productId) {
Session session = getSession();
Product product = (Product)session.get(Product.class, productId);
/*
Product productById = null;
for (Product product : listOfProducts) {
if (product != null && product.getProductId() != null && product.getProductId().equals(productId)) {
productById = product;
break;
}
} */
if (product == null) {
throw new IllegalArgumentException("No products found with the product id: " + productId);
}
return product;
}
public List<Product> getAllProducts() {
Session session = getSession();
Query query = session.createQuery("from Product");
return query.list();
}
public List<Product> getProductsByCategory(String category) {
/*List<Product> productsByCategory = new ArrayList<Product>();
for (Product product : listOfProducts) {
if (category.equalsIgnoreCase(product.getCategory())) {
productsByCategory.add(product);
}
}
return productsByCategory;
*/
return null;
}
public Set<Product> getProductsByFilter(Map<String, List<String>> filterParams) {
/*Set<Product> productsByBrand = new HashSet<Product>();
Set<Product> productsByCategory = new HashSet<Product>();
Set<String> criterias = filterParams.keySet();
if (criterias.contains("brand")) {
for (String brandName : filterParams.get("brand")) {
for (Product product : listOfProducts) {
if (brandName.equalsIgnoreCase(product.getManufacturer())) {
productsByBrand.add(product);
}
}
}
}
if (criterias.contains("category")) {
for (String category : filterParams.get("category")) {
productsByCategory.addAll(this.getProductsByCategory(category));
}
}
productsByCategory.retainAll(productsByBrand);
return productsByCategory;
*/
return null;
}
public void addProduct(Product product) {
Session session = getSession();
try {
session.save(product);
} catch (HibernateException he) {
he.printStackTrace();
}
}
}
| UTF-8 | Java | 2,676 | java | ProductDAOImpl.java | Java | []
| null | []
| package com.packt.webstore.dao;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.packt.webstore.domain.Product;
@Repository
public class ProductDAOImpl implements ProductDAO {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
Session session = sessionFactory.getCurrentSession();
return session;
}
public Product getProductById(String productId) {
Session session = getSession();
Product product = (Product)session.get(Product.class, productId);
/*
Product productById = null;
for (Product product : listOfProducts) {
if (product != null && product.getProductId() != null && product.getProductId().equals(productId)) {
productById = product;
break;
}
} */
if (product == null) {
throw new IllegalArgumentException("No products found with the product id: " + productId);
}
return product;
}
public List<Product> getAllProducts() {
Session session = getSession();
Query query = session.createQuery("from Product");
return query.list();
}
public List<Product> getProductsByCategory(String category) {
/*List<Product> productsByCategory = new ArrayList<Product>();
for (Product product : listOfProducts) {
if (category.equalsIgnoreCase(product.getCategory())) {
productsByCategory.add(product);
}
}
return productsByCategory;
*/
return null;
}
public Set<Product> getProductsByFilter(Map<String, List<String>> filterParams) {
/*Set<Product> productsByBrand = new HashSet<Product>();
Set<Product> productsByCategory = new HashSet<Product>();
Set<String> criterias = filterParams.keySet();
if (criterias.contains("brand")) {
for (String brandName : filterParams.get("brand")) {
for (Product product : listOfProducts) {
if (brandName.equalsIgnoreCase(product.getManufacturer())) {
productsByBrand.add(product);
}
}
}
}
if (criterias.contains("category")) {
for (String category : filterParams.get("category")) {
productsByCategory.addAll(this.getProductsByCategory(category));
}
}
productsByCategory.retainAll(productsByBrand);
return productsByCategory;
*/
return null;
}
public void addProduct(Product product) {
Session session = getSession();
try {
session.save(product);
} catch (HibernateException he) {
he.printStackTrace();
}
}
}
| 2,676 | 0.724215 | 0.724215 | 101 | 25.49505 | 23.911812 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.069307 | false | false | 0 |
918f37d2d3545676b18714f02aa69880a7b3bff4 | 3,255,585,234,064 | d64cb2636912d06a68ca8f2558dea12cb89d12c1 | /src/main/java/exceptions/Arithmetic.java | 881cfc55dddde3fe140509cf4b8d9ec400f9e4ef | []
| no_license | GizemYamasan/advanced-java | https://github.com/GizemYamasan/advanced-java | e3e3903213878deffdb7c2696e6b33a1bf7695a7 | ffd9bb5b6b04e07d9193f50d4f603c07702429db | refs/heads/master | 2020-04-09T10:01:31.963000 | 2018-12-03T22:24:46 | 2018-12-03T22:24:46 | 160,255,110 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package exceptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Arithmetic {
public static void main(String[] args) {
int x = 3;
int y = 0;
double z = 0;
try{
z = x / y;
}catch(ArithmeticException e){
System.err.println(e);;
}finally{
System.out.println("This gets called in any case");
}
System.out.printf("x = %d, y = %d, z = %s%n",x, y, z);
try {
Arithmetic.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Path dir = Paths.get("src", "main", "java","exceptions");
// Before try with resources statements implementations looks like that
// BufferedReader br = null;
// try {
// br = Files.newBufferedReader(dir.resolve("Arithmetic.java"));
// System.out.println(br.readLine());
// } catch(IOException e){
// e.printStackTrace();
// }
// finally {
// if (br != null) try{
// br.close();
// }catch (IOException e) {
// e.printStackTrace();
// }
// }
//
try (BufferedReader br = Files.newBufferedReader(dir.resolve("Arithmetic.java"));){
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
try {
throw new MyException();
} catch (MyException e) {
System.err.println(e.getMessage());
}
}
}
| UTF-8 | Java | 1,442 | java | Arithmetic.java | Java | []
| null | []
| package exceptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Arithmetic {
public static void main(String[] args) {
int x = 3;
int y = 0;
double z = 0;
try{
z = x / y;
}catch(ArithmeticException e){
System.err.println(e);;
}finally{
System.out.println("This gets called in any case");
}
System.out.printf("x = %d, y = %d, z = %s%n",x, y, z);
try {
Arithmetic.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Path dir = Paths.get("src", "main", "java","exceptions");
// Before try with resources statements implementations looks like that
// BufferedReader br = null;
// try {
// br = Files.newBufferedReader(dir.resolve("Arithmetic.java"));
// System.out.println(br.readLine());
// } catch(IOException e){
// e.printStackTrace();
// }
// finally {
// if (br != null) try{
// br.close();
// }catch (IOException e) {
// e.printStackTrace();
// }
// }
//
try (BufferedReader br = Files.newBufferedReader(dir.resolve("Arithmetic.java"));){
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
try {
throw new MyException();
} catch (MyException e) {
System.err.println(e.getMessage());
}
}
}
| 1,442 | 0.634535 | 0.632455 | 64 | 21.53125 | 19.749184 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.484375 | false | false | 0 |
939f5b82d028225d17da091ce6fedb6b39c5b89b | 23,364,622,159,982 | fe445b05c21b6f0360358fd682f590c66a984931 | /src/main/java/pl/narodzinyprrogramsity/parser/DataParser.java | b8797d5f41eb966d9639ffd297289be8c32ec7c7 | []
| no_license | Kwarku/JDBCLibrary | https://github.com/Kwarku/JDBCLibrary | 57ce51c879a826caeb806a2195053f366db4cd0b | 9ebf37db254d7c41524837a75611c5c6cb2d7229 | refs/heads/master | 2020-03-18T16:40:53.398000 | 2018-05-26T17:06:43 | 2018-05-26T17:06:43 | 134,980,048 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.narodzinyprrogramsity.parser;
import pl.narodzinyprrogramsity.model.BaseModel;
import java.sql.ResultSet;
import java.util.List;
public interface DataParser<T extends BaseModel> {
List<T> parseToList(ResultSet resultSet);
}
| UTF-8 | Java | 242 | java | DataParser.java | Java | []
| null | []
| package pl.narodzinyprrogramsity.parser;
import pl.narodzinyprrogramsity.model.BaseModel;
import java.sql.ResultSet;
import java.util.List;
public interface DataParser<T extends BaseModel> {
List<T> parseToList(ResultSet resultSet);
}
| 242 | 0.805785 | 0.805785 | 10 | 23.200001 | 20.512436 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
cfd2557a5e80fe8ba5e9a90d76f9298b4f498ed1 | 35,613,868,828,400 | 415d7bcc6338412a774485270195a3901e483c06 | /src/main/java/com/sportmonks/endpoints/RoundsEndPoint.java | e06f81060a04b54df1442dafc38ed1261e97b234 | [
"MIT"
]
| permissive | pacheikhcisse/sportmonks-soccer | https://github.com/pacheikhcisse/sportmonks-soccer | 2383354a9548bd96b7da9b2fc70e414e83fdc5a6 | 463c395ab63c9e2a313ec982a795b68233af1950 | refs/heads/master | 2021-09-09T17:48:09.888000 | 2018-03-18T17:40:52 | 2018-03-18T17:40:52 | 108,539,486 | 0 | 0 | null | true | 2017-10-27T11:45:56 | 2017-10-27T11:45:56 | 2017-06-06T13:44:27 | 2017-07-26T14:58:06 | 102 | 0 | 0 | 0 | null | false | null | package com.sportmonks.endpoints;
import com.mashape.unirest.http.HttpResponse;
import com.sportmonks.data.entity.Round;
import com.sportmonks.data.structure.Rounds;
import com.sportmonks.exceptions.HaveToDefineValidIdException;
import com.sportmonks.tools.RestTool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RoundsEndPoint extends AbstractEndPoint {
private static final String BASE_URL = AbstractEndPoint.API_URL + AbstractEndPoint.VERSION + "/rounds";
private static final String BY_SEASON_URL = BASE_URL + "/season/{seasonId}";
private static RoundsEndPoint INSTANCE;
private long lastTeamProxyCall = 0;
public RoundsEndPoint(Double hourRateLimit) {
super(hourRateLimit);
}
public static RoundsEndPoint getInstance(final Double customHourRateLimit) {
if (INSTANCE == null) {
INSTANCE = new RoundsEndPoint(customHourRateLimit);
}
return INSTANCE;
}
/**
* Liste de toutes les journées d'une saison
*
* @param seasonId
* @return
*/
public List<Round> findBySeason(final Long seasonId) {
final RoundsEndPointParams params = new RoundsEndPointParams();
params.setSeasonId(seasonId);
return findBySeason(params);
}
/**
* Liste de toutes les journées pour une saison avec les relations définies
*/
public List<Round> findBySeason(final RoundsEndPointParams params) {
if (!params.isValidSeasonId()) {
throw new HaveToDefineValidIdException();
}
return findResults(BY_SEASON_URL, params);
}
/**
* Retourne une liste de résultat
*
* @param url
* @param params
* @return
*/
private List<Round> findResults(final String url, final RoundsEndPointParams params) {
lastTeamProxyCall = waitBeforeNextCall(lastTeamProxyCall);
final Map<String, String> paramsMap = new HashMap<>();
if (params != null) {
paramsMap.put("includes", params.getRelations());
if (params.isValidSeasonId()) {
paramsMap.put("seasonId", params.getSeasonId().toString());
}
}
final HttpResponse<Rounds> httpResponse = RestTool.get(url, paramsMap, Rounds.class);
final List<Round> response = new ArrayList<>();
if (httpResponse != null) {
Rounds body = httpResponse.getBody();
if (body != null) {
List<Round> data = body.getData();
if (data != null) {
response.addAll(data);
}
}
}
return response;
}
/**
* Round relations
*/
public enum Relation {
fixtures, season, league
}
}
| UTF-8 | Java | 2,466 | java | RoundsEndPoint.java | Java | []
| null | []
| package com.sportmonks.endpoints;
import com.mashape.unirest.http.HttpResponse;
import com.sportmonks.data.entity.Round;
import com.sportmonks.data.structure.Rounds;
import com.sportmonks.exceptions.HaveToDefineValidIdException;
import com.sportmonks.tools.RestTool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RoundsEndPoint extends AbstractEndPoint {
private static final String BASE_URL = AbstractEndPoint.API_URL + AbstractEndPoint.VERSION + "/rounds";
private static final String BY_SEASON_URL = BASE_URL + "/season/{seasonId}";
private static RoundsEndPoint INSTANCE;
private long lastTeamProxyCall = 0;
public RoundsEndPoint(Double hourRateLimit) {
super(hourRateLimit);
}
public static RoundsEndPoint getInstance(final Double customHourRateLimit) {
if (INSTANCE == null) {
INSTANCE = new RoundsEndPoint(customHourRateLimit);
}
return INSTANCE;
}
/**
* Liste de toutes les journées d'une saison
*
* @param seasonId
* @return
*/
public List<Round> findBySeason(final Long seasonId) {
final RoundsEndPointParams params = new RoundsEndPointParams();
params.setSeasonId(seasonId);
return findBySeason(params);
}
/**
* Liste de toutes les journées pour une saison avec les relations définies
*/
public List<Round> findBySeason(final RoundsEndPointParams params) {
if (!params.isValidSeasonId()) {
throw new HaveToDefineValidIdException();
}
return findResults(BY_SEASON_URL, params);
}
/**
* Retourne une liste de résultat
*
* @param url
* @param params
* @return
*/
private List<Round> findResults(final String url, final RoundsEndPointParams params) {
lastTeamProxyCall = waitBeforeNextCall(lastTeamProxyCall);
final Map<String, String> paramsMap = new HashMap<>();
if (params != null) {
paramsMap.put("includes", params.getRelations());
if (params.isValidSeasonId()) {
paramsMap.put("seasonId", params.getSeasonId().toString());
}
}
final HttpResponse<Rounds> httpResponse = RestTool.get(url, paramsMap, Rounds.class);
final List<Round> response = new ArrayList<>();
if (httpResponse != null) {
Rounds body = httpResponse.getBody();
if (body != null) {
List<Round> data = body.getData();
if (data != null) {
response.addAll(data);
}
}
}
return response;
}
/**
* Round relations
*/
public enum Relation {
fixtures, season, league
}
}
| 2,466 | 0.721365 | 0.720959 | 101 | 23.376238 | 25.035757 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.594059 | false | false | 0 |
1b6f8961c0f38d72cd0dc2b8401e0ffc58ec7de0 | 11,381,663,357,294 | d94661973c6cdf896f90c211260134898786a77f | /Final_Project/Testing/LoginSystemTesting.java | b710080713272b8ab92d97522c5e02b2c8dba359 | []
| no_license | ShuvamDas123/CSC207_Final_Project | https://github.com/ShuvamDas123/CSC207_Final_Project | 5dd6284efcd1103b159c899368d31094c5c4e01d | 2645d633068e282271ee5f183a86c3005d0e4769 | refs/heads/main | 2023-04-19T13:15:25.083000 | 2021-05-09T10:03:47 | 2021-05-09T10:03:47 | 332,470,779 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import ConferenceControllers.LoginReceiver;
import UI.InterfaceController;
import org.junit.Test;
import UseCases.ConversationManager;
import UseCases.UserManager;
public class LoginSystemTesting {
/*
@Test(timeout = 5000)
public void AllTestsLogin() throws ClassNotFoundException {
UserManager userManager = new UserManager();
ConversationManager conversationManager = new ConversationManager();
InterfaceController interfaceController = new InterfaceController();
userManager.createAttendee("Dave", "pineapples");
userManager.createAttendee("John", "oranges");
userManager.createAttendee("Anthony", "peaches");
LoginReceiver loginReceiver = new LoginReceiver(userManager,interfaceController);
assert loginReceiver.login("Dave", "pineapples") == 3;
assert loginReceiver.login("John", "oranges") == 3;
assert loginReceiver.login("Anthony", "peaches") == 3;
assert loginReceiver.login("Pat", "beinghuman") == 0;
assert loginReceiver.login("Pat", "beinghuman") == 0;
// check the user differentiation
userManager.createOrganizer("Jack", "pineapples");
userManager.createOrganizer("Harry", "pineaåpples");
assert loginReceiver.login("Harry", "pineaåpples") == 1;
assert loginReceiver.login("Jack", "pineapples") == 1;
// check speaker
userManager.createSpeaker("Ted","oranges");
userManager.createSpeaker("Tess", "oranges");
assert loginReceiver.login("Ted","oranges") == 2;
assert loginReceiver.login("Tess","oranges") == 2;
}*/
}
| UTF-8 | Java | 1,634 | java | LoginSystemTesting.java | Java | [
{
"context": "Controller();\n userManager.createAttendee(\"Dave\", \"pineapples\");\n userManager.createAttend",
"end": 544,
"score": 0.9996597766876221,
"start": 540,
"tag": "NAME",
"value": "Dave"
},
{
"context": "pineapples\");\n userManager.createAttendee(\"John\", \"oranges\");\n userManager.createAttendee(",
"end": 602,
"score": 0.9996617436408997,
"start": 598,
"tag": "NAME",
"value": "John"
},
{
"context": "es\");\n userManager.createAttendee(\"John\", \"oranges\");\n userManager.createAttendee(\"Anthony\", ",
"end": 613,
"score": 0.9789023399353027,
"start": 606,
"tag": "NAME",
"value": "oranges"
},
{
"context": ", \"oranges\");\n userManager.createAttendee(\"Anthony\", \"peaches\");\n\n LoginReceiver loginReceive",
"end": 660,
"score": 0.9993494153022766,
"start": 653,
"tag": "NAME",
"value": "Anthony"
},
{
"context": "eController);\n assert loginReceiver.login(\"Dave\", \"pineapples\") == 3;\n assert loginReceive",
"end": 806,
"score": 0.9996402263641357,
"start": 802,
"tag": "NAME",
"value": "Dave"
},
{
"context": "pples\") == 3;\n assert loginReceiver.login(\"John\", \"oranges\") == 3;\n assert loginReceiver.l",
"end": 869,
"score": 0.9992640614509583,
"start": 865,
"tag": "NAME",
"value": "John"
},
{
"context": "== 3;\n assert loginReceiver.login(\"John\", \"oranges\") == 3;\n assert loginReceiver.login(\"Antho",
"end": 880,
"score": 0.948562502861023,
"start": 873,
"tag": "NAME",
"value": "oranges"
},
{
"context": "anges\") == 3;\n assert loginReceiver.login(\"Anthony\", \"peaches\") == 3;\n\n assert loginReceiver.",
"end": 932,
"score": 0.9991199970245361,
"start": 925,
"tag": "NAME",
"value": "Anthony"
},
{
"context": "ches\") == 3;\n\n assert loginReceiver.login(\"Pat\", \"beinghuman\") == 0;\n assert loginReceive",
"end": 992,
"score": 0.9995335340499878,
"start": 989,
"tag": "NAME",
"value": "Pat"
},
{
"context": "human\") == 0;\n assert loginReceiver.login(\"Pat\", \"beinghuman\") == 0;\n\n // check the user ",
"end": 1054,
"score": 0.9995891451835632,
"start": 1051,
"tag": "NAME",
"value": "Pat"
},
{
"context": "ferentiation\n userManager.createOrganizer(\"Jack\", \"pineapples\");\n userManager.createOrgani",
"end": 1161,
"score": 0.9996530413627625,
"start": 1157,
"tag": "NAME",
"value": "Jack"
},
{
"context": "ineapples\");\n userManager.createOrganizer(\"Harry\", \"pineaåpples\");\n\n assert loginReceiver.",
"end": 1221,
"score": 0.9995858669281006,
"start": 1216,
"tag": "NAME",
"value": "Harry"
},
{
"context": "eaåpples\");\n\n assert loginReceiver.login(\"Harry\", \"pineaåpples\") == 1;\n assert loginReceiv",
"end": 1283,
"score": 0.9993748664855957,
"start": 1278,
"tag": "NAME",
"value": "Harry"
},
{
"context": "pples\") == 1;\n assert loginReceiver.login(\"Jack\", \"pineapples\") == 1;\n\n // check speaker\n ",
"end": 1347,
"score": 0.9994977116584778,
"start": 1343,
"tag": "NAME",
"value": "Jack"
},
{
"context": " check speaker\n userManager.createSpeaker(\"Ted\",\"oranges\");\n userManager.createSpeaker(\"T",
"end": 1434,
"score": 0.9992454051971436,
"start": 1431,
"tag": "NAME",
"value": "Ted"
},
{
"context": "er\n userManager.createSpeaker(\"Ted\",\"oranges\");\n userManager.createSpeaker(\"Tess\", \"ora",
"end": 1444,
"score": 0.5680937767028809,
"start": 1443,
"tag": "NAME",
"value": "s"
},
{
"context": "d\",\"oranges\");\n userManager.createSpeaker(\"Tess\", \"oranges\");\n\n assert loginReceiver.logi",
"end": 1487,
"score": 0.9994080662727356,
"start": 1483,
"tag": "NAME",
"value": "Tess"
},
{
"context": "ges\");\n userManager.createSpeaker(\"Tess\", \"oranges\");\n\n assert loginReceiver.login(\"Ted\",\"or",
"end": 1498,
"score": 0.821540892124176,
"start": 1491,
"tag": "NAME",
"value": "oranges"
},
{
"context": "\"oranges\");\n\n assert loginReceiver.login(\"Ted\",\"oranges\") == 2;\n assert loginReceiver.lo",
"end": 1543,
"score": 0.9993161559104919,
"start": 1540,
"tag": "NAME",
"value": "Ted"
},
{
"context": "es\");\n\n assert loginReceiver.login(\"Ted\",\"oranges\") == 2;\n assert loginReceiver.login(\"Tess\"",
"end": 1553,
"score": 0.6916037797927856,
"start": 1546,
"tag": "NAME",
"value": "oranges"
},
{
"context": "anges\") == 2;\n assert loginReceiver.login(\"Tess\",\"oranges\") == 2;\n\n }*/\n}\n",
"end": 1602,
"score": 0.9989630579948425,
"start": 1598,
"tag": "NAME",
"value": "Tess"
},
{
"context": " == 2;\n assert loginReceiver.login(\"Tess\",\"oranges\") == 2;\n\n }*/\n}\n",
"end": 1612,
"score": 0.7887879014015198,
"start": 1605,
"tag": "NAME",
"value": "oranges"
}
]
| null | []
| import ConferenceControllers.LoginReceiver;
import UI.InterfaceController;
import org.junit.Test;
import UseCases.ConversationManager;
import UseCases.UserManager;
public class LoginSystemTesting {
/*
@Test(timeout = 5000)
public void AllTestsLogin() throws ClassNotFoundException {
UserManager userManager = new UserManager();
ConversationManager conversationManager = new ConversationManager();
InterfaceController interfaceController = new InterfaceController();
userManager.createAttendee("Dave", "pineapples");
userManager.createAttendee("John", "oranges");
userManager.createAttendee("Anthony", "peaches");
LoginReceiver loginReceiver = new LoginReceiver(userManager,interfaceController);
assert loginReceiver.login("Dave", "pineapples") == 3;
assert loginReceiver.login("John", "oranges") == 3;
assert loginReceiver.login("Anthony", "peaches") == 3;
assert loginReceiver.login("Pat", "beinghuman") == 0;
assert loginReceiver.login("Pat", "beinghuman") == 0;
// check the user differentiation
userManager.createOrganizer("Jack", "pineapples");
userManager.createOrganizer("Harry", "pineaåpples");
assert loginReceiver.login("Harry", "pineaåpples") == 1;
assert loginReceiver.login("Jack", "pineapples") == 1;
// check speaker
userManager.createSpeaker("Ted","oranges");
userManager.createSpeaker("Tess", "oranges");
assert loginReceiver.login("Ted","oranges") == 2;
assert loginReceiver.login("Tess","oranges") == 2;
}*/
}
| 1,634 | 0.68076 | 0.672794 | 42 | 37.857143 | 26.956377 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 0 |
d783f7c255e3a21fe849705181b62cf52fe4866a | 10,608,569,231,442 | f9f679559c51fc9e25d85c4b44ab3d52073658b9 | /Functions/src/roles/functions/Role08_DontRepeatYourself.java | 2b4b78b89d12166847666716d444b398b0c527bb | []
| no_license | LightWay152/Chapter03_Functions | https://github.com/LightWay152/Chapter03_Functions | 545004376c2c86307a53e54840b9bc3b5132e546 | b143b64e8b9dd0a0cb74f16455ff4728d461cdc5 | refs/heads/master | 2021-07-11T08:22:42.744000 | 2017-10-10T16:36:37 | 2017-10-10T16:36:37 | 106,443,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package roles.functions;
public class Role08_DontRepeatYourself {
public static void main(String[] args) {
System.out.print(addTwoOddNumber(6,9));
System.out.println();
System.out.print(subTwoOddNumber(6,9));
}
private static String subTwoOddNumber(int numberA, int numberB) {
if(numberA % 3 == 0){
if(numberB % 3 == 0){
return numberA - numberB + "";
}
else{
return "A, B does not even number, do not calculate!";
}
}
else{
return "A, B does not even number, do not calculate!";
}
}
private static String addTwoOddNumber(int numberA, int numberB) {
if(numberA % 3 == 0){
if(numberB % 3 == 0){
return numberA + numberB + "";
}
else{
return "A, B does not even number, do not calculate!";
}
}
else{
return "A, B does not even number, do not calculate!";
}
}
}
| UTF-8 | Java | 838 | java | Role08_DontRepeatYourself.java | Java | []
| null | []
| package roles.functions;
public class Role08_DontRepeatYourself {
public static void main(String[] args) {
System.out.print(addTwoOddNumber(6,9));
System.out.println();
System.out.print(subTwoOddNumber(6,9));
}
private static String subTwoOddNumber(int numberA, int numberB) {
if(numberA % 3 == 0){
if(numberB % 3 == 0){
return numberA - numberB + "";
}
else{
return "A, B does not even number, do not calculate!";
}
}
else{
return "A, B does not even number, do not calculate!";
}
}
private static String addTwoOddNumber(int numberA, int numberB) {
if(numberA % 3 == 0){
if(numberB % 3 == 0){
return numberA + numberB + "";
}
else{
return "A, B does not even number, do not calculate!";
}
}
else{
return "A, B does not even number, do not calculate!";
}
}
}
| 838 | 0.630072 | 0.613365 | 38 | 21.052631 | 21.585751 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.552632 | false | false | 0 |
fdece9001c3ffc87206400f627468b02a0a5d3fa | 8,272,107,061,416 | e2169c2fd39ab0882a05c3fdac93d02be0fbdb53 | /src/hr/fer/oop/helping/Solution.java | c5b7cba8bfcfe9036e8d6d9bdb124e0bdf36cec3 | []
| no_license | babe1304/OOP | https://github.com/babe1304/OOP | c13583d6bd69ed1d0dcc6412f57767723940b299 | 1d37b68ae0563a7950ef13235c421b366b906cbc | refs/heads/master | 2023-08-25T07:21:20.054000 | 2021-11-06T14:33:51 | 2021-11-06T14:33:51 | 425,265,443 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hr.fer.oop.helping;
import java.util.*;
public class Solution implements StudentDatabase {
Map<String, Map<String, Integer>> rezultati = new HashMap<>();
@Override
public void addEntry(String student, String course, int score) {
Map<String, Integer> ocjenaPredmeta = new HashMap<>();
ocjenaPredmeta.put(course, score);
if (!rezultati.containsKey(student)) rezultati.put(student, ocjenaPredmeta);
else {
if (rezultati.get(student).containsKey(course)) rezultati.get(student).replace(course, score);
else rezultati.get(student).put(course, score);
}
}
@Override
public Integer getScore(String student, String course) {
if (!rezultati.containsKey(student)) return null;
if (!rezultati.get(student).containsKey(course)) return null;
return rezultati.get(student).get(course);
}
@Override
public Collection<Integer> getNaturallyOrderedScoresByCourse(String course) {
List<Integer> ocjene = new ArrayList<>();
for (Map<String, Integer> opp : rezultati.values()) {
if (opp.containsKey(course)) ocjene.add(opp.get(course));
}
Collections.sort(ocjene);
return ocjene;
}
}
| UTF-8 | Java | 1,258 | java | Solution.java | Java | []
| null | []
| package hr.fer.oop.helping;
import java.util.*;
public class Solution implements StudentDatabase {
Map<String, Map<String, Integer>> rezultati = new HashMap<>();
@Override
public void addEntry(String student, String course, int score) {
Map<String, Integer> ocjenaPredmeta = new HashMap<>();
ocjenaPredmeta.put(course, score);
if (!rezultati.containsKey(student)) rezultati.put(student, ocjenaPredmeta);
else {
if (rezultati.get(student).containsKey(course)) rezultati.get(student).replace(course, score);
else rezultati.get(student).put(course, score);
}
}
@Override
public Integer getScore(String student, String course) {
if (!rezultati.containsKey(student)) return null;
if (!rezultati.get(student).containsKey(course)) return null;
return rezultati.get(student).get(course);
}
@Override
public Collection<Integer> getNaturallyOrderedScoresByCourse(String course) {
List<Integer> ocjene = new ArrayList<>();
for (Map<String, Integer> opp : rezultati.values()) {
if (opp.containsKey(course)) ocjene.add(opp.get(course));
}
Collections.sort(ocjene);
return ocjene;
}
}
| 1,258 | 0.653418 | 0.653418 | 36 | 33.944443 | 30.110855 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 0 |
012be37afc2bd30351faabacf49b64b39891436b | 4,939,212,430,557 | 735c653fb4b56e5c00a89ee262bb12aca4dfae2e | /src/main/java/com/lwy/demo/mapper/CartMapper.java | 21407c16527e54f6794073b2a7e82f0543c9ea2b | []
| no_license | Willi-Lau/I.TSHOP | https://github.com/Willi-Lau/I.TSHOP | 0cc409c11ad3e5c787492238ca39c262e9f5f49b | 3f7cfd23a43e4431f2b7614aad94ae5578b69daf | refs/heads/master | 2023-02-24T22:18:35.333000 | 2021-02-01T10:58:06 | 2021-02-01T10:58:06 | 334,913,187 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lwy.demo.mapper;
import com.lwy.demo.bean.Cart;
import com.lwy.demo.bean.CartHistory;
import com.lwy.demo.bean.Cart_Clothes;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CartMapper {
/**
*查询购物车中是否有要添加的货物的信息
*/
@Select("select COUNT(*) from cart where username = #{username} and id = #{id}")
int selecttocart(Cart cart);
/**
* 入宫没有添加到购物车
* @param cart
*/
@Insert("insert into cart (username,id,num) values(#{username},#{id},#{num})")
void addtocart(Cart cart);
/**
* 如果有就是修改
*/
@Update("update cart set num = num + #{num} where username = #{username} and id = #{id}")
void updatetocart(Cart cart);
/**
* 修改仓库的数据
*/
@Update("update clothes set num = num - #{num} where id = #{id}")
void updatetoclothes(Cart cart);
/**
* 查询现在购物车的货物
*
*/
List<Cart_Clothes> selectcartclothes(String name);
/**
* 支付
*/
@Delete("delete from cart where username = #{name}")
void paycartclothes (String name);
/**
* 查询指定用户的总消费
*/
@Select("select grossmoney from user where username = #{name}")
int selectgrossmoney(String name);
/**
* 修改指定用户总消费
*/
@Update("update user set grossmoney = #{grossmoney} where username = #{name}")
void updategrossmoney(String name,int grossmoney);
/**
* 向购物车历史信息添加
*/
@Insert("insert into carthistory(username,id,num,money,day,src) values (#{username},#{id},#{num},#{money},#{day},#{src})")
void addcarthistory(CartHistory cartHistory);
}
| UTF-8 | Java | 1,979 | java | CartMapper.java | Java | [
{
"context": "ect(\"select COUNT(*) from cart where username = #{username} and id = #{id}\")\n int selecttocart(Cart cart",
"end": 544,
"score": 0.5223541259765625,
"start": 536,
"tag": "USERNAME",
"value": "username"
},
{
"context": "te cart set num = num + #{num} where username = #{username} and id = #{id}\")\n void updatetocart(Cart cart",
"end": 873,
"score": 0.7216544151306152,
"start": 865,
"tag": "USERNAME",
"value": "username"
},
{
"context": "thistory(username,id,num,money,day,src) values (#{username},#{id},#{num},#{money},#{day},#{src})\")\n void ",
"end": 1716,
"score": 0.9964839220046997,
"start": 1708,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package com.lwy.demo.mapper;
import com.lwy.demo.bean.Cart;
import com.lwy.demo.bean.CartHistory;
import com.lwy.demo.bean.Cart_Clothes;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CartMapper {
/**
*查询购物车中是否有要添加的货物的信息
*/
@Select("select COUNT(*) from cart where username = #{username} and id = #{id}")
int selecttocart(Cart cart);
/**
* 入宫没有添加到购物车
* @param cart
*/
@Insert("insert into cart (username,id,num) values(#{username},#{id},#{num})")
void addtocart(Cart cart);
/**
* 如果有就是修改
*/
@Update("update cart set num = num + #{num} where username = #{username} and id = #{id}")
void updatetocart(Cart cart);
/**
* 修改仓库的数据
*/
@Update("update clothes set num = num - #{num} where id = #{id}")
void updatetoclothes(Cart cart);
/**
* 查询现在购物车的货物
*
*/
List<Cart_Clothes> selectcartclothes(String name);
/**
* 支付
*/
@Delete("delete from cart where username = #{name}")
void paycartclothes (String name);
/**
* 查询指定用户的总消费
*/
@Select("select grossmoney from user where username = #{name}")
int selectgrossmoney(String name);
/**
* 修改指定用户总消费
*/
@Update("update user set grossmoney = #{grossmoney} where username = #{name}")
void updategrossmoney(String name,int grossmoney);
/**
* 向购物车历史信息添加
*/
@Insert("insert into carthistory(username,id,num,money,day,src) values (#{username},#{id},#{num},#{money},#{day},#{src})")
void addcarthistory(CartHistory cartHistory);
}
| 1,979 | 0.633756 | 0.633756 | 70 | 24.9 | 26.622843 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false | 0 |
d89e55f5085844970b739482282ee8054a7c63d6 | 22,058,952,073,830 | 5e2cd3bf64acb50829feb1ef2aee77f1a7083d89 | /src/main/java/id/co/mandiri/dao/DeviceDao.java | 719baeae4e1cc0fd5bf3ac858e930310598a5e62 | []
| no_license | Herdi94/FinalProjectBootcampBackend | https://github.com/Herdi94/FinalProjectBootcampBackend | c6eeab828fb66767ba50a65350b4195684002b3d | 46b427bdd5ecec5d8585282814771ad1a92ac4a3 | refs/heads/master | 2020-04-20T18:34:25.272000 | 2019-02-04T07:17:20 | 2019-02-04T07:17:20 | 169,025,171 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package id.co.mandiri.dao;
import com.maryanto.dimas.plugins.web.commons.ui.datatables.DataTablesRequest;
import com.maryanto.dimas.plugins.web.commons.ui.datatables.dao.DaoCrudDataTablesPattern;
import id.co.mandiri.entity.Device;
import id.co.mandiri.repository.DeviceRepository;
import id.co.mandiri.utils.QueryComparator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class DeviceDao implements DaoCrudDataTablesPattern<Device, String> {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
private DeviceRepository DeviceRepository;
@Override
public Device findId(String s) {
return DeviceRepository.findOne(s);
}
@Override
@Deprecated
public List<Device> findAll() {
return null;
}
@Override
public Device save(Device device) {
return DeviceRepository.save(device);
}
@Override
public Device update(Device device) {
return DeviceRepository.save(device);
}
@Override
public boolean remove(Device device) {
DeviceRepository.delete(device);
return true;
}
@Override
public boolean removeById(String s) {
DeviceRepository.delete(s);
return true;
}
@Override
public List<Device> datatables(DataTablesRequest<Device> params) {
String baseQuery = "select id, name\n" +
"from device\n" +
"where 1 = 1 ";
Device param = params.getValue();
DeviceQueryCompare compare = new DeviceQueryCompare(baseQuery);
StringBuilder query = compare.getQuery(param);
MapSqlParameterSource values = compare.getParameters();
switch (params.getColOrder().intValue()) {
case 0:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by id asc ");
else
query.append(" order by id desc ");
break;
case 1:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by name asc ");
else
query.append(" order by name desc ");
break;
default:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by id asc ");
else
query.append(" order by id desc ");
break;
}
query.append("limit :limit offset :offset");
values.addValue("offset", params.getStart());
values.addValue("limit", params.getLength());
return this.jdbcTemplate.query(query.toString(), values, (resultSet, i) ->
new Device (
resultSet.getString("id"),
resultSet.getString("name")
));
}
@Override
public Long datatables(Device param) {
String baseQuery = "select count(id) as rows \n" +
"from device\n" +
"where 1 = 1 ";
DeviceQueryCompare compare = new DeviceQueryCompare(baseQuery);
StringBuilder query = compare.getQuery(param);
MapSqlParameterSource values = compare.getParameters();
return this.jdbcTemplate.queryForObject(
query.toString(),
values,
(resultSet, i) -> resultSet.getLong("rows")
);
}
private class DeviceQueryCompare implements QueryComparator<Device> {
private MapSqlParameterSource parameterSource;
private StringBuilder query;
DeviceQueryCompare(String query) {
this.parameterSource = new MapSqlParameterSource();
this.query = new StringBuilder(query);
}
@Override
public StringBuilder getQuery(Device param) {
if (StringUtils.isNoneBlank(param.getId())) {
query.append(" and lower(id) like :id ");
parameterSource.addValue("id",
new StringBuilder("%")
.append(param.getId().toLowerCase())
.append("%")
.toString());
}
if (StringUtils.isNoneBlank(param.getName())) {
query.append(" and lower(name) like :name ");
parameterSource.addValue("name", new StringBuilder("%")
.append(param.getName().toLowerCase())
.append("%")
.toString());
}
return query;
}
@Override
public MapSqlParameterSource getParameters() {
return this.parameterSource;
}
}
}
| UTF-8 | Java | 5,102 | java | DeviceDao.java | Java | []
| null | []
| package id.co.mandiri.dao;
import com.maryanto.dimas.plugins.web.commons.ui.datatables.DataTablesRequest;
import com.maryanto.dimas.plugins.web.commons.ui.datatables.dao.DaoCrudDataTablesPattern;
import id.co.mandiri.entity.Device;
import id.co.mandiri.repository.DeviceRepository;
import id.co.mandiri.utils.QueryComparator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class DeviceDao implements DaoCrudDataTablesPattern<Device, String> {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Autowired
private DeviceRepository DeviceRepository;
@Override
public Device findId(String s) {
return DeviceRepository.findOne(s);
}
@Override
@Deprecated
public List<Device> findAll() {
return null;
}
@Override
public Device save(Device device) {
return DeviceRepository.save(device);
}
@Override
public Device update(Device device) {
return DeviceRepository.save(device);
}
@Override
public boolean remove(Device device) {
DeviceRepository.delete(device);
return true;
}
@Override
public boolean removeById(String s) {
DeviceRepository.delete(s);
return true;
}
@Override
public List<Device> datatables(DataTablesRequest<Device> params) {
String baseQuery = "select id, name\n" +
"from device\n" +
"where 1 = 1 ";
Device param = params.getValue();
DeviceQueryCompare compare = new DeviceQueryCompare(baseQuery);
StringBuilder query = compare.getQuery(param);
MapSqlParameterSource values = compare.getParameters();
switch (params.getColOrder().intValue()) {
case 0:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by id asc ");
else
query.append(" order by id desc ");
break;
case 1:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by name asc ");
else
query.append(" order by name desc ");
break;
default:
if (StringUtils.equalsIgnoreCase(params.getColDir(), "asc"))
query.append(" order by id asc ");
else
query.append(" order by id desc ");
break;
}
query.append("limit :limit offset :offset");
values.addValue("offset", params.getStart());
values.addValue("limit", params.getLength());
return this.jdbcTemplate.query(query.toString(), values, (resultSet, i) ->
new Device (
resultSet.getString("id"),
resultSet.getString("name")
));
}
@Override
public Long datatables(Device param) {
String baseQuery = "select count(id) as rows \n" +
"from device\n" +
"where 1 = 1 ";
DeviceQueryCompare compare = new DeviceQueryCompare(baseQuery);
StringBuilder query = compare.getQuery(param);
MapSqlParameterSource values = compare.getParameters();
return this.jdbcTemplate.queryForObject(
query.toString(),
values,
(resultSet, i) -> resultSet.getLong("rows")
);
}
private class DeviceQueryCompare implements QueryComparator<Device> {
private MapSqlParameterSource parameterSource;
private StringBuilder query;
DeviceQueryCompare(String query) {
this.parameterSource = new MapSqlParameterSource();
this.query = new StringBuilder(query);
}
@Override
public StringBuilder getQuery(Device param) {
if (StringUtils.isNoneBlank(param.getId())) {
query.append(" and lower(id) like :id ");
parameterSource.addValue("id",
new StringBuilder("%")
.append(param.getId().toLowerCase())
.append("%")
.toString());
}
if (StringUtils.isNoneBlank(param.getName())) {
query.append(" and lower(name) like :name ");
parameterSource.addValue("name", new StringBuilder("%")
.append(param.getName().toLowerCase())
.append("%")
.toString());
}
return query;
}
@Override
public MapSqlParameterSource getParameters() {
return this.parameterSource;
}
}
}
| 5,102 | 0.584085 | 0.582713 | 161 | 30.689442 | 24.684654 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447205 | false | false | 0 |
d400e4e79b532fc54f2999b7f7c1994cb865f35e | 22,058,952,073,755 | 806c23cba0d7fd3ea07a358eda573c28179c25ca | /Computer.java | f32fb32ec910294a0c6d43e70b98b21c3da4d3f9 | []
| no_license | yuyonshen/147852 | https://github.com/yuyonshen/147852 | e1219be90cb6d1b118309e2fd8dfa80f11a8ac68 | 1017d583191051b3551180b5895f48863d28d942 | refs/heads/master | 2020-09-21T12:59:26.097000 | 2020-04-01T08:30:02 | 2020-04-01T08:30:02 | 224,795,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Computer {
String screen="液晶显示屏";
void startup(){
System.out.println("电脑正在开机,请等待......");
}
}
class Pad extends Computer{
String battery="5000毫安电池";
public static void main(String[] args) {
Computer pc=new Computer();
System.out.println("电脑的屏幕是:"+pc.screen);
pc.startup();
Pad ipad=new Pad();
System.out.println("pad的屏幕是:"+ipad.screen);
System.out.println("pad的电池是:"+ipad.battery);
ipad.startup();
}
}
| UTF-8 | Java | 581 | java | Computer.java | Java | []
| null | []
| public class Computer {
String screen="液晶显示屏";
void startup(){
System.out.println("电脑正在开机,请等待......");
}
}
class Pad extends Computer{
String battery="5000毫安电池";
public static void main(String[] args) {
Computer pc=new Computer();
System.out.println("电脑的屏幕是:"+pc.screen);
pc.startup();
Pad ipad=new Pad();
System.out.println("pad的屏幕是:"+ipad.screen);
System.out.println("pad的电池是:"+ipad.battery);
ipad.startup();
}
}
| 581 | 0.583497 | 0.575639 | 20 | 24.4 | 17.573845 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
118f4b32e7a64de8dfd4b0086392a5a131f52443 | 36,679,020,712,765 | fa20bb300daa5f912baab2e6df9af86922d5fbae | /re.java | 961aead4b66e887faa6554520ef91d5045eb1a72 | []
| no_license | booleantrue1/JavaCodes | https://github.com/booleantrue1/JavaCodes | 4ef8314b6f2ae5599383ea3104c0b0d0a4c5bbc1 | 8e5524a8f31dc68329186e16d1ffdb63d2bf8e22 | refs/heads/master | 2021-01-01T04:58:02.861000 | 2016-05-12T23:21:18 | 2016-05-12T23:21:18 | 58,675,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int t=0,j=0,k=0,n=0,i=0;
int d[];
String s,r;
r=b.readLine();
s=b.readLine();
StringTokenizer e=new StringTokenizer(r);
n=Integer.parseInt(e.nextToken());
k=Integer.parseInt(e.nextToken());
d=new int[n];
StringTokenizer c=new StringTokenizer(s);
for(i=0;i<n;i++)
d[i]=Integer.parseInt(c.nextToken());
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(d[i]>d[j])
{
t=d[j];
d[j]=d[i];
d[i]=t;
}
}
}
t=n-k;
if(t>=0)
System.out.print(d[t]+" "+d[t]);
else
System.out.print("-1");
}
} | UTF-8 | Java | 648 | java | re.java | Java | []
| null | []
| import java.io.*;
import java.util.*;
class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int t=0,j=0,k=0,n=0,i=0;
int d[];
String s,r;
r=b.readLine();
s=b.readLine();
StringTokenizer e=new StringTokenizer(r);
n=Integer.parseInt(e.nextToken());
k=Integer.parseInt(e.nextToken());
d=new int[n];
StringTokenizer c=new StringTokenizer(s);
for(i=0;i<n;i++)
d[i]=Integer.parseInt(c.nextToken());
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(d[i]>d[j])
{
t=d[j];
d[j]=d[i];
d[i]=t;
}
}
}
t=n-k;
if(t>=0)
System.out.print(d[t]+" "+d[t]);
else
System.out.print("-1");
}
} | 648 | 0.654321 | 0.637346 | 38 | 16.078947 | 16.187035 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.815789 | false | false | 0 |
d526f6e6fb96825c1304ce4073d07df1bc10c2c4 | 34,411,277,999,134 | c454f4dbc21268d6bfc12cf29402b5e1ce2f05cf | /src/main/java/server/integration/consumers/UserConsumer.java | 63278638c5292d1381c30b585e7a3bce60012753 | [
"MIT"
]
| permissive | Rinori99/Authentication | https://github.com/Rinori99/Authentication | 5335fab6d5c7876770c38b9f400ce35e24c9253e | e7e56f4bc5f894b7f016fa4c4401536c1aa46bb1 | refs/heads/master | 2022-12-23T03:48:57.704000 | 2020-09-17T14:47:54 | 2020-09-17T14:47:54 | 266,168,083 | 0 | 0 | null | false | 2020-09-13T19:06:41 | 2020-05-22T17:22:29 | 2020-09-13T19:01:16 | 2020-09-13T19:06:41 | 37,239 | 0 | 0 | 0 | Java | false | false | package server.integration.consumers;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import server.integration.models.UserCredentials;
import server.services.AuthUserService;
@Service
public class UserConsumer {
private AuthUserService authUserService;
public UserConsumer(AuthUserService authUserService) {
this.authUserService = authUserService;
}
@RabbitListener(queues = {"${queue.user.new.general}"})
public void handleNewUserReception(UserCredentials userCredentials) {
authUserService.saveAuthUser(userCredentials.getId(), userCredentials.getEmail(), userCredentials.getPassword());
}
}
| UTF-8 | Java | 706 | java | UserConsumer.java | Java | []
| null | []
| package server.integration.consumers;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import server.integration.models.UserCredentials;
import server.services.AuthUserService;
@Service
public class UserConsumer {
private AuthUserService authUserService;
public UserConsumer(AuthUserService authUserService) {
this.authUserService = authUserService;
}
@RabbitListener(queues = {"${queue.user.new.general}"})
public void handleNewUserReception(UserCredentials userCredentials) {
authUserService.saveAuthUser(userCredentials.getId(), userCredentials.getEmail(), userCredentials.getPassword());
}
}
| 706 | 0.788952 | 0.788952 | 22 | 31.09091 | 31.744591 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 0 |
e11e13974fcf9154ad494e03873075a20a8370a0 | 4,363,686,795,484 | 2cbb948bd605718b92a76bdc2bb64270e7092707 | /modules/web/app/models/web/Campus.java | da203c291f71d4fdef8e25804bc784b0adef7fd8 | [
"Apache-2.0"
]
| permissive | derduskenga/StudentConnect | https://github.com/derduskenga/StudentConnect | 2f4b5a78d2476cdcf4b8f88839797e0aaf202db4 | 9eec9dc0a61809535d8b9e0f7d685d8321845d8f | refs/heads/master | 2021-07-17T09:48:25.456000 | 2020-06-03T11:36:42 | 2020-06-03T11:36:42 | 98,464,377 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package models.web;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import play.Logger;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by derdus on 6/15/16.
*/
//For a university institution category, university colleges are included
@Entity
public class Campus extends Model {
@Id
public Long campus_id;
@Constraints.Required(message = "This field is required")
public String campus_name;
@Constraints.Required(message = "This field is required")
public String campus_nearest_town;
@Constraints.Required(message = "This field is required")
public String campus_description;
public Boolean is_main_campus = false;
//Relationship fields/Entity mapping
@ManyToOne
public Institution institution;
@OneToMany(mappedBy = "campus")
public List<InstitutionCourse> institutionCourseList;
@OneToMany(mappedBy = "campus")
public List<CampusCourse> campusCourseList;
@OneToMany(mappedBy = "campus")
public List<SchoolOrFacultyCampus> schoolOrFacultyCampusList;
//methods
public static Finder<Long, Campus> find(){
return new Finder<Long, Campus>(Long.class,Campus.class);
}
public Long saveCampus(){
if(this.campus_id == null){
save();
return campus_id;
}
update();
return campus_id;
}
public Campus getCampusById(Long id){
return find().byId(id);
}
public boolean deleteCampus(Long id){
if (getCampusById(id) != null){
try {
getCampusById(id).delete();;
return true;
}catch (PersistenceException pe){
Logger.error("Error:" + pe.getMessage().toString());
return false;
}catch (Exception ex){
Logger.error("Error:" + ex.getMessage().toString());
}
}
return false;
}
public JSONArray getCampusByInstitution(Institution institution){
JSONArray jsonArray = new JSONArray();
for (int i = 0; i<institution.campusList.size(); i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",institution.campusList.get(i).campus_id);
jsonObject.put("name",institution.campusList.get(i).campus_name);
jsonArray.add(jsonObject);
}
return jsonArray;
}
public Map<Map<Long,String>,Boolean> getCampusMap(){
List<Campus> campusList = find().orderBy("campus_name").findList();
Map<Map<Long,String>,Boolean> campusMap = new LinkedHashMap<Map<Long,String>,Boolean>();
for(int i = 0; i < campusList.size(); i++){
Map<Long,String> innerMap = new HashMap<Long,String>();
innerMap.put(campusList.get(i).campus_id,campusList.get(i).campus_name);
campusMap.put(innerMap,false);
}
return campusMap;
}
public Map<Map<Long,String>,Boolean> getCampusMap(Long id){
List<Campus> campusList = find().orderBy("campus_name").findList();
Map<Map<Long,String>,Boolean> campusMap = new LinkedHashMap<Map<Long,String>,Boolean>();
for(int i = 0; i < campusList.size(); i++){
Map<Long,String> innerMap = new HashMap<Long,String>();
innerMap.put(campusList.get(i).campus_id,campusList.get(i).campus_name);
if(campusList.get(i).campus_id == id){
campusMap.put(innerMap,true);
}else{
campusMap.put(innerMap,false);
}
}
return campusMap;
}
}
| UTF-8 | Java | 3,743 | java | Campus.java | Java | [
{
"context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by derdus on 6/15/16.\n */\n//For a university institution ca",
"end": 336,
"score": 0.9996676445007324,
"start": 330,
"tag": "USERNAME",
"value": "derdus"
}
]
| null | []
| package models.web;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import play.Logger;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by derdus on 6/15/16.
*/
//For a university institution category, university colleges are included
@Entity
public class Campus extends Model {
@Id
public Long campus_id;
@Constraints.Required(message = "This field is required")
public String campus_name;
@Constraints.Required(message = "This field is required")
public String campus_nearest_town;
@Constraints.Required(message = "This field is required")
public String campus_description;
public Boolean is_main_campus = false;
//Relationship fields/Entity mapping
@ManyToOne
public Institution institution;
@OneToMany(mappedBy = "campus")
public List<InstitutionCourse> institutionCourseList;
@OneToMany(mappedBy = "campus")
public List<CampusCourse> campusCourseList;
@OneToMany(mappedBy = "campus")
public List<SchoolOrFacultyCampus> schoolOrFacultyCampusList;
//methods
public static Finder<Long, Campus> find(){
return new Finder<Long, Campus>(Long.class,Campus.class);
}
public Long saveCampus(){
if(this.campus_id == null){
save();
return campus_id;
}
update();
return campus_id;
}
public Campus getCampusById(Long id){
return find().byId(id);
}
public boolean deleteCampus(Long id){
if (getCampusById(id) != null){
try {
getCampusById(id).delete();;
return true;
}catch (PersistenceException pe){
Logger.error("Error:" + pe.getMessage().toString());
return false;
}catch (Exception ex){
Logger.error("Error:" + ex.getMessage().toString());
}
}
return false;
}
public JSONArray getCampusByInstitution(Institution institution){
JSONArray jsonArray = new JSONArray();
for (int i = 0; i<institution.campusList.size(); i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",institution.campusList.get(i).campus_id);
jsonObject.put("name",institution.campusList.get(i).campus_name);
jsonArray.add(jsonObject);
}
return jsonArray;
}
public Map<Map<Long,String>,Boolean> getCampusMap(){
List<Campus> campusList = find().orderBy("campus_name").findList();
Map<Map<Long,String>,Boolean> campusMap = new LinkedHashMap<Map<Long,String>,Boolean>();
for(int i = 0; i < campusList.size(); i++){
Map<Long,String> innerMap = new HashMap<Long,String>();
innerMap.put(campusList.get(i).campus_id,campusList.get(i).campus_name);
campusMap.put(innerMap,false);
}
return campusMap;
}
public Map<Map<Long,String>,Boolean> getCampusMap(Long id){
List<Campus> campusList = find().orderBy("campus_name").findList();
Map<Map<Long,String>,Boolean> campusMap = new LinkedHashMap<Map<Long,String>,Boolean>();
for(int i = 0; i < campusList.size(); i++){
Map<Long,String> innerMap = new HashMap<Long,String>();
innerMap.put(campusList.get(i).campus_id,campusList.get(i).campus_name);
if(campusList.get(i).campus_id == id){
campusMap.put(innerMap,true);
}else{
campusMap.put(innerMap,false);
}
}
return campusMap;
}
}
| 3,743 | 0.624633 | 0.622495 | 114 | 31.833334 | 24.914209 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.745614 | false | false | 0 |
eebeddce112dc3f8fc386a166d200a9262106568 | 7,464,653,183,855 | 7db862dff06dc9a2b1941a80aab89f0b82cd7f0a | /escola/escola/src/main/java/com/ifpb/pds/escola/dao/PessoaDao.java | b35251702d7b5a87ef662c81e0a9b621fc58caef | []
| no_license | isleimar/projetoPDS | https://github.com/isleimar/projetoPDS | fde77f086ff4c69a8986d57b38daf80591a7ef90 | 9189ff12d45b575033c1cd7a2c85a067156305e1 | refs/heads/master | 2020-03-20T14:12:55.254000 | 2018-09-26T15:02:39 | 2018-09-26T15:02:39 | 137,479,566 | 2 | 0 | null | false | 2018-06-16T20:53:07 | 2018-06-15T11:26:08 | 2018-06-16T20:52:18 | 2018-06-16T20:53:07 | 1,022 | 1 | 0 | 0 | null | false | null | package com.ifpb.pds.escola.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.ifpb.pds.escola.database.ConnectionFactory;
import com.ifpb.pds.escola.model.*;
public class PessoaDao {
private ConnectionFactory factory;
public PessoaDao() {
factory = new ConnectionFactory();
}
public boolean salvar(Pessoa pessoa) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO pessoa (nome, cpf, senha, identidade, dataNascimento, sexo, endereco)" +
" VALUES (?,?,?,?,?,?,?)");
statement.setString(1,pessoa.getNome());
statement.setString(2,pessoa.getCpf());
statement.setString(3,pessoa.getSenha());
statement.setString(4,pessoa.getIdentidade());
statement.setDate(5,java.sql.Date.valueOf(pessoa.getNascimento()));
statement.setString(6,String.valueOf(pessoa.getSexo()));
statement.setString(7,pessoa.getEndereco());
return statement.executeUpdate()>0;
}
}
public Pessoa buscarPorCpf(String cpf) throws SQLException, ClassNotFoundException {
try (Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"SELECT nome, cpf, senha, identidade, dataNascimento, sexo, endereco FROM pessoa WHERE cpf = ?"
);
statement.setString(1, cpf);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
Pessoa pessoa = new Pessoa();
pessoa.setNome(resultSet.getString(1));
pessoa.setCpf(resultSet.getString(2));
pessoa.setSenha(resultSet.getString(3));
pessoa.setIdentidade(resultSet.getString(4));
pessoa.setNascimento(resultSet.getDate(5).toLocalDate());
pessoa.setSexo(resultSet.getString(6).charAt(0));
pessoa.setEndereco(resultSet.getString(7));
return pessoa;
} else {
return null;
}
}
}
public boolean deletarPorCpf(String cpf) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"DELETE FROM pessoa WHERE cpf=?"
);
statement.setString(1, cpf);
return statement.executeUpdate() > 0;
}
}
public boolean atualizar(Pessoa pessoa) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"UPDATE pessoa SET nome=?, senha=?, identidade=?, dataNascimento=?, sexo=?, endereco=? "+
"WHERE cpf=? "
);
statement.setString(1,pessoa.getNome());
statement.setString(2,pessoa.getSenha());
statement.setString(3,pessoa.getIdentidade());
statement.setDate(4,java.sql.Date.valueOf(pessoa.getNascimento()));
statement.setString(5,String.valueOf(pessoa.getSexo()));
statement.setString(6,pessoa.getEndereco());
statement.setString(7,pessoa.getCpf());
return statement.executeUpdate()>0;
}
}
}
| UTF-8 | Java | 3,326 | java | PessoaDao.java | Java | [
{
"context": ".prepareStatement(\n\t\t\t\t\t\"UPDATE pessoa SET nome=?, senha=?, identidade=?, dataNascimento=?, sexo=?, endere",
"end": 2812,
"score": 0.9689834117889404,
"start": 2807,
"tag": "NAME",
"value": "senha"
}
]
| null | []
| package com.ifpb.pds.escola.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.ifpb.pds.escola.database.ConnectionFactory;
import com.ifpb.pds.escola.model.*;
public class PessoaDao {
private ConnectionFactory factory;
public PessoaDao() {
factory = new ConnectionFactory();
}
public boolean salvar(Pessoa pessoa) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO pessoa (nome, cpf, senha, identidade, dataNascimento, sexo, endereco)" +
" VALUES (?,?,?,?,?,?,?)");
statement.setString(1,pessoa.getNome());
statement.setString(2,pessoa.getCpf());
statement.setString(3,pessoa.getSenha());
statement.setString(4,pessoa.getIdentidade());
statement.setDate(5,java.sql.Date.valueOf(pessoa.getNascimento()));
statement.setString(6,String.valueOf(pessoa.getSexo()));
statement.setString(7,pessoa.getEndereco());
return statement.executeUpdate()>0;
}
}
public Pessoa buscarPorCpf(String cpf) throws SQLException, ClassNotFoundException {
try (Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"SELECT nome, cpf, senha, identidade, dataNascimento, sexo, endereco FROM pessoa WHERE cpf = ?"
);
statement.setString(1, cpf);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()) {
Pessoa pessoa = new Pessoa();
pessoa.setNome(resultSet.getString(1));
pessoa.setCpf(resultSet.getString(2));
pessoa.setSenha(resultSet.getString(3));
pessoa.setIdentidade(resultSet.getString(4));
pessoa.setNascimento(resultSet.getDate(5).toLocalDate());
pessoa.setSexo(resultSet.getString(6).charAt(0));
pessoa.setEndereco(resultSet.getString(7));
return pessoa;
} else {
return null;
}
}
}
public boolean deletarPorCpf(String cpf) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"DELETE FROM pessoa WHERE cpf=?"
);
statement.setString(1, cpf);
return statement.executeUpdate() > 0;
}
}
public boolean atualizar(Pessoa pessoa) throws SQLException, ClassNotFoundException{
try(Connection connection = factory.getConnection()){
PreparedStatement statement = connection.prepareStatement(
"UPDATE pessoa SET nome=?, senha=?, identidade=?, dataNascimento=?, sexo=?, endereco=? "+
"WHERE cpf=? "
);
statement.setString(1,pessoa.getNome());
statement.setString(2,pessoa.getSenha());
statement.setString(3,pessoa.getIdentidade());
statement.setDate(4,java.sql.Date.valueOf(pessoa.getNascimento()));
statement.setString(5,String.valueOf(pessoa.getSexo()));
statement.setString(6,pessoa.getEndereco());
statement.setString(7,pessoa.getCpf());
return statement.executeUpdate()>0;
}
}
}
| 3,326 | 0.692423 | 0.684305 | 100 | 32.259998 | 27.611092 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.87 | false | false | 0 |
1e49ab22c25e3f6a3eb02485533c35229519458e | 24,309,514,914,830 | f4580422664b06aba3813228f0c51e0ec90f1f85 | /Mafia/src/mafiaserver/Participant.java | b0af5ce2adc124135f31c229a53f393422189492 | [
"BSD-3-Clause"
]
| permissive | ckdrmsdl9999/Mafia | https://github.com/ckdrmsdl9999/Mafia | 771e4219cc4721e5f66a302c3ce0e5c4f2009f7e | da2bbb01ae69636d7e24f9ef41442810962fdda6 | refs/heads/master | 2021-01-25T08:23:31.493000 | 2015-05-04T21:31:49 | 2015-05-04T21:31:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mafiaserver;
import java.io.IOException;
/**
* Participant.java Contains the Participant class
*
* @author Cory Gehr (cmg5573)
*/
abstract class Participant {
protected boolean isAlive = true; // Tells if user is alive/active
protected String username = "(UNKNOWN)"; // Username
private boolean canTalk = true; // Tells if user can chat
private boolean canVote = false; // Tells if user can vote
private boolean canSeeChat = true; // Tells if user can see chats
private Role role = null;
/**
* getUsername() Gets the participant's username
*
* @return Username of this Participant
*/
public String getUsername() {
return this.username;
}
/**
* getRole() Gets the participant's role
*
* @return Role
*/
public Role getRole() {
return this.role;
}
/**
* setRole() Sets the participant's role
*
* @return Role
*/
public void setRole(Role r) {
this.role = r;
}
/**
* hasRole() Tells if the user has an assigned role
*
* @returns True if Yes, False if No
*/
public boolean hasRole() {
return (this.role != null);
}
/**
* canSeeChat() Tells if the user can receive chat messages
*
* @returns True if Yes, False if No
*/
public boolean canSeeChat() {
return this.canSeeChat || !this.isAlive;
}
/**
* canTalk() Tells if the user can send messages
*
* @returns True if Yes, False if No
*/
public boolean canTalk() {
return this.canTalk && this.isAlive;
}
/**
* canVote() Tells if the user can vote
*
* @returns True if Yes, False if No
*/
public boolean canVote() {
return this.canVote && this.isAlive;
}
/**
* changeSeeChatStatus() Changes the user's ability to receive chats
*
* @param status True if they can see chats, False if not
*/
public void changeSeeChatStatus(boolean status) {
this.canSeeChat = status;
}
/**
* changeTalkStatus() Changes the user's ability to talk
*
* @param status True if they can talk, False if not
*/
public void changeTalkStatus(boolean status) {
this.canTalk = status;
}
/**
* changeVoteStatus() Changes the user's ability to vote
*
* @param status True if they can vote, False if not
*/
public void changeVoteStatus(boolean status) {
this.canVote = status;
}
/**
* deactivate() Deactivates the user
*/
public void deactivate() {
this.isAlive = false;
}
/**
* isAlive() Tells if the user is alive
*
* @returns True if Yes, False if No
*/
public boolean isAlive() {
return this.isAlive;
}
/**
* notifyOfRole() Prints the user's their role
*/
public void notifyOfRole() {
if (this.hasRole()) {
this.pushOutput("Your role is " + this.role.getName() + ".\n");
} else {
this.pushOutput("You have not yet been assigned a role.\n");
}
}
/**
* disconnect() Disconnects the client
*/
abstract public void disconnect();
/**
* isConnected()
* Returns true if the client is still connected
* @return True if Yes, False if No
*/
abstract public boolean isConnected();
/**
* getInput() Gets data from the client
*
* @return Input from Client
* @throws IOException
*/
abstract public String getInput() throws IOException;
/**
* pushOutput() Pushes data to the client
*
* @param input Message to send
*/
abstract public void pushOutput(String input);
}
| UTF-8 | Java | 3,818 | java | Participant.java | Java | [
{
"context": ".java Contains the Participant class\n *\n * @author Cory Gehr (cmg5573)\n */\nabstract class Participant {\n\n p",
"end": 129,
"score": 0.9998043775558472,
"start": 120,
"tag": "NAME",
"value": "Cory Gehr"
},
{
"context": "ns the Participant class\n *\n * @author Cory Gehr (cmg5573)\n */\nabstract class Participant {\n\n protected ",
"end": 138,
"score": 0.9995207786560059,
"start": 131,
"tag": "USERNAME",
"value": "cmg5573"
}
]
| null | []
| package mafiaserver;
import java.io.IOException;
/**
* Participant.java Contains the Participant class
*
* @author <NAME> (cmg5573)
*/
abstract class Participant {
protected boolean isAlive = true; // Tells if user is alive/active
protected String username = "(UNKNOWN)"; // Username
private boolean canTalk = true; // Tells if user can chat
private boolean canVote = false; // Tells if user can vote
private boolean canSeeChat = true; // Tells if user can see chats
private Role role = null;
/**
* getUsername() Gets the participant's username
*
* @return Username of this Participant
*/
public String getUsername() {
return this.username;
}
/**
* getRole() Gets the participant's role
*
* @return Role
*/
public Role getRole() {
return this.role;
}
/**
* setRole() Sets the participant's role
*
* @return Role
*/
public void setRole(Role r) {
this.role = r;
}
/**
* hasRole() Tells if the user has an assigned role
*
* @returns True if Yes, False if No
*/
public boolean hasRole() {
return (this.role != null);
}
/**
* canSeeChat() Tells if the user can receive chat messages
*
* @returns True if Yes, False if No
*/
public boolean canSeeChat() {
return this.canSeeChat || !this.isAlive;
}
/**
* canTalk() Tells if the user can send messages
*
* @returns True if Yes, False if No
*/
public boolean canTalk() {
return this.canTalk && this.isAlive;
}
/**
* canVote() Tells if the user can vote
*
* @returns True if Yes, False if No
*/
public boolean canVote() {
return this.canVote && this.isAlive;
}
/**
* changeSeeChatStatus() Changes the user's ability to receive chats
*
* @param status True if they can see chats, False if not
*/
public void changeSeeChatStatus(boolean status) {
this.canSeeChat = status;
}
/**
* changeTalkStatus() Changes the user's ability to talk
*
* @param status True if they can talk, False if not
*/
public void changeTalkStatus(boolean status) {
this.canTalk = status;
}
/**
* changeVoteStatus() Changes the user's ability to vote
*
* @param status True if they can vote, False if not
*/
public void changeVoteStatus(boolean status) {
this.canVote = status;
}
/**
* deactivate() Deactivates the user
*/
public void deactivate() {
this.isAlive = false;
}
/**
* isAlive() Tells if the user is alive
*
* @returns True if Yes, False if No
*/
public boolean isAlive() {
return this.isAlive;
}
/**
* notifyOfRole() Prints the user's their role
*/
public void notifyOfRole() {
if (this.hasRole()) {
this.pushOutput("Your role is " + this.role.getName() + ".\n");
} else {
this.pushOutput("You have not yet been assigned a role.\n");
}
}
/**
* disconnect() Disconnects the client
*/
abstract public void disconnect();
/**
* isConnected()
* Returns true if the client is still connected
* @return True if Yes, False if No
*/
abstract public boolean isConnected();
/**
* getInput() Gets data from the client
*
* @return Input from Client
* @throws IOException
*/
abstract public String getInput() throws IOException;
/**
* pushOutput() Pushes data to the client
*
* @param input Message to send
*/
abstract public void pushOutput(String input);
}
| 3,815 | 0.570194 | 0.569146 | 162 | 22.567902 | 21.433756 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.228395 | false | false | 0 |
e8d8eca3ffbee95a3388b5b198669043cdd33484 | 20,804,821,609,591 | ca86237aebda883217d688b3ee9622a9967e1213 | /src/ai/heuristics/Heuristic.java | 6a04a4b8c40ab500b893927df869084df208fd45 | []
| no_license | stlevy/Tower-Defense---AI-Project | https://github.com/stlevy/Tower-Defense---AI-Project | 2042a38493cde1d50fd91874bd4426d754fe6467 | 88aafeab21393da9cdb59570c22dbf1fc6ad2aa9 | refs/heads/master | 2020-05-17T05:53:10.984000 | 2015-09-24T14:29:11 | 2015-09-24T14:29:11 | 24,802,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ai.heuristics;
import logic.Game;
import ai.nodes.AbstractState;
public interface Heuristic {
/**
* calculates the heuristic value of a node
* @param node
* @return the heuristics if this node is legal,
* returs a negetive number if the node is illegal
*/
public abstract double getHeuristicValue(AbstractState node, Game game);
} | UTF-8 | Java | 373 | java | Heuristic.java | Java | []
| null | []
| package ai.heuristics;
import logic.Game;
import ai.nodes.AbstractState;
public interface Heuristic {
/**
* calculates the heuristic value of a node
* @param node
* @return the heuristics if this node is legal,
* returs a negetive number if the node is illegal
*/
public abstract double getHeuristicValue(AbstractState node, Game game);
} | 373 | 0.707775 | 0.707775 | 16 | 21.4375 | 22.183802 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.0625 | false | false | 0 |
55c025c9e2a114b0c29ce687e07a6567285a3675 | 26,439,818,704,060 | 8ca3d0e278784ab9e5ababd363a9c44773738714 | /src/org/apollo/game/action/impl/LeatherCraftingAction.java | b9c448b8947f9bba55804b99c69a7340b7c36326 | [
"ISC"
]
| permissive | LukeSAV/ProtoScape | https://github.com/LukeSAV/ProtoScape | fa9dd5be9b24b949f08ea14cf41911bf4af5fb6a | ba6c21b3a8b36e8bd8c750a5e13dc000ef88a4fa | refs/heads/master | 2020-12-11T01:38:29.980000 | 2014-10-30T04:10:46 | 2014-10-30T04:10:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.apollo.game.action.impl;
import org.apollo.game.action.Action;
import org.apollo.game.content.skills.crafting.Crafting;
import org.apollo.game.content.skills.crafting.LeatherData;
import org.apollo.game.model.Animation;
import org.apollo.game.model.Item;
import org.apollo.game.model.Player;
import org.apollo.game.model.Skill;
/**
* LeatherCraftingAction.java
* @author The Wanderer
*/
public class LeatherCraftingAction extends Action<Player> {
Player player;
LeatherData hides;
int index;
public LeatherCraftingAction(Player player, LeatherData hides, int index) {
super(3, false, player);
this.player = player;
this.hides = hides;
this.index = index;
}
int amountMade = Crafting.amt;
int threadCount = 0;
@Override
public void execute() {
if (amountMade > 0) {
if (player.getInventory().getCount(hides.getHide()) >= hides.getHideAmount(index)) {
if (player.getInventory().contains(1734)) {
if (amountMade > 1) {
player.playAnimation(new Animation(1249));
}
player.getInventory().remove(new Item(hides.getHide(), hides.getHideAmount(index)));
player.getInventory().add(new Item(hides.getProductId(index), 1));
player.getSkillSet().addExperience(Skill.CRAFTING, hides.getExp(index));
} else {
player.sendMessage("You have ran out of thread.");
stop();
}
} else {
player.sendMessage("You have ran out of hide.");
stop();
}
}
amountMade--;
threadCount++;
if (threadCount == 4) {
threadCount = 0;
player.getInventory().remove(new Item(1734, 1));
}
if (amountMade == 0) {
stop();
}
}
@Override
public QueuePolicy getQueuePolicy() {
return QueuePolicy.NEVER;
}
@Override
public WalkablePolicy getWalkablePolicy() {
return WalkablePolicy.NON_WALKABLE;
}
}
| UTF-8 | Java | 2,176 | java | LeatherCraftingAction.java | Java | [
{
"context": "ill;\n\n/**\n * LeatherCraftingAction.java\n * @author The Wanderer\n */\npublic class LeatherCraftingAction extends Ac",
"end": 399,
"score": 0.9996470212936401,
"start": 387,
"tag": "NAME",
"value": "The Wanderer"
}
]
| null | []
| package org.apollo.game.action.impl;
import org.apollo.game.action.Action;
import org.apollo.game.content.skills.crafting.Crafting;
import org.apollo.game.content.skills.crafting.LeatherData;
import org.apollo.game.model.Animation;
import org.apollo.game.model.Item;
import org.apollo.game.model.Player;
import org.apollo.game.model.Skill;
/**
* LeatherCraftingAction.java
* @author <NAME>
*/
public class LeatherCraftingAction extends Action<Player> {
Player player;
LeatherData hides;
int index;
public LeatherCraftingAction(Player player, LeatherData hides, int index) {
super(3, false, player);
this.player = player;
this.hides = hides;
this.index = index;
}
int amountMade = Crafting.amt;
int threadCount = 0;
@Override
public void execute() {
if (amountMade > 0) {
if (player.getInventory().getCount(hides.getHide()) >= hides.getHideAmount(index)) {
if (player.getInventory().contains(1734)) {
if (amountMade > 1) {
player.playAnimation(new Animation(1249));
}
player.getInventory().remove(new Item(hides.getHide(), hides.getHideAmount(index)));
player.getInventory().add(new Item(hides.getProductId(index), 1));
player.getSkillSet().addExperience(Skill.CRAFTING, hides.getExp(index));
} else {
player.sendMessage("You have ran out of thread.");
stop();
}
} else {
player.sendMessage("You have ran out of hide.");
stop();
}
}
amountMade--;
threadCount++;
if (threadCount == 4) {
threadCount = 0;
player.getInventory().remove(new Item(1734, 1));
}
if (amountMade == 0) {
stop();
}
}
@Override
public QueuePolicy getQueuePolicy() {
return QueuePolicy.NEVER;
}
@Override
public WalkablePolicy getWalkablePolicy() {
return WalkablePolicy.NON_WALKABLE;
}
}
| 2,170 | 0.577206 | 0.567555 | 72 | 29.222221 | 24.865316 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 0 |
5bf312451a8cdbb9aa401b0f4987449d0f8cb030 | 24,799,141,192,449 | f463bbbcb41480573e62c27043cbfa844dedb777 | /module_04/_09_AOP/baitap/src/main/java/com/example/demo/controller/BookException.java | 4d1826e53204fbddb7ba5845ca106fc6773a4d9d | []
| no_license | vantjn01/C0421G1_LeVanDiep_Module1 | https://github.com/vantjn01/C0421G1_LeVanDiep_Module1 | eb7c8ffbc34b2f2a4a8f672c274adefbb6977b76 | 199f8d99ef1d92cc1879a864000980bf4749ab1b | refs/heads/master | 2023-04-21T07:35:42.144000 | 2022-02-22T03:13:06 | 2022-02-22T03:13:06 | 362,051,954 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.controller;
public class BookException extends Exception{
}
| UTF-8 | Java | 86 | java | BookException.java | Java | []
| null | []
| package com.example.demo.controller;
public class BookException extends Exception{
}
| 86 | 0.825581 | 0.825581 | 4 | 20.5 | 20.254629 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
f26e3dc609652345a82473d893768a0c8b29b3f0 | 8,478,265,479,939 | 4ca9b4e25a0925e2570b7e7b7c612dc50d91125e | /ReqSquares/src/Circles.java | a443dac2b340ff3e153bf3f3bfd94e6631cb58ad | []
| no_license | nitesis/algducking-octo-computing-machine | https://github.com/nitesis/algducking-octo-computing-machine | 82c778c940ecf3b5bc6d2a2b3e6b71509214399b | 395ae921d94f15581d48b2e8580428a26f3d7347 | refs/heads/master | 2020-05-19T12:35:44.791000 | 2016-12-21T08:48:31 | 2016-12-21T08:48:31 | 31,132,934 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Circles extends Panel{
public static void main(String[] args) {
final Frame f = new Frame();
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
f.repaint();
}
});
f.setSize(410, 450);
Panel p = new Circles();
f.add(p);
f.setVisible(true);
}
@Override
public void paint(Graphics g) {
int w = getWidth(), h = getHeight();
drawCircles(g, 2, 2, (w < h ? w : h) - 4);
}
private static final int margin = 2;
private void drawCircles(Graphics g, int x, int y, int size) {
x = x + margin;
y = y + margin;
size = size - 2 * margin;
if (size >= 4) {
g.drawOval(x, y, size, size);
drawCircles(g, x, size/4 + y, size/2);
drawCircles(g, size/2 + x, size/4 + y, size/2);
}
}
}
| UTF-8 | Java | 1,153 | java | Circles.java | Java | []
| null | []
| import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Circles extends Panel{
public static void main(String[] args) {
final Frame f = new Frame();
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
f.repaint();
}
});
f.setSize(410, 450);
Panel p = new Circles();
f.add(p);
f.setVisible(true);
}
@Override
public void paint(Graphics g) {
int w = getWidth(), h = getHeight();
drawCircles(g, 2, 2, (w < h ? w : h) - 4);
}
private static final int margin = 2;
private void drawCircles(Graphics g, int x, int y, int size) {
x = x + margin;
y = y + margin;
size = size - 2 * margin;
if (size >= 4) {
g.drawOval(x, y, size, size);
drawCircles(g, x, size/4 + y, size/2);
drawCircles(g, size/2 + x, size/4 + y, size/2);
}
}
}
| 1,153 | 0.653946 | 0.638335 | 49 | 22.530613 | 16.997122 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.428571 | false | false | 0 |
be58f1dcbde9db8f0c050ee5efeba1f4ae090ce5 | 14,362,370,674,205 | d6da8011151b158e10c94bdf57a7f4f3ba26eb61 | /src/main/java/com/wembleyleach/headfirstdesignpatterns/command/remote_control/CielingFanMediumCommand.java | 829f4c0d01f90787b6c051a8471d5d63375b0766 | []
| no_license | WemGL/head-first-design-patterns | https://github.com/WemGL/head-first-design-patterns | c0e8b95099cda2677b0545207fb797f1cc72abd9 | 4b9ce18f42d63a5dcfe2d085bdd80199dc8478b6 | refs/heads/master | 2016-09-10T05:34:29.338000 | 2016-07-04T16:14:20 | 2016-07-04T16:14:20 | 58,314,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wembleyleach.headfirstdesignpatterns.command.remote_control;
public class CielingFanMediumCommand implements Command {
private CielingFan cielingFan;
private CielingFan.Speed previousSpeed;
public CielingFanMediumCommand(CielingFan cielingFan) {
this.cielingFan = cielingFan;
}
@Override
public void execute() {
previousSpeed = cielingFan.getSpeed();
cielingFan.medium();
}
@Override
public void undo() {
switch (previousSpeed) {
case HIGH:
cielingFan.high();
break;
case MEDIUM:
cielingFan.medium();
break;
case LOW:
cielingFan.low();
break;
case OFF:
cielingFan.off();
break;
default:
cielingFan.low();
break;
}
}
}
| UTF-8 | Java | 934 | java | CielingFanMediumCommand.java | Java | [
{
"context": "package com.wembleyleach.headfirstdesignpatterns.command.remote_control;\n\n",
"end": 24,
"score": 0.7930952310562134,
"start": 13,
"tag": "USERNAME",
"value": "embleyleach"
}
]
| null | []
| package com.wembleyleach.headfirstdesignpatterns.command.remote_control;
public class CielingFanMediumCommand implements Command {
private CielingFan cielingFan;
private CielingFan.Speed previousSpeed;
public CielingFanMediumCommand(CielingFan cielingFan) {
this.cielingFan = cielingFan;
}
@Override
public void execute() {
previousSpeed = cielingFan.getSpeed();
cielingFan.medium();
}
@Override
public void undo() {
switch (previousSpeed) {
case HIGH:
cielingFan.high();
break;
case MEDIUM:
cielingFan.medium();
break;
case LOW:
cielingFan.low();
break;
case OFF:
cielingFan.off();
break;
default:
cielingFan.low();
break;
}
}
}
| 934 | 0.53212 | 0.53212 | 37 | 24.243244 | 17.042721 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432432 | false | false | 0 |
3ecd6e3be0abc6c0cd94d6c5df025b4ab5dcd9b7 | 22,634,477,655,985 | b91340a2e63cff90265407aad286f0da7f081764 | /src/main/java/StepDefinitions/stepDefinition1.java | 541cc5a4c337d6c3526a72523035a8ee0d8450d6 | []
| no_license | Rustem-Erdem/Cucumber | https://github.com/Rustem-Erdem/Cucumber | 23fcf33d65ef8fee12d36caae5575a6a655e5495 | 5a735f4b85ba6837c7a3aa1f6a0bb4ee5117fa57 | refs/heads/master | 2023-07-24T15:59:48.241000 | 2021-09-07T00:10:57 | 2021-09-07T00:10:57 | 403,789,365 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package StepDefinitions;
import PageObjectModel.registerClass;
import Utils.Driver;
import io.cucumber.java.After;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
@RunWith(Cucumber.class)
public class stepDefinition1 {
registerClass registerClass = new registerClass();
private WebDriver driver;
@Given("^Navigate to Website$")
public void navigate_to_website() throws Throwable {
driver = Driver.getDriver();
driver.manage().window().maximize();
driver.get("http://automationpractice.com/index.php");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@And("^Click on sign button$")
public void click_on_sign_button() throws Throwable {
registerClass.setSignbutton();
Thread.sleep(2000);
}
@And("^type email \"([^\"]*)\"$")
public void type_email_something(String email) throws Throwable {
registerClass.setEmail(email);
Thread.sleep(2000);
}
@And("^Click on Create Account Button$")
public void click_on_create_account_button() throws Throwable {
registerClass.setClickCreateButton();
Thread.sleep(2000);
}
@And("^Type Firstname\"([^\"]*)\" and Lastname \"([^\"]*)\"$")
public void type_firstnamesomething_and_lastname_something(String firstname, String lastname) throws Throwable {
registerClass.setName(firstname, lastname);
Thread.sleep(2000);
}
@And("^Type Password \"([^\"]*)\"$")
public void type_password_something(String password) throws Throwable {
registerClass.setPassword(password);
Thread.sleep(2000);
}
@And("^Type Address \"([^\"]*)\"$")
public void type_address_something(String address) throws Throwable {
registerClass.setAddress(address);
Thread.sleep(2000);
}
@And("^Type Company \"([^\"]*)\"$")
public void type_company_something(String company) throws Throwable {
registerClass.setCompany(company);
Thread.sleep(2000);
}
@After
public void quitDriver() throws InterruptedException {
Thread.sleep(2000);
Driver.closeDriver();
}
}
| UTF-8 | Java | 2,325 | java | stepDefinition1.java | Java | []
| null | []
| package StepDefinitions;
import PageObjectModel.registerClass;
import Utils.Driver;
import io.cucumber.java.After;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
@RunWith(Cucumber.class)
public class stepDefinition1 {
registerClass registerClass = new registerClass();
private WebDriver driver;
@Given("^Navigate to Website$")
public void navigate_to_website() throws Throwable {
driver = Driver.getDriver();
driver.manage().window().maximize();
driver.get("http://automationpractice.com/index.php");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@And("^Click on sign button$")
public void click_on_sign_button() throws Throwable {
registerClass.setSignbutton();
Thread.sleep(2000);
}
@And("^type email \"([^\"]*)\"$")
public void type_email_something(String email) throws Throwable {
registerClass.setEmail(email);
Thread.sleep(2000);
}
@And("^Click on Create Account Button$")
public void click_on_create_account_button() throws Throwable {
registerClass.setClickCreateButton();
Thread.sleep(2000);
}
@And("^Type Firstname\"([^\"]*)\" and Lastname \"([^\"]*)\"$")
public void type_firstnamesomething_and_lastname_something(String firstname, String lastname) throws Throwable {
registerClass.setName(firstname, lastname);
Thread.sleep(2000);
}
@And("^Type Password \"([^\"]*)\"$")
public void type_password_something(String password) throws Throwable {
registerClass.setPassword(password);
Thread.sleep(2000);
}
@And("^Type Address \"([^\"]*)\"$")
public void type_address_something(String address) throws Throwable {
registerClass.setAddress(address);
Thread.sleep(2000);
}
@And("^Type Company \"([^\"]*)\"$")
public void type_company_something(String company) throws Throwable {
registerClass.setCompany(company);
Thread.sleep(2000);
}
@After
public void quitDriver() throws InterruptedException {
Thread.sleep(2000);
Driver.closeDriver();
}
}
| 2,325 | 0.660645 | 0.645591 | 79 | 28.417721 | 24.470911 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.443038 | false | false | 0 |
caa6a4b05efdcebdd5615b132440458589a27ec9 | 824,633,757,490 | 4fbac274f026d6b62342022a40b7aa5397f00fc8 | /src/main/java/net/adamsmolnik/handler/PhotoKeyEntity.java | a566cd813291fcc7043f6a6542a84841e6a62adb | []
| no_license | smolnik/photo-collection-handlers | https://github.com/smolnik/photo-collection-handlers | a209fb0fb5d0a02f1c5795e6b27137257805eab5 | 001cfd1d4c7f2df6358c096bdc22bc9bf4ae450f | refs/heads/master | 2021-06-02T21:36:15.871000 | 2018-08-01T13:10:50 | 2018-08-01T13:10:50 | 39,724,454 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.adamsmolnik.handler;
/**
* @author asmolnik
*
*/
public class PhotoKeyEntity {
private String bucket, key;
public PhotoKeyEntity(String bucket, String key) {
this.bucket = bucket;
this.key = key;
}
public PhotoKeyEntity() {
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String toString() {
return "PhotoKeyEntity [bucket=" + bucket + ", key=" + key + "]";
}
}
| UTF-8 | Java | 628 | java | PhotoKeyEntity.java | Java | [
{
"context": "ackage net.adamsmolnik.handler;\r\n\r\n/**\r\n * @author asmolnik\r\n *\r\n */\r\npublic class PhotoKeyEntity {\r\n\r\n\tpriva",
"end": 60,
"score": 0.9994251132011414,
"start": 52,
"tag": "USERNAME",
"value": "asmolnik"
}
]
| null | []
| package net.adamsmolnik.handler;
/**
* @author asmolnik
*
*/
public class PhotoKeyEntity {
private String bucket, key;
public PhotoKeyEntity(String bucket, String key) {
this.bucket = bucket;
this.key = key;
}
public PhotoKeyEntity() {
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String toString() {
return "PhotoKeyEntity [bucket=" + bucket + ", key=" + key + "]";
}
}
| 628 | 0.611465 | 0.611465 | 41 | 13.317073 | 15.976261 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.02439 | false | false | 0 |
527581585b1bc05afb1a91d237f9a28ad7ab0873 | 22,874,995,830,114 | 0190a4fafae9f2aa1069805c9ca8ff6890fe5bdb | /src/main/java/com/vsm/devcase/model/Produto.java | f81771fcab6613b80addb281bebc0130977cae42 | []
| no_license | eckelp/devcase-backend | https://github.com/eckelp/devcase-backend | f2655c0b92ed67ab3b417781367b01c8f406764e | dd52be18df2094977e7e987cd26c47fbb003d8fc | refs/heads/master | 2020-05-16T21:41:33.262000 | 2019-05-04T01:36:56 | 2019-05-04T01:36:56 | 183,312,092 | 0 | 0 | null | true | 2019-04-24T21:53:03 | 2019-04-24T21:53:03 | 2019-03-12T14:15:04 | 2019-03-12T14:15:02 | 23 | 0 | 0 | 0 | null | false | false | package com.vsm.devcase.model;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
@Entity
@Table(name = "produto")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@ApiModel(description = "Todos os detalhes sobre a produto. ")
public class Produto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Size(max = 75)
@Column(name = "descricao")
private String descricao;
@Column(name = "quantidade")
private BigDecimal quantidade;
@Column(name = "preco")
private BigDecimal preco;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoria_id")
private Categoria categoria;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "unidade_medida_id")
private UnidadeMedida unidadeMedida;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public BigDecimal getQuantidade() {
return quantidade;
}
public void setQuantidade(BigDecimal quantidade) {
this.quantidade = quantidade;
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public UnidadeMedida getUnidadeMedida() {
return unidadeMedida;
}
public void setUnidadeMedida(UnidadeMedida unidadeMedida) {
this.unidadeMedida = unidadeMedida;
}
@Override
public String toString() {
return "Produto [id=" + id + ", descricao=" + descricao + ", quantidade=" + quantidade + ", preco=" + preco
+ ", categoria=" + categoria + ", unidadeMedida=" + unidadeMedida + "]";
}
}
| UTF-8 | Java | 2,282 | java | Produto.java | Java | []
| null | []
| package com.vsm.devcase.model;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
@Entity
@Table(name = "produto")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@ApiModel(description = "Todos os detalhes sobre a produto. ")
public class Produto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Size(max = 75)
@Column(name = "descricao")
private String descricao;
@Column(name = "quantidade")
private BigDecimal quantidade;
@Column(name = "preco")
private BigDecimal preco;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoria_id")
private Categoria categoria;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "unidade_medida_id")
private UnidadeMedida unidadeMedida;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public BigDecimal getQuantidade() {
return quantidade;
}
public void setQuantidade(BigDecimal quantidade) {
this.quantidade = quantidade;
}
public BigDecimal getPreco() {
return preco;
}
public void setPreco(BigDecimal preco) {
this.preco = preco;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public UnidadeMedida getUnidadeMedida() {
return unidadeMedida;
}
public void setUnidadeMedida(UnidadeMedida unidadeMedida) {
this.unidadeMedida = unidadeMedida;
}
@Override
public String toString() {
return "Produto [id=" + id + ", descricao=" + descricao + ", quantidade=" + quantidade + ", preco=" + preco
+ ", categoria=" + categoria + ", unidadeMedida=" + unidadeMedida + "]";
}
}
| 2,282 | 0.738826 | 0.737949 | 105 | 20.733334 | 20.486124 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.161905 | false | false | 0 |
b9544757a00d19d16ccbc12eac5eae7fb533d2bb | 3,444,563,776,909 | b62d9003e17ad4a0bbb6398e1f54a132431d58b8 | /src/main/java/oreluniver/maze/level/BitmapEntranceUtil.java | b9adacae3ac3c96eabd83e1c6093212243616a57 | []
| no_license | lkmfwe/maze | https://github.com/lkmfwe/maze | 6a0a48df90bbcf226442b6b51ce92775944e33e5 | e28bc32d594a5ae810fb78357c4236874f8ec2bf | refs/heads/master | 2021-05-24T03:04:30.699000 | 2017-04-27T21:38:33 | 2017-04-27T21:38:33 | 82,948,247 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package oreluniver.maze.level;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* Class - helper for adding entrances to maze in form of bitmap
*/
public class BitmapEntranceUtil {
static boolean willOfRandom() {
return ThreadLocalRandom.current().nextInt(0, 2) != 0;
}
/**
* Adds an entrance to the given maze and registers it in the list of entrances
* @param m matrix where the entrance should be added into
* @param entrances - list of entrances
*/
public static void addEntrance(int [][] m, List<MazePos> entrances) {
if (m == null || m.length == 0 || m[0].length == 0)
return;
if (entrances.size() > 0) {
int area = getFreeArea(entrances.get(0), m[0].length, m.length);
/* Areas:
* 1 2
* 3 4 */
switch (area) {
case 1: addToFourthArea(m); break;
case 2: addToThirdArea(m); break;
case 4: addToSecondArea(m); break;
case 8: addToFirstArea(m); break;
default: addToFirstArea(m); break;
}
} else {
if (willOfRandom()) { // vertical
if (willOfRandom()) {
entrances.add(addEntranceInColumn(m, 0, 0, m.length));
}
else {
entrances.add(addEntranceInColumn(m, m[0].length -1, 0, m.length));
}
}
else { // horizontal
if (willOfRandom()) {
entrances.add(addEntranceInRow(m, 0, 0, m[0].length));
}
else {
entrances.add(addEntranceInRow(m, m.length-1, 0, m[0].length));
}
}
}
}
private static MazePos addEntranceInColumn(int [][] m, int column, int fromRow, int toRow) {
int nearDif = column == 0 ? 1 : -1;
if (fromRow == 0) {
fromRow = 1;
}
if (toRow == m.length) {
toRow--;
}
int i = fromRow;
while (i < toRow) {
if ( m[i] [column] == 0
&& m[i - 1][column] == 0
&& m[i + 1][column] == 0
&& m[i][column + nearDif] != 0
&& willOfRandom())
{
m[i][column] = 1;
return new MazePos(i, column);
}
i++;
}
i = fromRow;
while (i < toRow) {
if (m[i][column] == 0 && m[i][column + nearDif] != 0) {
m[i][column] = 1;
return new MazePos(i, column);
}
i++;
}
System.out.println(String.format("Error adding entrance to column %d, starting from row %d, ending by row %d", column, fromRow, toRow));
return null;
}
private static MazePos addEntranceInRow(int [][] m, int row, int fromCol, int toCol) {
int nearDif = row == 0 ? 1 : -1;
if (fromCol == 0) {
fromCol = 1;
}
if (toCol == m[0].length) {
toCol--;
}
int i = fromCol;
while (i < toCol) {
if ( m[row][i] == 0
&& m[row][i - 1] == 0
&& m[row][i + 1] == 0
&& m[row + nearDif][i] != 0
&& willOfRandom())
{
m[row][i] = 1;
return new MazePos(row, i);
}
i++;
}
i = fromCol;
while (i < toCol) {
if (m[row][i] == 0 && m[row + nearDif][i] != 0) {
m[row][i] = 1;
return new MazePos(row, i);
}
i++;
}
System.out.println(String.format("Error adding entrance to row %d, starting from column %d, ending by column %d", row, fromCol, toCol));
return null;
}
private static MazePos addToFirstArea(int [][] m) {
if (willOfRandom()) { // add to top row
return addEntranceInRow(m, 0, 0, m[0].length / 2);
}
else { // add to left row
return addEntranceInColumn(m, 0, 0, m.length / 2);
}
}
private static MazePos addToSecondArea(int [][] m) {
if (willOfRandom()) { // add to top col
return addEntranceInRow(m, 0, m[0].length / 2, m[0].length);
}
else { // add to right col
return addEntranceInColumn(m, m[0].length -1, 0, m.length / 2);
}
}
private static MazePos addToThirdArea(int [][] m) {
if (willOfRandom()) { // add to left third
return addEntranceInColumn(m, 0, m.length / 2, m.length);
}
else { // add to bottom third
return addEntranceInRow(m, m.length - 1, 0, m[0].length / 2);
}
}
private static MazePos addToFourthArea(int [][] m) {
if (willOfRandom()) {
// add to bottom fourth
return addEntranceInRow(m, m.length - 1, m[0].length / 2, m[0].length);
}
else {
// add to right fourth
return addEntranceInColumn(m, m[0].length - 1, m.length / 2, m.length);
}
}
private static int getFreeArea(MazePos entrance, int w, int h) {
if ( (entrance.row == 0 && entrance.col < w / 2)
|| (entrance.col == 0 && entrance.row < h / 2))
{ // row is ocupied, 4-th is free
return 1;
}
if ((entrance.row == 0 && entrance.col >= w / 2)
|| (entrance.col == w - 1 && entrance.row < h / 2))
{ // col is occupied, third is free
return 2;
}
if ((entrance.col == 0 && entrance.row >= h / 2)
|| (entrance.row == h - 1 && entrance.col < w / 2))
{ // third is occupied, col is free
return 4;
}
// if ((entrance.row == h -1 && entrnacce.col >= w / 2)
// || (entrnacce.col == w -1 && entrnacce.row >= h / 2))
// {
// return 8
// }
// 4-th is occupied, row is free
return 8;
}
}
| UTF-8 | Java | 6,117 | java | BitmapEntranceUtil.java | Java | []
| null | []
| package oreluniver.maze.level;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* Class - helper for adding entrances to maze in form of bitmap
*/
public class BitmapEntranceUtil {
static boolean willOfRandom() {
return ThreadLocalRandom.current().nextInt(0, 2) != 0;
}
/**
* Adds an entrance to the given maze and registers it in the list of entrances
* @param m matrix where the entrance should be added into
* @param entrances - list of entrances
*/
public static void addEntrance(int [][] m, List<MazePos> entrances) {
if (m == null || m.length == 0 || m[0].length == 0)
return;
if (entrances.size() > 0) {
int area = getFreeArea(entrances.get(0), m[0].length, m.length);
/* Areas:
* 1 2
* 3 4 */
switch (area) {
case 1: addToFourthArea(m); break;
case 2: addToThirdArea(m); break;
case 4: addToSecondArea(m); break;
case 8: addToFirstArea(m); break;
default: addToFirstArea(m); break;
}
} else {
if (willOfRandom()) { // vertical
if (willOfRandom()) {
entrances.add(addEntranceInColumn(m, 0, 0, m.length));
}
else {
entrances.add(addEntranceInColumn(m, m[0].length -1, 0, m.length));
}
}
else { // horizontal
if (willOfRandom()) {
entrances.add(addEntranceInRow(m, 0, 0, m[0].length));
}
else {
entrances.add(addEntranceInRow(m, m.length-1, 0, m[0].length));
}
}
}
}
private static MazePos addEntranceInColumn(int [][] m, int column, int fromRow, int toRow) {
int nearDif = column == 0 ? 1 : -1;
if (fromRow == 0) {
fromRow = 1;
}
if (toRow == m.length) {
toRow--;
}
int i = fromRow;
while (i < toRow) {
if ( m[i] [column] == 0
&& m[i - 1][column] == 0
&& m[i + 1][column] == 0
&& m[i][column + nearDif] != 0
&& willOfRandom())
{
m[i][column] = 1;
return new MazePos(i, column);
}
i++;
}
i = fromRow;
while (i < toRow) {
if (m[i][column] == 0 && m[i][column + nearDif] != 0) {
m[i][column] = 1;
return new MazePos(i, column);
}
i++;
}
System.out.println(String.format("Error adding entrance to column %d, starting from row %d, ending by row %d", column, fromRow, toRow));
return null;
}
private static MazePos addEntranceInRow(int [][] m, int row, int fromCol, int toCol) {
int nearDif = row == 0 ? 1 : -1;
if (fromCol == 0) {
fromCol = 1;
}
if (toCol == m[0].length) {
toCol--;
}
int i = fromCol;
while (i < toCol) {
if ( m[row][i] == 0
&& m[row][i - 1] == 0
&& m[row][i + 1] == 0
&& m[row + nearDif][i] != 0
&& willOfRandom())
{
m[row][i] = 1;
return new MazePos(row, i);
}
i++;
}
i = fromCol;
while (i < toCol) {
if (m[row][i] == 0 && m[row + nearDif][i] != 0) {
m[row][i] = 1;
return new MazePos(row, i);
}
i++;
}
System.out.println(String.format("Error adding entrance to row %d, starting from column %d, ending by column %d", row, fromCol, toCol));
return null;
}
private static MazePos addToFirstArea(int [][] m) {
if (willOfRandom()) { // add to top row
return addEntranceInRow(m, 0, 0, m[0].length / 2);
}
else { // add to left row
return addEntranceInColumn(m, 0, 0, m.length / 2);
}
}
private static MazePos addToSecondArea(int [][] m) {
if (willOfRandom()) { // add to top col
return addEntranceInRow(m, 0, m[0].length / 2, m[0].length);
}
else { // add to right col
return addEntranceInColumn(m, m[0].length -1, 0, m.length / 2);
}
}
private static MazePos addToThirdArea(int [][] m) {
if (willOfRandom()) { // add to left third
return addEntranceInColumn(m, 0, m.length / 2, m.length);
}
else { // add to bottom third
return addEntranceInRow(m, m.length - 1, 0, m[0].length / 2);
}
}
private static MazePos addToFourthArea(int [][] m) {
if (willOfRandom()) {
// add to bottom fourth
return addEntranceInRow(m, m.length - 1, m[0].length / 2, m[0].length);
}
else {
// add to right fourth
return addEntranceInColumn(m, m[0].length - 1, m.length / 2, m.length);
}
}
private static int getFreeArea(MazePos entrance, int w, int h) {
if ( (entrance.row == 0 && entrance.col < w / 2)
|| (entrance.col == 0 && entrance.row < h / 2))
{ // row is ocupied, 4-th is free
return 1;
}
if ((entrance.row == 0 && entrance.col >= w / 2)
|| (entrance.col == w - 1 && entrance.row < h / 2))
{ // col is occupied, third is free
return 2;
}
if ((entrance.col == 0 && entrance.row >= h / 2)
|| (entrance.row == h - 1 && entrance.col < w / 2))
{ // third is occupied, col is free
return 4;
}
// if ((entrance.row == h -1 && entrnacce.col >= w / 2)
// || (entrnacce.col == w -1 && entrnacce.row >= h / 2))
// {
// return 8
// }
// 4-th is occupied, row is free
return 8;
}
}
| 6,117 | 0.456596 | 0.438614 | 192 | 30.859375 | 26.282837 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.708333 | false | false | 0 |
79b0b0c94e2da3b830459b89cfc96e643f4b5faf | 23,304,492,550,320 | cf4153b5357bd25e730d48f52181fbc096027a6e | /src/top/mymoe/pointscommands/Config.java | 43ba2a09ed27ba438f298ee21add010713714000 | []
| no_license | ginyai/PointsCommands-for-Bukkit | https://github.com/ginyai/PointsCommands-for-Bukkit | d18e27e9805d43c7dfa3c31d8bf7999b979690fc | 0988b3e13fb669a0343ef8d9cd9fab60d2ae895f | refs/heads/master | 2021-01-19T12:34:48.418000 | 2017-04-17T13:49:48 | 2017-04-20T07:49:02 | 88,037,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package top.mymoe.pointscommands;
import org.black_ixx.playerpoints.services.PointsCommand;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by ginya on 2017/4/11.
*/
public class Config {
private Plugin plugin;
private Map<String,PluginCommand> iCommands;
private FileConfiguration fileConfiguration;
private PluginCommand confirmCommand;
public Config(Plugin plugin) {
this.plugin = plugin;
iCommands = new HashMap<>();
this.fileConfiguration=plugin.getConfig();
}
public void reload() {
plugin.reloadConfig();
this.fileConfiguration=plugin.getConfig();
Map<String,PluginCommand> tempMap = new HashMap<>();
try {
Constructor<?> constructor = PluginCommand.class.getDeclaredConstructor(String.class,Plugin.class);
constructor.setAccessible(true);
for(String name:fileConfiguration.getConfigurationSection("PointsCommands").getKeys(false)){
PluginCommand command = null;
if(iCommands.containsKey(name)){
command = iCommands.get(name);
}else {
command = (PluginCommand) constructor.newInstance(new Object[]{name, plugin});
}
if(fileConfiguration.getString("PointsCommands."+name+".description")!=null)
command.setDescription(fileConfiguration.getString("PointsCommands."+name+".description"));
if(fileConfiguration.getStringList("PointsCommands."+name+".aliases")!=null)
command.setAliases(fileConfiguration.getStringList("PointsCommands."+name+".aliases"));
tempMap.put(name,command);
}
if (confirmCommand==null||(!confirmCommand.getName().equalsIgnoreCase(fileConfiguration.getString("ConfirmCommandName")))){
confirmCommand = (PluginCommand) constructor.newInstance(new Object[]{fileConfiguration.getString("ConfirmCommandName"), plugin});
}
} catch (Exception e) {
e.printStackTrace();
}
iCommands = tempMap;
}
public PointsPlugins getPointsPlugin() {
return PointsPlugins.valueOf(fileConfiguration.getString("PointsPlugin","playerpoints").toLowerCase());
}
public Map<String,PluginCommand> getICommands() {
return iCommands;
}
public String getCommandMessage(String name,String key){
return fileConfiguration.getString("PointsCommands."+name+"."+key,fileConfiguration.getString("DefaultMessages."+key,key));
}
public int getPoints(String name) {
return fileConfiguration.getInt("PointsCommands."+name+".Points",0);
}
public int getRequiredArgs(String name ){
return fileConfiguration.getInt("PointsCommands."+name+".RequiredArgs",-1);
}
public List<String> getCommandRuns(String name){
return fileConfiguration.getStringList("PointsCommands."+name+".runcmd");
}
public String getCommandPermission(String name) {
return fileConfiguration.getString("PointsCommands."+name+".Permission","");
}
public boolean isConfirmCommands() {
return fileConfiguration.getBoolean("ConfirmCommands");
}
public PluginCommand getConfirmCommand(){
return this.confirmCommand;
}
public int getConfirmTime() {
return fileConfiguration.getInt("ConfirmTime");
}
}
| UTF-8 | Java | 3,650 | java | Config.java | Java | [
{
"context": "util.Map;\nimport java.util.Set;\n\n/**\n * Created by ginya on 2017/4/11.\n */\npublic class Config {\n priva",
"end": 379,
"score": 0.9996854662895203,
"start": 374,
"tag": "USERNAME",
"value": "ginya"
}
]
| null | []
| package top.mymoe.pointscommands;
import org.black_ixx.playerpoints.services.PointsCommand;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by ginya on 2017/4/11.
*/
public class Config {
private Plugin plugin;
private Map<String,PluginCommand> iCommands;
private FileConfiguration fileConfiguration;
private PluginCommand confirmCommand;
public Config(Plugin plugin) {
this.plugin = plugin;
iCommands = new HashMap<>();
this.fileConfiguration=plugin.getConfig();
}
public void reload() {
plugin.reloadConfig();
this.fileConfiguration=plugin.getConfig();
Map<String,PluginCommand> tempMap = new HashMap<>();
try {
Constructor<?> constructor = PluginCommand.class.getDeclaredConstructor(String.class,Plugin.class);
constructor.setAccessible(true);
for(String name:fileConfiguration.getConfigurationSection("PointsCommands").getKeys(false)){
PluginCommand command = null;
if(iCommands.containsKey(name)){
command = iCommands.get(name);
}else {
command = (PluginCommand) constructor.newInstance(new Object[]{name, plugin});
}
if(fileConfiguration.getString("PointsCommands."+name+".description")!=null)
command.setDescription(fileConfiguration.getString("PointsCommands."+name+".description"));
if(fileConfiguration.getStringList("PointsCommands."+name+".aliases")!=null)
command.setAliases(fileConfiguration.getStringList("PointsCommands."+name+".aliases"));
tempMap.put(name,command);
}
if (confirmCommand==null||(!confirmCommand.getName().equalsIgnoreCase(fileConfiguration.getString("ConfirmCommandName")))){
confirmCommand = (PluginCommand) constructor.newInstance(new Object[]{fileConfiguration.getString("ConfirmCommandName"), plugin});
}
} catch (Exception e) {
e.printStackTrace();
}
iCommands = tempMap;
}
public PointsPlugins getPointsPlugin() {
return PointsPlugins.valueOf(fileConfiguration.getString("PointsPlugin","playerpoints").toLowerCase());
}
public Map<String,PluginCommand> getICommands() {
return iCommands;
}
public String getCommandMessage(String name,String key){
return fileConfiguration.getString("PointsCommands."+name+"."+key,fileConfiguration.getString("DefaultMessages."+key,key));
}
public int getPoints(String name) {
return fileConfiguration.getInt("PointsCommands."+name+".Points",0);
}
public int getRequiredArgs(String name ){
return fileConfiguration.getInt("PointsCommands."+name+".RequiredArgs",-1);
}
public List<String> getCommandRuns(String name){
return fileConfiguration.getStringList("PointsCommands."+name+".runcmd");
}
public String getCommandPermission(String name) {
return fileConfiguration.getString("PointsCommands."+name+".Permission","");
}
public boolean isConfirmCommands() {
return fileConfiguration.getBoolean("ConfirmCommands");
}
public PluginCommand getConfirmCommand(){
return this.confirmCommand;
}
public int getConfirmTime() {
return fileConfiguration.getInt("ConfirmTime");
}
}
| 3,650 | 0.672055 | 0.669589 | 95 | 37.421051 | 35.105728 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 0 |
8eabbe172b88899d9ccf64aff969f89b6800d26f | 23,304,492,550,701 | bc2edde0a4132fc10f2da242bd559f9cd8ddeead | /Ejerciciospararepasar/src/es/ejercicios/iaw/repasomios/Ejercicio21.java | 9eeff6dd6e24287dd82af949729ce79842b2a3a9 | []
| no_license | Sergiobelmo99/IAW | https://github.com/Sergiobelmo99/IAW | 795830f90b364497c9c4bd929f7b0d24db4c30c2 | e47d24788d6e62aa856cd08ae9e40152283d898c | refs/heads/master | 2023-02-13T06:57:49.125000 | 2021-01-11T21:03:55 | 2021-01-11T21:03:55 | 300,264,897 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.ejercicios.iaw.repasomios;
import java.util.Scanner;
public class Ejercicio21 {
/*
* Pida 10 números, y muestre al final si se ha introducido algún negativo.
*/
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int numero;
int contador=0;
for (int i = 0; i <=10; i++) {
System.out.println("Introduce 10 Números: ");
numero=sc.nextInt();
if (numero<0) {
contador++;
}
}
System.out.println("Se ha introducido: "+contador+ " números negativos");
sc.close();
}
}
| ISO-8859-1 | Java | 574 | java | Ejercicio21.java | Java | []
| null | []
| package es.ejercicios.iaw.repasomios;
import java.util.Scanner;
public class Ejercicio21 {
/*
* Pida 10 números, y muestre al final si se ha introducido algún negativo.
*/
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int numero;
int contador=0;
for (int i = 0; i <=10; i++) {
System.out.println("Introduce 10 Números: ");
numero=sc.nextInt();
if (numero<0) {
contador++;
}
}
System.out.println("Se ha introducido: "+contador+ " números negativos");
sc.close();
}
}
| 574 | 0.638596 | 0.619298 | 33 | 16.272728 | 21.170696 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.69697 | false | false | 0 |
0c884d316724c217b96b4cc8ab0b9336ae3be056 | 33,028,298,560,071 | 050d277065332adbfc56a2008df1a2d35ad69f84 | /engine/src/main/java/nl/inl/blacklab/codec/BlackLab40PostingsWriter.java | a3840e6e3bcc7c6a1bbd4450f2c449d8a886a39f | [
"Apache-2.0"
]
| permissive | INL/BlackLab | https://github.com/INL/BlackLab | d48d4cbb6e3bd0fd797c76472b272651c0fcdb42 | c27a1b0ad0425393ca7c8cf1d048bf0fad6f7bf6 | refs/heads/dev | 2023-09-02T19:14:26.371000 | 2023-08-10T09:59:58 | 2023-08-10T10:03:47 | 6,074,181 | 73 | 50 | Apache-2.0 | false | 2023-09-14T11:42:14 | 2012-10-04T10:59:42 | 2023-09-10T01:33:35 | 2023-09-14T11:42:10 | 25,314 | 87 | 52 | 73 | Java | false | false | package nl.inl.blacklab.codec;
import java.io.IOException;
import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.NormsProducer;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MappedMultiFields;
import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.ReaderSlice;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
import it.unimi.dsi.fastutil.ints.IntArrays;
import nl.inl.blacklab.analysis.PayloadUtils;
import nl.inl.blacklab.codec.TokensCodec.VALUE_PER_TOKEN_PARAMETER;
import nl.inl.blacklab.exceptions.BlackLabRuntimeException;
import nl.inl.blacklab.forwardindex.Collators;
import nl.inl.blacklab.search.BlackLabIndexIntegrated;
import nl.inl.blacklab.search.indexmetadata.MatchSensitivity;
/**
* BlackLab FieldsConsumer: writes postings information to the index,
* using a delegate and extending its functionality by also writing a forward
* index.
*
* Adapted from <a href="https://github.com/meertensinstituut/mtas/">MTAS</a>.
*/
public class BlackLab40PostingsWriter extends FieldsConsumer {
protected static final Logger logger = LogManager.getLogger(BlackLab40PostingsWriter.class);
private static final int NO_TERM = nl.inl.blacklab.forwardindex.Terms.NO_TERM;
/** The FieldsConsumer we're adapting and delegating some requests to. */
private final FieldsConsumer delegateFieldsConsumer;
/** Holds common information used for writing to index files. */
private final SegmentWriteState state;
/** Name of the postings format we've adapted. */
private final String delegatePostingsFormatName;
/**
* Instantiates a fields consumer.
*
* @param delegateFieldsConsumer FieldsConsumer to be adapted by us
* @param state holder class for common parameters used during write
* @param delegatePostingsFormatName name of the delegate postings format
* (the one our PostingsFormat class adapts)
*/
public BlackLab40PostingsWriter(FieldsConsumer delegateFieldsConsumer, SegmentWriteState state,
String delegatePostingsFormatName) {
this.delegateFieldsConsumer = delegateFieldsConsumer;
this.state = state;
this.delegatePostingsFormatName = delegatePostingsFormatName;
}
/**
* Merges in the fields from the readers in <code>mergeState</code>.
*
* Identical to {@link FieldsConsumer#merge}, essentially cancelling the delegate's
* own merge method, e.g. FieldsWriter#merge in
* {@link org.apache.lucene.codecs.perfield.PerFieldPostingsFormat}}.
*
* As suggested by the name and above comments, this seems to be related to segment merging.
* Notice the call to write() at the end of the method, writing the merged segment to disk.
*
* (not sure why this is done; presumably the overridden merge method caused problems?
* the javadoc for FieldsConsumer's version does mention that subclasses can provide more sophisticated
* merging; maybe that interferes with this FieldsConsumer's customizations?)
*/
@Override
public void merge(MergeState mergeState, NormsProducer norms) throws IOException {
final List<Fields> fields = new ArrayList<>();
final List<ReaderSlice> slices = new ArrayList<>();
int docBase = 0;
for (int readerIndex = 0; readerIndex < mergeState.fieldsProducers.length; readerIndex++) {
final FieldsProducer f = mergeState.fieldsProducers[readerIndex];
final int maxDoc = mergeState.maxDocs[readerIndex];
f.checkIntegrity();
slices.add(new ReaderSlice(docBase, maxDoc, readerIndex));
fields.add(f);
docBase += maxDoc;
}
Fields mergedFields = new MappedMultiFields(mergeState,
new MultiFields(fields.toArray(Fields.EMPTY_ARRAY),
slices.toArray(ReaderSlice.EMPTY_ARRAY)));
write(mergedFields, norms);
}
/**
* Called by Lucene to write fields, terms and postings.
*
* Seems to be called whenever a segment is written, either initially or after
* a segment merge.
*
* Delegates to the default fields consumer, but also uses the opportunity
* to write our forward index.
*
* @param fields fields to write
* @param norms norms (not used by us)
*/
@Override
public void write(Fields fields, NormsProducer norms) throws IOException {
write(state.fieldInfos, fields);
delegateFieldsConsumer.write(fields, norms);
}
/**
* Information about a Lucene field that represents a BlackLab annotation in the forward index.
* A Field's information is only valid for the segment (leafreadercontext) of the index it was read from.
* Contains offsets into files comprising the terms strings and forward index information.
* Such as where in the term strings file the strings for this field begin.
* See integrated.md
*/
public static class Field {
private final String fieldName;
protected int numberOfTerms;
protected long termOrderOffset;
protected long termIndexOffset;
protected long tokensIndexOffset;
protected Field(String fieldName) { this.fieldName = fieldName; }
/** Read our values from the file */
public Field(IndexInput file) throws IOException {
this.fieldName = file.readString();
this.numberOfTerms = file.readInt();
this.termOrderOffset = file.readLong();
this.termIndexOffset = file.readLong();
this.tokensIndexOffset = file.readLong();
}
public Field(String fieldName, int numberOfTerms, long termIndexOffset, long termOrderOffset, long tokensIndexOffset) {
this.fieldName = fieldName;
this.numberOfTerms = numberOfTerms;
this.termOrderOffset = termOrderOffset;
this.termIndexOffset = termIndexOffset;
this.tokensIndexOffset = tokensIndexOffset;
}
public String getFieldName() { return fieldName; }
public int getNumberOfTerms() { return numberOfTerms; }
public long getTermIndexOffset() { return termIndexOffset; }
public long getTermOrderOffset() { return termOrderOffset; }
public long getTokensIndexOffset() { return tokensIndexOffset; }
public void write(IndexOutput file) throws IOException {
file.writeString(getFieldName());
file.writeInt(getNumberOfTerms());
file.writeLong(getTermOrderOffset());
file.writeLong(getTermIndexOffset());
file.writeLong(getTokensIndexOffset());
}
}
private static class FieldMutable extends Field {
public FieldMutable(String fieldName) { super(fieldName); }
public void setNumberOfTerms(int number) { this.numberOfTerms = number; }
public void setTermIndexOffset(long offset) { this.termIndexOffset = offset; }
public void setTermOrderOffset(long offset) { this.termOrderOffset = offset; }
public void setTokensIndexOffset(long offset) { this.tokensIndexOffset = offset; }
}
/**
* Write our additions to the default postings (i.e. the forward index)
*
* Iterates over the term vector to build the forward index in a temporary file.
*
* Tokens are sorted by field, term, doc, then position, so not by field, doc, position as
* you might expect with a forward index. This is a temporary measure for efficiency.
*
* The second pass links all the doc+position for each term together and writes them to another
* temporary file.
*
* Finally, everything is written to the final objects file in the correct order.
*
* This method also records metadata about fields in the FieldInfo attributes.
*/
private void write(FieldInfos fieldInfos, Fields fields) {
Map<String, FieldMutable> fiFields = new HashMap<>();
try ( IndexOutput outTokensIndexFile = createOutput(BlackLab40PostingsFormat.TOKENS_INDEX_EXT);
IndexOutput outTokensFile = createOutput(BlackLab40PostingsFormat.TOKENS_EXT);
IndexOutput termIndexFile = createOutput(BlackLab40PostingsFormat.TERMINDEX_EXT);
IndexOutput termsFile = createOutput(BlackLab40PostingsFormat.TERMS_EXT);
IndexOutput termsOrderFile = createOutput(BlackLab40PostingsFormat.TERMORDER_EXT)
) {
// Write our postings extension information
// We'll keep track of doc lengths so we can preallocate our forward index structure.
Map<Integer, Integer> docLengths = new HashMap<>();
// First we write a temporary dump of the term vector, and keep track of
// where we can find term occurrences per document so we can reverse this
// file later.
// (we iterate per field & term first, because that is how Lucene's reverse
// index stores the information. What we need is per field, then per document
// (we're trying to reconstruct the document), so we will do that below.
// we use temporary files because this might take a huge amount of memory)
// (use a LinkedHashMap to maintain the same field order when we write the tokens below)
Map<String/*field*/, SortedMap<Integer/*lucene doc id*/, Map<Integer/*termID*/, Long/*filePointer*/>>> field2docTermVecFileOffsets = new LinkedHashMap<>();
try (IndexOutput outTempTermVectorFile = createOutput(BlackLab40PostingsFormat.TERMVEC_TMP_EXT)) {
// Process fields
for (String luceneField: fields) { // for each field
// If this field should get a forward index...
if (!BlackLabIndexIntegrated.isForwardIndexField(fieldInfos.fieldInfo(luceneField))) {
continue;
}
FieldMutable offsets = fiFields.computeIfAbsent(luceneField, FieldMutable::new);
// We're creating a forward index for this field.
// That also means that the payloads will include an "is-primary-value" indicator,
// so we know which value to store in the forward index (the primary value, i.e.
// the first value, to be used in concordances, sort, group, etc.).
// We must skip these indicators when working with other payload info. See PayloadUtils
// for details.
// Record starting offset of field in termindex file (written to fields file later)
offsets.setTermIndexOffset(termIndexFile.getFilePointer());
// Keep track of where to find term positions for each document
// (for reversing index)
// The map is keyed by docId and stores a list of offsets into the
// temporary termvector file where the occurrences for each term can be
// found.
Map<Integer, Map<Integer, Long>> docId2TermVecFileOffsets =
field2docTermVecFileOffsets.computeIfAbsent(luceneField, k -> new TreeMap<>());
// For each term in this field...
PostingsEnum postingsEnum = null; // we'll reuse this for efficiency
Terms terms = fields.terms(luceneField);
TermsEnum termsEnum = terms.iterator();
int termId = 0;
List<String> termsList = new ArrayList<>();
while (true) {
BytesRef term = termsEnum.next();
if (term == null)
break;
// Write the term to the terms file
String termString = term.utf8ToString();
termIndexFile.writeLong(termsFile.getFilePointer()); // where to find term string
termsFile.writeString(termString);
termsList.add(termString);
// For each document containing this term...
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.POSITIONS | PostingsEnum.PAYLOADS);
while (true) {
Integer docId = postingsEnum.nextDoc();
if (docId.equals(DocIdSetIterator.NO_MORE_DOCS))
break;
// Keep track of term positions offsets in term vector file
Map<Integer, Long> vecFileOffsetsPerTermId =
docId2TermVecFileOffsets.computeIfAbsent(docId, k -> new HashMap<>());
vecFileOffsetsPerTermId.put(termId, outTempTermVectorFile.getFilePointer());
// Go through each occurrence of term in this doc,
// gathering the positions where this term occurs as a "primary value"
// (the first value at this token position, which we will store in the
// forward index). Also determine docLength.
int nOccurrences = postingsEnum.freq();
int docLength = docLengths.getOrDefault(docId, 0);
byte[] bytesPositions = new byte[nOccurrences * Integer.BYTES];
DataOutput positions = new ByteArrayDataOutput(bytesPositions);
int numOccurrencesWritten = 0;
for (int i = 0; i < nOccurrences; i++) {
int position = postingsEnum.nextPosition();
if (position >= docLength)
docLength = position + 1;
// Is this a primary value or a secondary one?
// Primary values are e.g. the original word from the document,
// and will be stored in the forward index to be used for concordances,
// sorting and grouping. Secondary values may be synonyms or stemmed versions
// and will not be stored in the forward index.
BytesRef payload = postingsEnum.getPayload();
if (PayloadUtils.isPrimaryValue(payload)) {
// primary value; write to buffer
positions.writeInt(position);
numOccurrencesWritten++;
}
}
docLengths.put(docId, docLength);
// Write the positions where this term occurs as primary value
// (will be reversed below to get the forward index)
outTempTermVectorFile.writeInt(numOccurrencesWritten);
if (numOccurrencesWritten > 0) {
outTempTermVectorFile.writeBytes(bytesPositions, 0,
numOccurrencesWritten * Integer.BYTES);
}
}
termId++;
}
// begin writing term IDs and sort orders
Collators collators = Collators.defaultCollator();
int[] sensitivePos2TermID = getTermSortOrder(termsList, collators.get(MatchSensitivity.SENSITIVE));
int[] insensitivePos2TermID = getTermSortOrder(termsList, collators.get(MatchSensitivity.INSENSITIVE));
int[] termID2SensitivePos = invert(termsList, sensitivePos2TermID, collators.get(MatchSensitivity.SENSITIVE));
int[] termID2InsensitivePos = invert(termsList, insensitivePos2TermID, collators.get(MatchSensitivity.INSENSITIVE));
int numTerms = termsList.size();
fiFields.get(luceneField).setNumberOfTerms(numTerms);
fiFields.get(luceneField).setTermOrderOffset(termsOrderFile.getFilePointer());
// write out, specific order.
for (int i : termID2InsensitivePos) termsOrderFile.writeInt(i);
for (int i : insensitivePos2TermID) termsOrderFile.writeInt(i);
for (int i : termID2SensitivePos) termsOrderFile.writeInt(i);
for (int i : sensitivePos2TermID) termsOrderFile.writeInt(i);
}
CodecUtil.writeFooter(outTempTermVectorFile);
}
// Reverse the reverse index to create forward index
// (this time we iterate per field and per document first, then reconstruct the document by
// looking at each term's occurrences. This produces our forward index)
try (IndexInput inTermVectorFile = openInput(BlackLab40PostingsFormat.TERMVEC_TMP_EXT)) {
// For each field...
for (Entry<String, SortedMap<Integer, Map<Integer, Long>>> fieldEntry: field2docTermVecFileOffsets.entrySet()) {
String luceneField = fieldEntry.getKey();
SortedMap<Integer/*docID*/, Map<Integer/*termID*/, Long/*file offset*/>> docPosOffsets = fieldEntry.getValue();
// Record starting offset of field in tokensindex file (written to fields file later)
fiFields.get(luceneField).setTokensIndexOffset(outTokensIndexFile.getFilePointer());
// For each document...
for (int docId = 0; docId < state.segmentInfo.maxDoc(); docId++) {
int[] termIds = getDocumentContents(docId, docLengths, inTermVectorFile, docPosOffsets);
writeTokensInDoc(outTokensIndexFile, outTokensFile, termIds);
}
}
} finally {
// Clean up after ourselves
deleteIndexFile(BlackLab40PostingsFormat.TERMVEC_TMP_EXT);
}
// Write fields file, now that we know all the relevant offsets
try (IndexOutput fieldsFile = createOutput(BlackLab40PostingsFormat.FIELDS_EXT)) {
// for each field that has a forward index...
for (Field field : fiFields.values()) {
// write the information to fields file, see integrated.md
field.write(fieldsFile);
}
CodecUtil.writeFooter(fieldsFile);
}
CodecUtil.writeFooter(outTokensIndexFile);
CodecUtil.writeFooter(outTokensFile);
CodecUtil.writeFooter(termIndexFile);
CodecUtil.writeFooter(termsFile);
CodecUtil.writeFooter(termsOrderFile);
} catch (IOException e) {
throw new BlackLabRuntimeException(e);
}
}
private int[] getDocumentContents(int docId, Map<Integer, Integer> docLengths,
IndexInput inTermVectorFile, SortedMap<Integer, Map<Integer, Long>> docPosOffsets)
throws IOException {
final Map<Integer/*term ID*/, Long/*file offset*/> termPosOffsets = docPosOffsets.getOrDefault(docId, Collections.emptyMap());
final int docLength = docLengths.getOrDefault(docId, 0);
final int[] tokensInDoc = new int[docLength]; // reconstruct the document here
// NOTE: sometimes docs won't have any values for a field, but we'll
// still write all NO_TERMs in this case. This is similar to sparse
// fields (e.g. the field that stores <p> <s> etc.) which also have a
// lot of NO_TERMs.
Arrays.fill(tokensInDoc, NO_TERM);
// For each term...
for (Entry<Integer/*term ID*/, Long/*file offset*/> e: termPosOffsets.entrySet()) {
int termId = e.getKey();
inTermVectorFile.seek(e.getValue());
int nOccurrences = inTermVectorFile.readInt();
// For each occurrence...
for (int i = 0; i < nOccurrences; i++) {
int position = inTermVectorFile.readInt();
tokensInDoc[position] = termId;
}
}
return tokensInDoc;
}
/**
* Write the tokens to the tokens file.
*
* Also records offset, length and encoding in the tokens index file.
*
* Chooses the most appropriate encoding for the tokens and records this choice in
* the tokens index file.
*
* @param outTokensIndexFile token index file
* @param outTokensFile tokens file
* @param tokensInDoc tokens to write
* @throws IOException When failing to write
*/
private void writeTokensInDoc(IndexOutput outTokensIndexFile, IndexOutput outTokensFile, int[] tokensInDoc) throws IOException {
int max = 0, min = 0;
boolean allTheSame = tokensInDoc.length > 0; // if no tokens, then not all the same.
int last = -1;
for (int token: tokensInDoc) {
max = Math.max(max, token);
min = Math.min(min, token);
allTheSame = allTheSame && (last == -1 || last == token);
last = token;
if ((min < Short.MIN_VALUE || max > Short.MAX_VALUE) && !allTheSame) // stop if already at worst case (int per token + not all the same).
break;
}
// determine codec
TokensCodec tokensCodec = allTheSame ? TokensCodec.ALL_TOKENS_THE_SAME : TokensCodec.VALUE_PER_TOKEN;
// determine parameter byte for codec.
byte tokensCodecParameter = 0;
switch (tokensCodec) {
case ALL_TOKENS_THE_SAME: tokensCodecParameter = 0; break;
case VALUE_PER_TOKEN: {
if (min >= Byte.MIN_VALUE && max <= Byte.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.BYTE.code;
else if (min >= Short.MIN_VALUE && max <= Short.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.SHORT.code;
else if (min >= ThreeByteInt.MIN_VALUE && max <= ThreeByteInt.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.THREE_BYTES.code;
else tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.INT.code;
break;
}
default: throw new NotImplementedException("Parameter byte determination for tokens codec " + tokensCodec + " not implemented.");
}
// Write offset in the tokens file, doc length in tokens and tokens codec used
outTokensIndexFile.writeLong(outTokensFile.getFilePointer());
outTokensIndexFile.writeInt(tokensInDoc.length);
outTokensIndexFile.writeByte(tokensCodec.code);
outTokensIndexFile.writeByte(tokensCodecParameter);
if (tokensInDoc.length == 0) {
return; // done.
}
// Write the tokens
switch (tokensCodec) {
case VALUE_PER_TOKEN:
switch (VALUE_PER_TOKEN_PARAMETER.fromCode(tokensCodecParameter)) {
case BYTE:
for (int token: tokensInDoc) {
outTokensFile.writeByte((byte) token);
}
break;
case SHORT:
for (int token: tokensInDoc) {
outTokensFile.writeShort((short) token);
}
break;
case THREE_BYTES:
for (int token : tokensInDoc) {
ThreeByteInt.write((b) -> outTokensFile.writeByte(b), token);
}
break;
case INT:
for (int token: tokensInDoc) {
outTokensFile.writeInt((int) token);
}
break;
default: throw new NotImplementedException("Handling for tokens codec " + tokensCodec + " with parameter " + tokensCodecParameter + " not implemented.");
}
break;
case ALL_TOKENS_THE_SAME:
outTokensFile.writeInt(tokensInDoc[0]);
break;
}
}
private IndexOutput createOutput(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
IndexOutput output = state.directory.createOutput(fileName, state.context);
// Write standard header, with the codec name and version, segment info.
// Also write the delegate codec name (Lucene's default codec).
CodecUtil.writeIndexHeader(output, BlackLab40PostingsFormat.NAME, BlackLab40PostingsFormat.VERSION_CURRENT,
state.segmentInfo.getId(), state.segmentSuffix);
output.writeString(delegatePostingsFormatName);
return output;
}
@SuppressWarnings("SameParameterValue")
private IndexInput openInput(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
IndexInput input = state.directory.openInput(fileName, state.context);
// Read and check standard header, with codec name and version and segment info.
// Also check the delegate codec name (should be the expected version of Lucene's codec).
CodecUtil.checkIndexHeader(input, BlackLab40PostingsFormat.NAME, BlackLab40PostingsFormat.VERSION_START,
BlackLab40PostingsFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
String delegatePFN = input.readString();
if (!delegatePostingsFormatName.equals(delegatePFN))
throw new IOException("Segment file " + fileName +
" contains wrong delegate postings format name: " + delegatePFN +
" (expected " + delegatePostingsFormatName + ")");
return input;
}
@SuppressWarnings("SameParameterValue")
private void deleteIndexFile(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
state.directory.deleteFile(fileName);
}
@Override
public void close() throws IOException {
delegateFieldsConsumer.close();
}
/**
* Given a list of terms, return the indices to sort them.
* E.G: getTermSortOrder(['b','c','a']) --> [2, 0, 1]
*/
private static int[] getTermSortOrder(List<String> terms, Collator coll) {
int[] ret = new int[terms.size()];
for (int i = 0; i < ret.length; ++i) ret[i] = i;
// Collator.compare() is synchronized, so precomputing the collation keys speeds things up
CollationKey[] ck = new CollationKey[terms.size()];
for (int i = 0; i < ck.length; ++i)
ck[i] = coll.getCollationKey(terms.get(i));
IntArrays.parallelQuickSort(ret, (a, b) -> ck[a].compareTo(ck[b]));
return ret;
}
/**
* Invert the given array so the values become the indexes and vice versa.
*
* @param array array to invert
* @return inverted array
*/
private static int[] invert(List<String> terms, int[] array, Collator collator) {
int[] result = new int[array.length];
int prevSortPosition = -1;
int prevTermId = -1;
for (int i = 0; i < array.length; i++) {
int termId = array[i];
int sortPosition = i;
if (prevTermId >= 0 && collator.equals(terms.get(prevTermId), terms.get(termId))) {
// Keep the same sort position because the terms are the same
sortPosition = prevSortPosition;
} else {
// Remember the sort position in case the next term is identical
prevSortPosition = sortPosition;
}
result[termId] = sortPosition;
prevTermId = termId;
}
return result;
}
}
| UTF-8 | Java | 29,354 | java | BlackLab40PostingsWriter.java | Java | [
{
"context": "x.\n *\n * Adapted from <a href=\"https://github.com/meertensinstituut/mtas/\">MTAS</a>.\n */\npublic class BlackLab40Posti",
"end": 2082,
"score": 0.9731206893920898,
"start": 2065,
"tag": "USERNAME",
"value": "meertensinstituut"
}
]
| null | []
| package nl.inl.blacklab.codec;
import java.io.IOException;
import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.NormsProducer;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.MappedMultiFields;
import org.apache.lucene.index.MergeState;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.ReaderSlice;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
import it.unimi.dsi.fastutil.ints.IntArrays;
import nl.inl.blacklab.analysis.PayloadUtils;
import nl.inl.blacklab.codec.TokensCodec.VALUE_PER_TOKEN_PARAMETER;
import nl.inl.blacklab.exceptions.BlackLabRuntimeException;
import nl.inl.blacklab.forwardindex.Collators;
import nl.inl.blacklab.search.BlackLabIndexIntegrated;
import nl.inl.blacklab.search.indexmetadata.MatchSensitivity;
/**
* BlackLab FieldsConsumer: writes postings information to the index,
* using a delegate and extending its functionality by also writing a forward
* index.
*
* Adapted from <a href="https://github.com/meertensinstituut/mtas/">MTAS</a>.
*/
public class BlackLab40PostingsWriter extends FieldsConsumer {
protected static final Logger logger = LogManager.getLogger(BlackLab40PostingsWriter.class);
private static final int NO_TERM = nl.inl.blacklab.forwardindex.Terms.NO_TERM;
/** The FieldsConsumer we're adapting and delegating some requests to. */
private final FieldsConsumer delegateFieldsConsumer;
/** Holds common information used for writing to index files. */
private final SegmentWriteState state;
/** Name of the postings format we've adapted. */
private final String delegatePostingsFormatName;
/**
* Instantiates a fields consumer.
*
* @param delegateFieldsConsumer FieldsConsumer to be adapted by us
* @param state holder class for common parameters used during write
* @param delegatePostingsFormatName name of the delegate postings format
* (the one our PostingsFormat class adapts)
*/
public BlackLab40PostingsWriter(FieldsConsumer delegateFieldsConsumer, SegmentWriteState state,
String delegatePostingsFormatName) {
this.delegateFieldsConsumer = delegateFieldsConsumer;
this.state = state;
this.delegatePostingsFormatName = delegatePostingsFormatName;
}
/**
* Merges in the fields from the readers in <code>mergeState</code>.
*
* Identical to {@link FieldsConsumer#merge}, essentially cancelling the delegate's
* own merge method, e.g. FieldsWriter#merge in
* {@link org.apache.lucene.codecs.perfield.PerFieldPostingsFormat}}.
*
* As suggested by the name and above comments, this seems to be related to segment merging.
* Notice the call to write() at the end of the method, writing the merged segment to disk.
*
* (not sure why this is done; presumably the overridden merge method caused problems?
* the javadoc for FieldsConsumer's version does mention that subclasses can provide more sophisticated
* merging; maybe that interferes with this FieldsConsumer's customizations?)
*/
@Override
public void merge(MergeState mergeState, NormsProducer norms) throws IOException {
final List<Fields> fields = new ArrayList<>();
final List<ReaderSlice> slices = new ArrayList<>();
int docBase = 0;
for (int readerIndex = 0; readerIndex < mergeState.fieldsProducers.length; readerIndex++) {
final FieldsProducer f = mergeState.fieldsProducers[readerIndex];
final int maxDoc = mergeState.maxDocs[readerIndex];
f.checkIntegrity();
slices.add(new ReaderSlice(docBase, maxDoc, readerIndex));
fields.add(f);
docBase += maxDoc;
}
Fields mergedFields = new MappedMultiFields(mergeState,
new MultiFields(fields.toArray(Fields.EMPTY_ARRAY),
slices.toArray(ReaderSlice.EMPTY_ARRAY)));
write(mergedFields, norms);
}
/**
* Called by Lucene to write fields, terms and postings.
*
* Seems to be called whenever a segment is written, either initially or after
* a segment merge.
*
* Delegates to the default fields consumer, but also uses the opportunity
* to write our forward index.
*
* @param fields fields to write
* @param norms norms (not used by us)
*/
@Override
public void write(Fields fields, NormsProducer norms) throws IOException {
write(state.fieldInfos, fields);
delegateFieldsConsumer.write(fields, norms);
}
/**
* Information about a Lucene field that represents a BlackLab annotation in the forward index.
* A Field's information is only valid for the segment (leafreadercontext) of the index it was read from.
* Contains offsets into files comprising the terms strings and forward index information.
* Such as where in the term strings file the strings for this field begin.
* See integrated.md
*/
public static class Field {
private final String fieldName;
protected int numberOfTerms;
protected long termOrderOffset;
protected long termIndexOffset;
protected long tokensIndexOffset;
protected Field(String fieldName) { this.fieldName = fieldName; }
/** Read our values from the file */
public Field(IndexInput file) throws IOException {
this.fieldName = file.readString();
this.numberOfTerms = file.readInt();
this.termOrderOffset = file.readLong();
this.termIndexOffset = file.readLong();
this.tokensIndexOffset = file.readLong();
}
public Field(String fieldName, int numberOfTerms, long termIndexOffset, long termOrderOffset, long tokensIndexOffset) {
this.fieldName = fieldName;
this.numberOfTerms = numberOfTerms;
this.termOrderOffset = termOrderOffset;
this.termIndexOffset = termIndexOffset;
this.tokensIndexOffset = tokensIndexOffset;
}
public String getFieldName() { return fieldName; }
public int getNumberOfTerms() { return numberOfTerms; }
public long getTermIndexOffset() { return termIndexOffset; }
public long getTermOrderOffset() { return termOrderOffset; }
public long getTokensIndexOffset() { return tokensIndexOffset; }
public void write(IndexOutput file) throws IOException {
file.writeString(getFieldName());
file.writeInt(getNumberOfTerms());
file.writeLong(getTermOrderOffset());
file.writeLong(getTermIndexOffset());
file.writeLong(getTokensIndexOffset());
}
}
private static class FieldMutable extends Field {
public FieldMutable(String fieldName) { super(fieldName); }
public void setNumberOfTerms(int number) { this.numberOfTerms = number; }
public void setTermIndexOffset(long offset) { this.termIndexOffset = offset; }
public void setTermOrderOffset(long offset) { this.termOrderOffset = offset; }
public void setTokensIndexOffset(long offset) { this.tokensIndexOffset = offset; }
}
/**
* Write our additions to the default postings (i.e. the forward index)
*
* Iterates over the term vector to build the forward index in a temporary file.
*
* Tokens are sorted by field, term, doc, then position, so not by field, doc, position as
* you might expect with a forward index. This is a temporary measure for efficiency.
*
* The second pass links all the doc+position for each term together and writes them to another
* temporary file.
*
* Finally, everything is written to the final objects file in the correct order.
*
* This method also records metadata about fields in the FieldInfo attributes.
*/
private void write(FieldInfos fieldInfos, Fields fields) {
Map<String, FieldMutable> fiFields = new HashMap<>();
try ( IndexOutput outTokensIndexFile = createOutput(BlackLab40PostingsFormat.TOKENS_INDEX_EXT);
IndexOutput outTokensFile = createOutput(BlackLab40PostingsFormat.TOKENS_EXT);
IndexOutput termIndexFile = createOutput(BlackLab40PostingsFormat.TERMINDEX_EXT);
IndexOutput termsFile = createOutput(BlackLab40PostingsFormat.TERMS_EXT);
IndexOutput termsOrderFile = createOutput(BlackLab40PostingsFormat.TERMORDER_EXT)
) {
// Write our postings extension information
// We'll keep track of doc lengths so we can preallocate our forward index structure.
Map<Integer, Integer> docLengths = new HashMap<>();
// First we write a temporary dump of the term vector, and keep track of
// where we can find term occurrences per document so we can reverse this
// file later.
// (we iterate per field & term first, because that is how Lucene's reverse
// index stores the information. What we need is per field, then per document
// (we're trying to reconstruct the document), so we will do that below.
// we use temporary files because this might take a huge amount of memory)
// (use a LinkedHashMap to maintain the same field order when we write the tokens below)
Map<String/*field*/, SortedMap<Integer/*lucene doc id*/, Map<Integer/*termID*/, Long/*filePointer*/>>> field2docTermVecFileOffsets = new LinkedHashMap<>();
try (IndexOutput outTempTermVectorFile = createOutput(BlackLab40PostingsFormat.TERMVEC_TMP_EXT)) {
// Process fields
for (String luceneField: fields) { // for each field
// If this field should get a forward index...
if (!BlackLabIndexIntegrated.isForwardIndexField(fieldInfos.fieldInfo(luceneField))) {
continue;
}
FieldMutable offsets = fiFields.computeIfAbsent(luceneField, FieldMutable::new);
// We're creating a forward index for this field.
// That also means that the payloads will include an "is-primary-value" indicator,
// so we know which value to store in the forward index (the primary value, i.e.
// the first value, to be used in concordances, sort, group, etc.).
// We must skip these indicators when working with other payload info. See PayloadUtils
// for details.
// Record starting offset of field in termindex file (written to fields file later)
offsets.setTermIndexOffset(termIndexFile.getFilePointer());
// Keep track of where to find term positions for each document
// (for reversing index)
// The map is keyed by docId and stores a list of offsets into the
// temporary termvector file where the occurrences for each term can be
// found.
Map<Integer, Map<Integer, Long>> docId2TermVecFileOffsets =
field2docTermVecFileOffsets.computeIfAbsent(luceneField, k -> new TreeMap<>());
// For each term in this field...
PostingsEnum postingsEnum = null; // we'll reuse this for efficiency
Terms terms = fields.terms(luceneField);
TermsEnum termsEnum = terms.iterator();
int termId = 0;
List<String> termsList = new ArrayList<>();
while (true) {
BytesRef term = termsEnum.next();
if (term == null)
break;
// Write the term to the terms file
String termString = term.utf8ToString();
termIndexFile.writeLong(termsFile.getFilePointer()); // where to find term string
termsFile.writeString(termString);
termsList.add(termString);
// For each document containing this term...
postingsEnum = termsEnum.postings(postingsEnum, PostingsEnum.POSITIONS | PostingsEnum.PAYLOADS);
while (true) {
Integer docId = postingsEnum.nextDoc();
if (docId.equals(DocIdSetIterator.NO_MORE_DOCS))
break;
// Keep track of term positions offsets in term vector file
Map<Integer, Long> vecFileOffsetsPerTermId =
docId2TermVecFileOffsets.computeIfAbsent(docId, k -> new HashMap<>());
vecFileOffsetsPerTermId.put(termId, outTempTermVectorFile.getFilePointer());
// Go through each occurrence of term in this doc,
// gathering the positions where this term occurs as a "primary value"
// (the first value at this token position, which we will store in the
// forward index). Also determine docLength.
int nOccurrences = postingsEnum.freq();
int docLength = docLengths.getOrDefault(docId, 0);
byte[] bytesPositions = new byte[nOccurrences * Integer.BYTES];
DataOutput positions = new ByteArrayDataOutput(bytesPositions);
int numOccurrencesWritten = 0;
for (int i = 0; i < nOccurrences; i++) {
int position = postingsEnum.nextPosition();
if (position >= docLength)
docLength = position + 1;
// Is this a primary value or a secondary one?
// Primary values are e.g. the original word from the document,
// and will be stored in the forward index to be used for concordances,
// sorting and grouping. Secondary values may be synonyms or stemmed versions
// and will not be stored in the forward index.
BytesRef payload = postingsEnum.getPayload();
if (PayloadUtils.isPrimaryValue(payload)) {
// primary value; write to buffer
positions.writeInt(position);
numOccurrencesWritten++;
}
}
docLengths.put(docId, docLength);
// Write the positions where this term occurs as primary value
// (will be reversed below to get the forward index)
outTempTermVectorFile.writeInt(numOccurrencesWritten);
if (numOccurrencesWritten > 0) {
outTempTermVectorFile.writeBytes(bytesPositions, 0,
numOccurrencesWritten * Integer.BYTES);
}
}
termId++;
}
// begin writing term IDs and sort orders
Collators collators = Collators.defaultCollator();
int[] sensitivePos2TermID = getTermSortOrder(termsList, collators.get(MatchSensitivity.SENSITIVE));
int[] insensitivePos2TermID = getTermSortOrder(termsList, collators.get(MatchSensitivity.INSENSITIVE));
int[] termID2SensitivePos = invert(termsList, sensitivePos2TermID, collators.get(MatchSensitivity.SENSITIVE));
int[] termID2InsensitivePos = invert(termsList, insensitivePos2TermID, collators.get(MatchSensitivity.INSENSITIVE));
int numTerms = termsList.size();
fiFields.get(luceneField).setNumberOfTerms(numTerms);
fiFields.get(luceneField).setTermOrderOffset(termsOrderFile.getFilePointer());
// write out, specific order.
for (int i : termID2InsensitivePos) termsOrderFile.writeInt(i);
for (int i : insensitivePos2TermID) termsOrderFile.writeInt(i);
for (int i : termID2SensitivePos) termsOrderFile.writeInt(i);
for (int i : sensitivePos2TermID) termsOrderFile.writeInt(i);
}
CodecUtil.writeFooter(outTempTermVectorFile);
}
// Reverse the reverse index to create forward index
// (this time we iterate per field and per document first, then reconstruct the document by
// looking at each term's occurrences. This produces our forward index)
try (IndexInput inTermVectorFile = openInput(BlackLab40PostingsFormat.TERMVEC_TMP_EXT)) {
// For each field...
for (Entry<String, SortedMap<Integer, Map<Integer, Long>>> fieldEntry: field2docTermVecFileOffsets.entrySet()) {
String luceneField = fieldEntry.getKey();
SortedMap<Integer/*docID*/, Map<Integer/*termID*/, Long/*file offset*/>> docPosOffsets = fieldEntry.getValue();
// Record starting offset of field in tokensindex file (written to fields file later)
fiFields.get(luceneField).setTokensIndexOffset(outTokensIndexFile.getFilePointer());
// For each document...
for (int docId = 0; docId < state.segmentInfo.maxDoc(); docId++) {
int[] termIds = getDocumentContents(docId, docLengths, inTermVectorFile, docPosOffsets);
writeTokensInDoc(outTokensIndexFile, outTokensFile, termIds);
}
}
} finally {
// Clean up after ourselves
deleteIndexFile(BlackLab40PostingsFormat.TERMVEC_TMP_EXT);
}
// Write fields file, now that we know all the relevant offsets
try (IndexOutput fieldsFile = createOutput(BlackLab40PostingsFormat.FIELDS_EXT)) {
// for each field that has a forward index...
for (Field field : fiFields.values()) {
// write the information to fields file, see integrated.md
field.write(fieldsFile);
}
CodecUtil.writeFooter(fieldsFile);
}
CodecUtil.writeFooter(outTokensIndexFile);
CodecUtil.writeFooter(outTokensFile);
CodecUtil.writeFooter(termIndexFile);
CodecUtil.writeFooter(termsFile);
CodecUtil.writeFooter(termsOrderFile);
} catch (IOException e) {
throw new BlackLabRuntimeException(e);
}
}
private int[] getDocumentContents(int docId, Map<Integer, Integer> docLengths,
IndexInput inTermVectorFile, SortedMap<Integer, Map<Integer, Long>> docPosOffsets)
throws IOException {
final Map<Integer/*term ID*/, Long/*file offset*/> termPosOffsets = docPosOffsets.getOrDefault(docId, Collections.emptyMap());
final int docLength = docLengths.getOrDefault(docId, 0);
final int[] tokensInDoc = new int[docLength]; // reconstruct the document here
// NOTE: sometimes docs won't have any values for a field, but we'll
// still write all NO_TERMs in this case. This is similar to sparse
// fields (e.g. the field that stores <p> <s> etc.) which also have a
// lot of NO_TERMs.
Arrays.fill(tokensInDoc, NO_TERM);
// For each term...
for (Entry<Integer/*term ID*/, Long/*file offset*/> e: termPosOffsets.entrySet()) {
int termId = e.getKey();
inTermVectorFile.seek(e.getValue());
int nOccurrences = inTermVectorFile.readInt();
// For each occurrence...
for (int i = 0; i < nOccurrences; i++) {
int position = inTermVectorFile.readInt();
tokensInDoc[position] = termId;
}
}
return tokensInDoc;
}
/**
* Write the tokens to the tokens file.
*
* Also records offset, length and encoding in the tokens index file.
*
* Chooses the most appropriate encoding for the tokens and records this choice in
* the tokens index file.
*
* @param outTokensIndexFile token index file
* @param outTokensFile tokens file
* @param tokensInDoc tokens to write
* @throws IOException When failing to write
*/
private void writeTokensInDoc(IndexOutput outTokensIndexFile, IndexOutput outTokensFile, int[] tokensInDoc) throws IOException {
int max = 0, min = 0;
boolean allTheSame = tokensInDoc.length > 0; // if no tokens, then not all the same.
int last = -1;
for (int token: tokensInDoc) {
max = Math.max(max, token);
min = Math.min(min, token);
allTheSame = allTheSame && (last == -1 || last == token);
last = token;
if ((min < Short.MIN_VALUE || max > Short.MAX_VALUE) && !allTheSame) // stop if already at worst case (int per token + not all the same).
break;
}
// determine codec
TokensCodec tokensCodec = allTheSame ? TokensCodec.ALL_TOKENS_THE_SAME : TokensCodec.VALUE_PER_TOKEN;
// determine parameter byte for codec.
byte tokensCodecParameter = 0;
switch (tokensCodec) {
case ALL_TOKENS_THE_SAME: tokensCodecParameter = 0; break;
case VALUE_PER_TOKEN: {
if (min >= Byte.MIN_VALUE && max <= Byte.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.BYTE.code;
else if (min >= Short.MIN_VALUE && max <= Short.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.SHORT.code;
else if (min >= ThreeByteInt.MIN_VALUE && max <= ThreeByteInt.MAX_VALUE) tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.THREE_BYTES.code;
else tokensCodecParameter = VALUE_PER_TOKEN_PARAMETER.INT.code;
break;
}
default: throw new NotImplementedException("Parameter byte determination for tokens codec " + tokensCodec + " not implemented.");
}
// Write offset in the tokens file, doc length in tokens and tokens codec used
outTokensIndexFile.writeLong(outTokensFile.getFilePointer());
outTokensIndexFile.writeInt(tokensInDoc.length);
outTokensIndexFile.writeByte(tokensCodec.code);
outTokensIndexFile.writeByte(tokensCodecParameter);
if (tokensInDoc.length == 0) {
return; // done.
}
// Write the tokens
switch (tokensCodec) {
case VALUE_PER_TOKEN:
switch (VALUE_PER_TOKEN_PARAMETER.fromCode(tokensCodecParameter)) {
case BYTE:
for (int token: tokensInDoc) {
outTokensFile.writeByte((byte) token);
}
break;
case SHORT:
for (int token: tokensInDoc) {
outTokensFile.writeShort((short) token);
}
break;
case THREE_BYTES:
for (int token : tokensInDoc) {
ThreeByteInt.write((b) -> outTokensFile.writeByte(b), token);
}
break;
case INT:
for (int token: tokensInDoc) {
outTokensFile.writeInt((int) token);
}
break;
default: throw new NotImplementedException("Handling for tokens codec " + tokensCodec + " with parameter " + tokensCodecParameter + " not implemented.");
}
break;
case ALL_TOKENS_THE_SAME:
outTokensFile.writeInt(tokensInDoc[0]);
break;
}
}
private IndexOutput createOutput(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
IndexOutput output = state.directory.createOutput(fileName, state.context);
// Write standard header, with the codec name and version, segment info.
// Also write the delegate codec name (Lucene's default codec).
CodecUtil.writeIndexHeader(output, BlackLab40PostingsFormat.NAME, BlackLab40PostingsFormat.VERSION_CURRENT,
state.segmentInfo.getId(), state.segmentSuffix);
output.writeString(delegatePostingsFormatName);
return output;
}
@SuppressWarnings("SameParameterValue")
private IndexInput openInput(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
IndexInput input = state.directory.openInput(fileName, state.context);
// Read and check standard header, with codec name and version and segment info.
// Also check the delegate codec name (should be the expected version of Lucene's codec).
CodecUtil.checkIndexHeader(input, BlackLab40PostingsFormat.NAME, BlackLab40PostingsFormat.VERSION_START,
BlackLab40PostingsFormat.VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
String delegatePFN = input.readString();
if (!delegatePostingsFormatName.equals(delegatePFN))
throw new IOException("Segment file " + fileName +
" contains wrong delegate postings format name: " + delegatePFN +
" (expected " + delegatePostingsFormatName + ")");
return input;
}
@SuppressWarnings("SameParameterValue")
private void deleteIndexFile(String ext) throws IOException {
String fileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, ext);
state.directory.deleteFile(fileName);
}
@Override
public void close() throws IOException {
delegateFieldsConsumer.close();
}
/**
* Given a list of terms, return the indices to sort them.
* E.G: getTermSortOrder(['b','c','a']) --> [2, 0, 1]
*/
private static int[] getTermSortOrder(List<String> terms, Collator coll) {
int[] ret = new int[terms.size()];
for (int i = 0; i < ret.length; ++i) ret[i] = i;
// Collator.compare() is synchronized, so precomputing the collation keys speeds things up
CollationKey[] ck = new CollationKey[terms.size()];
for (int i = 0; i < ck.length; ++i)
ck[i] = coll.getCollationKey(terms.get(i));
IntArrays.parallelQuickSort(ret, (a, b) -> ck[a].compareTo(ck[b]));
return ret;
}
/**
* Invert the given array so the values become the indexes and vice versa.
*
* @param array array to invert
* @return inverted array
*/
private static int[] invert(List<String> terms, int[] array, Collator collator) {
int[] result = new int[array.length];
int prevSortPosition = -1;
int prevTermId = -1;
for (int i = 0; i < array.length; i++) {
int termId = array[i];
int sortPosition = i;
if (prevTermId >= 0 && collator.equals(terms.get(prevTermId), terms.get(termId))) {
// Keep the same sort position because the terms are the same
sortPosition = prevSortPosition;
} else {
// Remember the sort position in case the next term is identical
prevSortPosition = sortPosition;
}
result[termId] = sortPosition;
prevTermId = termId;
}
return result;
}
}
| 29,354 | 0.617769 | 0.614942 | 601 | 47.84193 | 35.527824 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.660566 | false | false | 0 |
677ca8a42a94c1d84aa5d07e73c16129dde07a42 | 11,836,929,925,934 | ef502f0ec8fd47ce1422dfda2a14bca276cb0e72 | /aletheia-kafka0.10/src/main/java/com/outbrain/aletheia/kafka/streams/AletheiaStreams.java | f1195941afebb46721e10c9331a958316c172122 | [
"Apache-2.0"
]
| permissive | isabella232/Aletheia | https://github.com/isabella232/Aletheia | fa7d0ae676095c3d9a3f0d77ed7db3bbfc4b3b13 | e0300e555938d7bb4d178a8a124522e56d361efc | refs/heads/master | 2021-10-25T03:25:49.268000 | 2019-03-17T12:48:58 | 2019-03-17T12:48:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.outbrain.aletheia.kafka.streams;
import com.google.common.base.Preconditions;
import com.outbrain.aletheia.AletheiaConfig;
import com.outbrain.aletheia.configuration.kafka.KafkaTopicEndPointTemplate;
import com.outbrain.aletheia.datum.consumption.kafka.KafkaTopicConsumptionEndPoint;
import com.outbrain.aletheia.datum.envelope.avro.DatumEnvelope;
import com.outbrain.aletheia.kafka.serialization.AletheiaKafkaEnvelopeDeserializer;
import com.outbrain.aletheia.kafka.serialization.AletheiaKafkaEnvelopeSerializer;
import com.outbrain.aletheia.kafka.serialization.AletheiaSerdes;
import com.outbrain.aletheia.kafka.serialization.SerDeListener;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.kafka.common.serialization.Serdes.serdeFrom;
/**
* An helper class for consuming Aletheia datums as Kafka Streams
*/
public class AletheiaStreams {
private final Map<String, Object> originalConfig;
private final Map<String, Object> effectiveConfig = new HashMap<>();
private final Set<String> bootstrapServers = new HashSet<>();
private final KStreamBuilder kstreamBuilder;
public AletheiaStreams(final Map<String, Object> streamsAppConfig) {
AletheiaConfig.registerEndPointTemplate(KafkaTopicEndPointTemplate.TYPE, KafkaTopicEndPointTemplate.class);
this.kstreamBuilder = new KStreamBuilder();
this.originalConfig = streamsAppConfig;
}
public <TDomainClass> KStream<String, TDomainClass> stream(final AletheiaConfig config,
final Class<TDomainClass> domainClass,
final String consumeFromEndPointId,
final String datumSerDeId) {
return stream(config, domainClass, consumeFromEndPointId, datumSerDeId, null);
}
public <TDomainClass> KStream<String, TDomainClass> stream(final AletheiaConfig config,
final Class<TDomainClass> domainClass,
final String consumeFromEndPointId,
final String datumSerDeId,
final SerDeListener<TDomainClass> serDeListener) {
final KafkaTopicConsumptionEndPoint consumptionEndPoint = getKafkaTopicConsumptionEndPoint(config, consumeFromEndPointId);
final Serde<TDomainClass> valueSerDe = AletheiaSerdes.serdeFrom(domainClass, datumSerDeId, config, serDeListener);
return kstreamBuilder.stream(Serdes.String(), valueSerDe, consumptionEndPoint.getTopicName());
}
public KStream<String, DatumEnvelope> envelopeStream(final AletheiaConfig config,
final String consumeFromEndPointId) {
final KafkaTopicConsumptionEndPoint endPoint = getKafkaTopicConsumptionEndPoint(config, consumeFromEndPointId);
final Serde<DatumEnvelope> envelopeSerde = serdeFrom(new AletheiaKafkaEnvelopeSerializer(), new AletheiaKafkaEnvelopeDeserializer());
return kstreamBuilder.stream(Serdes.String(), envelopeSerde, endPoint.getTopicName());
}
public KafkaStreams constructStreamsInstance() {
// Validate and set bootstrap servers config
if (!originalConfig.containsKey(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) {
effectiveConfig.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, getBootstrapServers());
}
// Override with original config
effectiveConfig.putAll(originalConfig);
return new KafkaStreams(kstreamBuilder, new StreamsConfig(effectiveConfig));
}
public KStreamBuilder getKStreamBuilder() {
return kstreamBuilder;
}
public Map<String, Object> getEffectiveConfig() {
return Collections.unmodifiableMap(effectiveConfig);
}
private String getBootstrapServers() {
if (bootstrapServers.size() == 0) {
// No streams created
throw new IllegalStateException("At least one stream must be created before constructing a KafkaStreams instance");
}
if (bootstrapServers.size() > 1) {
// Multiple clusters - unsupported
throw new IllegalStateException("All streams consumption end-points must reside on the same Kafka cluster");
}
return bootstrapServers.iterator().next();
}
private KafkaTopicConsumptionEndPoint getKafkaTopicConsumptionEndPoint(final AletheiaConfig config, final String consumeFromEndPointId) {
final KafkaTopicConsumptionEndPoint consumptionEndPoint = (KafkaTopicConsumptionEndPoint) config.getConsumptionEndPoint(consumeFromEndPointId);
Preconditions.checkNotNull(consumptionEndPoint, "Could not resolve consumption endpoint id: \"%s\"", consumeFromEndPointId);
bootstrapServers.add(consumptionEndPoint.getBrokers());
return consumptionEndPoint;
}
}
| UTF-8 | Java | 5,256 | java | AletheiaStreams.java | Java | []
| null | []
| package com.outbrain.aletheia.kafka.streams;
import com.google.common.base.Preconditions;
import com.outbrain.aletheia.AletheiaConfig;
import com.outbrain.aletheia.configuration.kafka.KafkaTopicEndPointTemplate;
import com.outbrain.aletheia.datum.consumption.kafka.KafkaTopicConsumptionEndPoint;
import com.outbrain.aletheia.datum.envelope.avro.DatumEnvelope;
import com.outbrain.aletheia.kafka.serialization.AletheiaKafkaEnvelopeDeserializer;
import com.outbrain.aletheia.kafka.serialization.AletheiaKafkaEnvelopeSerializer;
import com.outbrain.aletheia.kafka.serialization.AletheiaSerdes;
import com.outbrain.aletheia.kafka.serialization.SerDeListener;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KStreamBuilder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.kafka.common.serialization.Serdes.serdeFrom;
/**
* An helper class for consuming Aletheia datums as Kafka Streams
*/
public class AletheiaStreams {
private final Map<String, Object> originalConfig;
private final Map<String, Object> effectiveConfig = new HashMap<>();
private final Set<String> bootstrapServers = new HashSet<>();
private final KStreamBuilder kstreamBuilder;
public AletheiaStreams(final Map<String, Object> streamsAppConfig) {
AletheiaConfig.registerEndPointTemplate(KafkaTopicEndPointTemplate.TYPE, KafkaTopicEndPointTemplate.class);
this.kstreamBuilder = new KStreamBuilder();
this.originalConfig = streamsAppConfig;
}
public <TDomainClass> KStream<String, TDomainClass> stream(final AletheiaConfig config,
final Class<TDomainClass> domainClass,
final String consumeFromEndPointId,
final String datumSerDeId) {
return stream(config, domainClass, consumeFromEndPointId, datumSerDeId, null);
}
public <TDomainClass> KStream<String, TDomainClass> stream(final AletheiaConfig config,
final Class<TDomainClass> domainClass,
final String consumeFromEndPointId,
final String datumSerDeId,
final SerDeListener<TDomainClass> serDeListener) {
final KafkaTopicConsumptionEndPoint consumptionEndPoint = getKafkaTopicConsumptionEndPoint(config, consumeFromEndPointId);
final Serde<TDomainClass> valueSerDe = AletheiaSerdes.serdeFrom(domainClass, datumSerDeId, config, serDeListener);
return kstreamBuilder.stream(Serdes.String(), valueSerDe, consumptionEndPoint.getTopicName());
}
public KStream<String, DatumEnvelope> envelopeStream(final AletheiaConfig config,
final String consumeFromEndPointId) {
final KafkaTopicConsumptionEndPoint endPoint = getKafkaTopicConsumptionEndPoint(config, consumeFromEndPointId);
final Serde<DatumEnvelope> envelopeSerde = serdeFrom(new AletheiaKafkaEnvelopeSerializer(), new AletheiaKafkaEnvelopeDeserializer());
return kstreamBuilder.stream(Serdes.String(), envelopeSerde, endPoint.getTopicName());
}
public KafkaStreams constructStreamsInstance() {
// Validate and set bootstrap servers config
if (!originalConfig.containsKey(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG)) {
effectiveConfig.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, getBootstrapServers());
}
// Override with original config
effectiveConfig.putAll(originalConfig);
return new KafkaStreams(kstreamBuilder, new StreamsConfig(effectiveConfig));
}
public KStreamBuilder getKStreamBuilder() {
return kstreamBuilder;
}
public Map<String, Object> getEffectiveConfig() {
return Collections.unmodifiableMap(effectiveConfig);
}
private String getBootstrapServers() {
if (bootstrapServers.size() == 0) {
// No streams created
throw new IllegalStateException("At least one stream must be created before constructing a KafkaStreams instance");
}
if (bootstrapServers.size() > 1) {
// Multiple clusters - unsupported
throw new IllegalStateException("All streams consumption end-points must reside on the same Kafka cluster");
}
return bootstrapServers.iterator().next();
}
private KafkaTopicConsumptionEndPoint getKafkaTopicConsumptionEndPoint(final AletheiaConfig config, final String consumeFromEndPointId) {
final KafkaTopicConsumptionEndPoint consumptionEndPoint = (KafkaTopicConsumptionEndPoint) config.getConsumptionEndPoint(consumeFromEndPointId);
Preconditions.checkNotNull(consumptionEndPoint, "Could not resolve consumption endpoint id: \"%s\"", consumeFromEndPointId);
bootstrapServers.add(consumptionEndPoint.getBrokers());
return consumptionEndPoint;
}
}
| 5,256 | 0.731545 | 0.731164 | 112 | 45.92857 | 41.060867 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.741071 | false | false | 0 |
576dd60d7d639900e89cb9eac5c0c43f941a3a35 | 28,080,496,248,917 | fb73a18eda8a194b3fc64e9bab4a9b9d16686eaf | /app/src/main/java/com/example/hp/gall8/signup.java | 5452a809c13db9e26a35575ec953f2a6750015c6 | []
| no_license | kylekruu/javasampleapp | https://github.com/kylekruu/javasampleapp | 2a8bad767f1c54b84af5091b54ee616a67425f98 | a55516091f7474340b47fbb2da84edddbf71d6c8 | refs/heads/master | 2020-03-26T04:47:59.929000 | 2018-08-13T03:07:38 | 2018-08-13T03:07:38 | 144,523,128 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hp.gall8;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class signup extends AppCompatActivity implements View.OnClickListener {
DBHelper myDb;
Button btnAdd;
EditText email, password, cpass, name1, uname2;
String s;
EditText editTextEmail;
EditText editTextPassword;
Button buttonSignup;
ProgressBar progressBar;
private ProgressDialog progressDialog;
private DatabaseReference mDatabase;
EditText lname;
Spinner gender;
EditText getdate;
String date;
DatePickerDialog datePickerDialog;
//defining firebaseauth object
private FirebaseAuth mAuth;
SessionManagement session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// myDb = new DBHelper(this);
s = getIntent().getStringExtra("EXTRA_SESSION_ID");
session = new SessionManagement(getApplicationContext());
//uname2 = (EditText) findViewById(R.id.username);
editTextEmail = (EditText) findViewById(R.id.email);
editTextPassword = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.confirm);
name1 = (EditText) findViewById(R.id.name);
lname = (EditText) findViewById(R.id.lname);
gender = (Spinner) findViewById(R.id.spinner);
getdate = (EditText) findViewById(R.id.bDate);
buttonSignup = (Button) findViewById(R.id.create);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference("path");
buttonSignup.setOnClickListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar3);
getdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(signup.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
getdate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
ArrayAdapter<String> adapter;
List<String> list;
list = new ArrayList<String>();
list.add("Male");
list.add("Female");
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(adapter);
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError("Please enter a valid email");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Minimum length of password should be 6");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
String id = mDatabase.push().getKey();
User user = new User(id, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), s, email, password);
mDatabase.child(email.replaceAll("[-+.^:,@]","")).setValue(user);
finish();
if (s.equals("User")) {
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, MainActivity.class));
}
if (s.equals("Guardian")){
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, guardian.class));
}
if (s.equals("Psychiatrist")){
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, psych.class));
}
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
public void onClick(View view) {
//calling register method on click
registerUser();
}
} | UTF-8 | Java | 7,725 | java | signup.java | Java | []
| null | []
| package com.example.hp.gall8;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class signup extends AppCompatActivity implements View.OnClickListener {
DBHelper myDb;
Button btnAdd;
EditText email, password, cpass, name1, uname2;
String s;
EditText editTextEmail;
EditText editTextPassword;
Button buttonSignup;
ProgressBar progressBar;
private ProgressDialog progressDialog;
private DatabaseReference mDatabase;
EditText lname;
Spinner gender;
EditText getdate;
String date;
DatePickerDialog datePickerDialog;
//defining firebaseauth object
private FirebaseAuth mAuth;
SessionManagement session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
// myDb = new DBHelper(this);
s = getIntent().getStringExtra("EXTRA_SESSION_ID");
session = new SessionManagement(getApplicationContext());
//uname2 = (EditText) findViewById(R.id.username);
editTextEmail = (EditText) findViewById(R.id.email);
editTextPassword = (EditText) findViewById(R.id.password);
cpass = (EditText) findViewById(R.id.confirm);
name1 = (EditText) findViewById(R.id.name);
lname = (EditText) findViewById(R.id.lname);
gender = (Spinner) findViewById(R.id.spinner);
getdate = (EditText) findViewById(R.id.bDate);
buttonSignup = (Button) findViewById(R.id.create);
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference("path");
buttonSignup.setOnClickListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar3);
getdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(signup.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
getdate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
ArrayAdapter<String> adapter;
List<String> list;
list = new ArrayList<String>();
list.add("Male");
list.add("Female");
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(adapter);
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError("Email is required");
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError("Please enter a valid email");
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError("Password is required");
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError("Minimum length of password should be 6");
editTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
String id = mDatabase.push().getKey();
User user = new User(id, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), s, email, password);
mDatabase.child(email.replaceAll("[-+.^:,@]","")).setValue(user);
finish();
if (s.equals("User")) {
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, MainActivity.class));
}
if (s.equals("Guardian")){
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, guardian.class));
}
if (s.equals("Psychiatrist")){
session.createLoginSession(s, name1.getText().toString(),lname.getText().toString(),getdate.getText().toString(),gender.getSelectedItem().toString(), email);
startActivity(new Intent(signup.this, psych.class));
}
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
@Override
public void onClick(View view) {
//calling register method on click
registerUser();
}
} | 7,725 | 0.617476 | 0.615663 | 197 | 38.218273 | 34.214729 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.80203 | false | false | 0 |
33ddacda4a8fc188f09ca38971ffb731d6b9ecae | 27,951,647,166,360 | 23d46b8af5b8fec48c3259f395b94fd6591df580 | /src/main/java/de/perdian/apps/podcastcentral/ui/modules/library/actions/DeleteFeedsOrEpisodesActionEventHandler.java | ab6c627cc13b8fa7b8799d8c5ad5c658c043cc93 | [
"Apache-2.0"
]
| permissive | perdian/podcastcentral | https://github.com/perdian/podcastcentral | 2a9ecd7868807c7bfce4b57aeda60c6986d156ce | a8daee5a85c0bf2343654274bda1a073d09851b0 | refs/heads/master | 2023-07-22T04:57:59.483000 | 2023-07-09T18:33:27 | 2023-07-09T18:33:27 | 221,977,362 | 4 | 0 | Apache-2.0 | false | 2023-07-09T18:33:28 | 2019-11-15T18:02:30 | 2022-12-27T23:04:00 | 2023-07-09T18:33:27 | 874 | 3 | 0 | 0 | Java | false | false | /*
* Copyright 2019 Christian Seifert
*
* 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 de.perdian.apps.podcastcentral.ui.modules.library.actions;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import de.perdian.apps.podcastcentral.downloader.episodes.EpisodeDownloader;
import de.perdian.apps.podcastcentral.model.Episode;
import de.perdian.apps.podcastcentral.model.Feed;
import de.perdian.apps.podcastcentral.model.Library;
import de.perdian.apps.podcastcentral.ui.support.backgroundtasks.BackgroundTaskExecutor;
import de.perdian.apps.podcastcentral.ui.support.localization.Localization;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.Window;
public class DeleteFeedsOrEpisodesActionEventHandler implements EventHandler<ActionEvent> {
private Supplier<Window> ownerSupplier = null;
private Supplier<List<Feed>> feedsSupplier = null;
private Supplier<List<Episode>> episodesSupplier = null;
private Library library = null;
private EpisodeDownloader episodeDownloader = null;
private BackgroundTaskExecutor backgroundTaskExecutor = null;
private Localization localization = null;
public DeleteFeedsOrEpisodesActionEventHandler(Supplier<Window> ownerSupplier, Supplier<List<Feed>> feedsSupplier, Supplier<List<Episode>> episodesSupplier, Library library, EpisodeDownloader episodeDownloader, BackgroundTaskExecutor backgroundTaskExecutor, Localization localization) {
this.setOwnerSupplier(ownerSupplier);
this.setFeedsSupplier(feedsSupplier);
this.setEpisodesSupplier(episodesSupplier);
this.setLibrary(library);
this.setEpisodeDownloader(episodeDownloader);
this.setBackgroundTaskExecutor(backgroundTaskExecutor);
this.setLocalization(localization);
}
@Override
public void handle(ActionEvent event) {
List<Feed> feeds = this.getFeedsSupplier().get();
if (!feeds.isEmpty()) {
Alert confirmationAlert = new Alert(AlertType.CONFIRMATION);
confirmationAlert.initOwner(this.getOwnerSupplier().get());
confirmationAlert.setTitle(this.getLocalization().delete());
confirmationAlert.setHeaderText(null);
confirmationAlert.setContentText(this.getLocalization().reallyDeleteFeeds(feeds.size()));
confirmationAlert.getDialogPane().getScene().getStylesheets().add("META-INF/stylesheets/podcastcentral.css");
if (!ButtonType.OK.equals(confirmationAlert.showAndWait().orElse(ButtonType.CANCEL))) {
return;
}
}
this.getBackgroundTaskExecutor().execute(this.getLocalization().deletingEntries(), progress -> {
for (int i=0; i < feeds.size(); i++) {
progress.updateProgress((double)(i+1) / (double)feeds.size(), this.getLocalization().deletingFeed(feeds.get(i).getTitle().getValue()));
feeds.get(i).getEpisodes().forEach(episode -> this.getEpisodeDownloader().cancelDownload(episode));
this.getLibrary().deleteFeeds(List.of(feeds.get(i)));
}
List<Episode> remainingEpisodes = this.getEpisodesSupplier().get().stream().filter(episode -> !feeds.contains(episode.getFeed())).collect(Collectors.toList());
Map<Feed, List<Episode>> remainingEpisodesByFeed = Episode.mapByFeed(remainingEpisodes);
int feedIndex = 0;
for (Map.Entry<Feed, List<Episode>> remainingEpisodesByFeedEntry : remainingEpisodesByFeed.entrySet()) {
progress.updateProgress((double)(++feedIndex) / (double)remainingEpisodes.size(), this.getLocalization().deletingEpisodesFromFeed(remainingEpisodesByFeedEntry.getValue().size(), remainingEpisodesByFeedEntry.getKey().getTitle().getValue()));
remainingEpisodesByFeedEntry.getValue().forEach(episode -> this.getEpisodeDownloader().cancelDownload(episode));
remainingEpisodesByFeedEntry.getKey().deleteEpisodes(remainingEpisodesByFeedEntry.getValue());
}
});
}
private Supplier<Window> getOwnerSupplier() {
return this.ownerSupplier;
}
private void setOwnerSupplier(Supplier<Window> ownerSupplier) {
this.ownerSupplier = ownerSupplier;
}
private Supplier<List<Feed>> getFeedsSupplier() {
return this.feedsSupplier;
}
private void setFeedsSupplier(Supplier<List<Feed>> feedsSupplier) {
this.feedsSupplier = feedsSupplier;
}
private Supplier<List<Episode>> getEpisodesSupplier() {
return this.episodesSupplier;
}
private void setEpisodesSupplier(Supplier<List<Episode>> episodesSupplier) {
this.episodesSupplier = episodesSupplier;
}
private Library getLibrary() {
return this.library;
}
private void setLibrary(Library library) {
this.library = library;
}
private EpisodeDownloader getEpisodeDownloader() {
return this.episodeDownloader;
}
private void setEpisodeDownloader(EpisodeDownloader episodeDownloader) {
this.episodeDownloader = episodeDownloader;
}
private BackgroundTaskExecutor getBackgroundTaskExecutor() {
return this.backgroundTaskExecutor;
}
private void setBackgroundTaskExecutor(BackgroundTaskExecutor backgroundTaskExecutor) {
this.backgroundTaskExecutor = backgroundTaskExecutor;
}
private Localization getLocalization() {
return this.localization;
}
private void setLocalization(Localization localization) {
this.localization = localization;
}
}
| UTF-8 | Java | 6,284 | java | DeleteFeedsOrEpisodesActionEventHandler.java | Java | [
{
"context": "/*\n * Copyright 2019 Christian Seifert\n *\n * Licensed under the Apache License, Version ",
"end": 38,
"score": 0.9997362494468689,
"start": 21,
"tag": "NAME",
"value": "Christian Seifert"
}
]
| null | []
| /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.perdian.apps.podcastcentral.ui.modules.library.actions;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import de.perdian.apps.podcastcentral.downloader.episodes.EpisodeDownloader;
import de.perdian.apps.podcastcentral.model.Episode;
import de.perdian.apps.podcastcentral.model.Feed;
import de.perdian.apps.podcastcentral.model.Library;
import de.perdian.apps.podcastcentral.ui.support.backgroundtasks.BackgroundTaskExecutor;
import de.perdian.apps.podcastcentral.ui.support.localization.Localization;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.stage.Window;
public class DeleteFeedsOrEpisodesActionEventHandler implements EventHandler<ActionEvent> {
private Supplier<Window> ownerSupplier = null;
private Supplier<List<Feed>> feedsSupplier = null;
private Supplier<List<Episode>> episodesSupplier = null;
private Library library = null;
private EpisodeDownloader episodeDownloader = null;
private BackgroundTaskExecutor backgroundTaskExecutor = null;
private Localization localization = null;
public DeleteFeedsOrEpisodesActionEventHandler(Supplier<Window> ownerSupplier, Supplier<List<Feed>> feedsSupplier, Supplier<List<Episode>> episodesSupplier, Library library, EpisodeDownloader episodeDownloader, BackgroundTaskExecutor backgroundTaskExecutor, Localization localization) {
this.setOwnerSupplier(ownerSupplier);
this.setFeedsSupplier(feedsSupplier);
this.setEpisodesSupplier(episodesSupplier);
this.setLibrary(library);
this.setEpisodeDownloader(episodeDownloader);
this.setBackgroundTaskExecutor(backgroundTaskExecutor);
this.setLocalization(localization);
}
@Override
public void handle(ActionEvent event) {
List<Feed> feeds = this.getFeedsSupplier().get();
if (!feeds.isEmpty()) {
Alert confirmationAlert = new Alert(AlertType.CONFIRMATION);
confirmationAlert.initOwner(this.getOwnerSupplier().get());
confirmationAlert.setTitle(this.getLocalization().delete());
confirmationAlert.setHeaderText(null);
confirmationAlert.setContentText(this.getLocalization().reallyDeleteFeeds(feeds.size()));
confirmationAlert.getDialogPane().getScene().getStylesheets().add("META-INF/stylesheets/podcastcentral.css");
if (!ButtonType.OK.equals(confirmationAlert.showAndWait().orElse(ButtonType.CANCEL))) {
return;
}
}
this.getBackgroundTaskExecutor().execute(this.getLocalization().deletingEntries(), progress -> {
for (int i=0; i < feeds.size(); i++) {
progress.updateProgress((double)(i+1) / (double)feeds.size(), this.getLocalization().deletingFeed(feeds.get(i).getTitle().getValue()));
feeds.get(i).getEpisodes().forEach(episode -> this.getEpisodeDownloader().cancelDownload(episode));
this.getLibrary().deleteFeeds(List.of(feeds.get(i)));
}
List<Episode> remainingEpisodes = this.getEpisodesSupplier().get().stream().filter(episode -> !feeds.contains(episode.getFeed())).collect(Collectors.toList());
Map<Feed, List<Episode>> remainingEpisodesByFeed = Episode.mapByFeed(remainingEpisodes);
int feedIndex = 0;
for (Map.Entry<Feed, List<Episode>> remainingEpisodesByFeedEntry : remainingEpisodesByFeed.entrySet()) {
progress.updateProgress((double)(++feedIndex) / (double)remainingEpisodes.size(), this.getLocalization().deletingEpisodesFromFeed(remainingEpisodesByFeedEntry.getValue().size(), remainingEpisodesByFeedEntry.getKey().getTitle().getValue()));
remainingEpisodesByFeedEntry.getValue().forEach(episode -> this.getEpisodeDownloader().cancelDownload(episode));
remainingEpisodesByFeedEntry.getKey().deleteEpisodes(remainingEpisodesByFeedEntry.getValue());
}
});
}
private Supplier<Window> getOwnerSupplier() {
return this.ownerSupplier;
}
private void setOwnerSupplier(Supplier<Window> ownerSupplier) {
this.ownerSupplier = ownerSupplier;
}
private Supplier<List<Feed>> getFeedsSupplier() {
return this.feedsSupplier;
}
private void setFeedsSupplier(Supplier<List<Feed>> feedsSupplier) {
this.feedsSupplier = feedsSupplier;
}
private Supplier<List<Episode>> getEpisodesSupplier() {
return this.episodesSupplier;
}
private void setEpisodesSupplier(Supplier<List<Episode>> episodesSupplier) {
this.episodesSupplier = episodesSupplier;
}
private Library getLibrary() {
return this.library;
}
private void setLibrary(Library library) {
this.library = library;
}
private EpisodeDownloader getEpisodeDownloader() {
return this.episodeDownloader;
}
private void setEpisodeDownloader(EpisodeDownloader episodeDownloader) {
this.episodeDownloader = episodeDownloader;
}
private BackgroundTaskExecutor getBackgroundTaskExecutor() {
return this.backgroundTaskExecutor;
}
private void setBackgroundTaskExecutor(BackgroundTaskExecutor backgroundTaskExecutor) {
this.backgroundTaskExecutor = backgroundTaskExecutor;
}
private Localization getLocalization() {
return this.localization;
}
private void setLocalization(Localization localization) {
this.localization = localization;
}
}
| 6,273 | 0.728039 | 0.726289 | 136 | 45.205883 | 44.405239 | 290 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602941 | false | false | 0 |
6ff1e24f3359e2e06a7d5aa0005838679e69fc9a | 23,922,967,860,003 | b31120cefe3991a960833a21ed54d4e10770bc53 | /modules/org.llvm.ir/src/org/llvm/ir/impl/ProfileSummaryStatics.java | 75954ea95a6ed6a23f04029f66c97db6ca152fa4 | []
| no_license | JianpingZeng/clank | https://github.com/JianpingZeng/clank | 94581710bd89caffcdba6ecb502e4fdb0098caaa | bcdf3389cd57185995f9ee9c101a4dfd97145442 | refs/heads/master | 2020-11-30T05:36:06.401000 | 2017-10-26T14:15:27 | 2017-10-26T14:15:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This file was converted to Java from the original LLVM source file. The original
* source file follows the LLVM Release License, outlined below.
*
* ==============================================================================
* LLVM Release License
* ==============================================================================
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* Developed by:
*
* LLVM Team
*
* University of Illinois at Urbana-Champaign
*
* http://llvm.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal with
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of the LLVM Team, University of Illinois at
* Urbana-Champaign, nor the names of its contributors may be used to
* endorse or promote products derived from this Software without specific
* prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
* SOFTWARE.
*
* ==============================================================================
* Copyrights and Licenses for Third Party Software Distributed with LLVM:
* ==============================================================================
* The LLVM software contains code written by third parties. Such software will
* have its own individual LICENSE.TXT file in the directory in which it appears.
* This file will describe the copyrights, license, and restrictions which apply
* to that code.
*
* The disclaimer of warranty in the University of Illinois Open Source License
* applies to all code in the LLVM Distribution, and nothing in any of the
* other licenses gives permission to use the names of the LLVM Team or the
* University of Illinois to endorse or promote products derived from this
* Software.
*
* The following pieces of software have additional or alternate copyrights,
* licenses, and/or restrictions:
*
* Program Directory
* ------- ---------
* Autoconf llvm/autoconf
* llvm/projects/ModuleMaker/autoconf
* Google Test llvm/utils/unittest/googletest
* OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
* pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
* ARM contributions llvm/lib/Target/ARM/LICENSE.TXT
* md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
*/
package org.llvm.ir.impl;
import org.clank.java.*;
import org.clank.support.*;
import org.clank.support.aliases.*;
import static org.clank.support.Unsigned.*;
import org.llvm.adt.aliases.*;
import org.llvm.ir.*;
import static org.llvm.ir.java.IrRTTI.*;
//<editor-fold defaultstate="collapsed" desc="static type ProfileSummaryStatics">
@Converted(kind = Converted.Kind.AUTO,
NM="org.llvm.ir.impl.ProfileSummaryStatics",
cmd="jclank.sh -java-options=${SPUTNIK}/contrib/JConvert/llvmToClankType -print -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_;_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy;_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_;_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE;_ZL6getValPN4llvm7MDTupleEPKcRy; -static-type=ProfileSummaryStatics -package=org.llvm.ir.impl")
//</editor-fold>
public final class ProfileSummaryStatics {
// Return an MDTuple with two elements. The first element is a string Key and
// the second is a uint64_t Value.
//<editor-fold defaultstate="collapsed" desc="getKeyValMD">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 29,
FQN="getKeyValMD", NM="_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy")
//</editor-fold>
public static Metadata /*P*/ getKeyValMD(final LLVMContext /*&*/ Context, /*const*/char$ptr/*char P*/ Key,
long/*uint64_t*/ Val) {
Type /*P*/ Int64Ty = Type.getInt64Ty(Context);
Metadata /*P*/ Ops[/*2*/] = new Metadata /*P*/ [/*2*/] {
MDString.get(Context, Key),
ConstantAsMetadata.get(ConstantInt.get(Int64Ty, Val))};
return MDTuple.get(Context, new ArrayRef<Metadata /*P*/ >(Ops, true));
}
// Return an MDTuple with two elements. The first element is a string Key and
// the second is a string Value.
//<editor-fold defaultstate="collapsed" desc="getKeyValMD">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 39,
FQN="getKeyValMD", NM="_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_")
//</editor-fold>
public static Metadata /*P*/ getKeyValMD(final LLVMContext /*&*/ Context, /*const*/char$ptr/*char P*/ Key,
/*const*/char$ptr/*char P*/ Val) {
Metadata /*P*/ Ops[/*2*/] = new Metadata /*P*/ [/*2*/] {MDString.get(Context, Key), MDString.get(Context, Val)};
return MDTuple.get(Context, new ArrayRef<Metadata /*P*/ >(Ops, true));
}
// Parse an MDTuple representing (Key, Val) pair.
//<editor-fold defaultstate="collapsed" desc="getVal">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 88,
FQN="getVal", NM="_ZL6getValPN4llvm7MDTupleEPKcRy",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL6getValPN4llvm7MDTupleEPKcRy")
//</editor-fold>
public static boolean getVal(MDTuple /*P*/ MD, /*const*/char$ptr/*char P*/ Key, final ulong$ref/*uint64_t &*/ Val) {
if (!(MD != null)) {
return false;
}
if (MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
ConstantAsMetadata /*P*/ ValMD = dyn_cast_ConstantAsMetadata(MD.getOperand(1));
if (!(KeyMD != null) || !(ValMD != null)) {
return false;
}
if (!KeyMD.getString().equals(/*STRINGREF_STR*/Key)) {
return false;
}
Val.$set(cast_ConstantInt(ValMD.getValue()).getZExtValue());
return true;
}
// Check if an MDTuple represents a (Key, Val) pair.
//<editor-fold defaultstate="collapsed" desc="isKeyValuePair">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 104,
FQN="isKeyValuePair", NM="_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_")
//</editor-fold>
public static boolean isKeyValuePair(MDTuple /*P*/ MD, /*const*/char$ptr/*char P*/ Key, /*const*/char$ptr/*char P*/ Val) {
if (!(MD != null) || MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
MDString /*P*/ ValMD = dyn_cast_MDString(MD.getOperand(1));
if (!(KeyMD != null) || !(ValMD != null)) {
return false;
}
if (!KeyMD.getString().equals(/*STRINGREF_STR*/Key) || !ValMD.getString().equals(/*STRINGREF_STR*/Val)) {
return false;
}
return true;
}
// Parse an MDTuple representing detailed summary.
//<editor-fold defaultstate="collapsed" desc="getSummaryFromMD">
@Converted(kind = Converted.Kind.MANUAL_COMPILATION,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 117,
FQN="getSummaryFromMD", NM="_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE")
//</editor-fold>
public static boolean getSummaryFromMD(MDTuple /*P*/ MD, final std.vector<ProfileSummaryEntry> /*&*/ Summary) {
if (!(MD != null) || MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
if (!(KeyMD != null) || !KeyMD.getString().equals(/*STRINGREF_STR*/"DetailedSummary")) {
return false;
}
MDTuple /*P*/ EntriesMD = dyn_cast_MDTuple(MD.getOperand(1));
if (!(EntriesMD != null)) {
return false;
}
for (final /*const*/ MDOperand /*&*/ /*&*/ MDOp : EntriesMD.operands()) {
MDTuple /*P*/ EntryMD = dyn_cast_MDTuple(MDOp);
if (!(EntryMD != null) || EntryMD.getNumOperands() != 3) {
return false;
}
ConstantAsMetadata /*P*/ Op0 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(0));
ConstantAsMetadata /*P*/ Op1 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(1));
ConstantAsMetadata /*P*/ Op2 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(2));
if (!(Op0 != null) || !(Op1 != null) || !(Op2 != null)) {
return false;
}
Summary.emplace_back(new ProfileSummaryEntry($ulong2uint(cast_ConstantInt(Op0.getValue()).getZExtValue()),
cast_ConstantInt(Op1.getValue()).getZExtValue(),
cast_ConstantInt(Op2.getValue()).getZExtValue()));
}
return true;
}
} // END OF class ProfileSummaryStatics
| UTF-8 | Java | 10,420 | java | ProfileSummaryStatics.java | Java | []
| null | []
| /**
* This file was converted to Java from the original LLVM source file. The original
* source file follows the LLVM Release License, outlined below.
*
* ==============================================================================
* LLVM Release License
* ==============================================================================
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* Developed by:
*
* LLVM Team
*
* University of Illinois at Urbana-Champaign
*
* http://llvm.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal with
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of the LLVM Team, University of Illinois at
* Urbana-Champaign, nor the names of its contributors may be used to
* endorse or promote products derived from this Software without specific
* prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
* SOFTWARE.
*
* ==============================================================================
* Copyrights and Licenses for Third Party Software Distributed with LLVM:
* ==============================================================================
* The LLVM software contains code written by third parties. Such software will
* have its own individual LICENSE.TXT file in the directory in which it appears.
* This file will describe the copyrights, license, and restrictions which apply
* to that code.
*
* The disclaimer of warranty in the University of Illinois Open Source License
* applies to all code in the LLVM Distribution, and nothing in any of the
* other licenses gives permission to use the names of the LLVM Team or the
* University of Illinois to endorse or promote products derived from this
* Software.
*
* The following pieces of software have additional or alternate copyrights,
* licenses, and/or restrictions:
*
* Program Directory
* ------- ---------
* Autoconf llvm/autoconf
* llvm/projects/ModuleMaker/autoconf
* Google Test llvm/utils/unittest/googletest
* OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
* pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
* ARM contributions llvm/lib/Target/ARM/LICENSE.TXT
* md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
*/
package org.llvm.ir.impl;
import org.clank.java.*;
import org.clank.support.*;
import org.clank.support.aliases.*;
import static org.clank.support.Unsigned.*;
import org.llvm.adt.aliases.*;
import org.llvm.ir.*;
import static org.llvm.ir.java.IrRTTI.*;
//<editor-fold defaultstate="collapsed" desc="static type ProfileSummaryStatics">
@Converted(kind = Converted.Kind.AUTO,
NM="org.llvm.ir.impl.ProfileSummaryStatics",
cmd="jclank.sh -java-options=${SPUTNIK}/contrib/JConvert/llvmToClankType -print -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_;_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy;_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_;_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE;_ZL6getValPN4llvm7MDTupleEPKcRy; -static-type=ProfileSummaryStatics -package=org.llvm.ir.impl")
//</editor-fold>
public final class ProfileSummaryStatics {
// Return an MDTuple with two elements. The first element is a string Key and
// the second is a uint64_t Value.
//<editor-fold defaultstate="collapsed" desc="getKeyValMD">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 29,
FQN="getKeyValMD", NM="_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcy")
//</editor-fold>
public static Metadata /*P*/ getKeyValMD(final LLVMContext /*&*/ Context, /*const*/char$ptr/*char P*/ Key,
long/*uint64_t*/ Val) {
Type /*P*/ Int64Ty = Type.getInt64Ty(Context);
Metadata /*P*/ Ops[/*2*/] = new Metadata /*P*/ [/*2*/] {
MDString.get(Context, Key),
ConstantAsMetadata.get(ConstantInt.get(Int64Ty, Val))};
return MDTuple.get(Context, new ArrayRef<Metadata /*P*/ >(Ops, true));
}
// Return an MDTuple with two elements. The first element is a string Key and
// the second is a string Value.
//<editor-fold defaultstate="collapsed" desc="getKeyValMD">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 39,
FQN="getKeyValMD", NM="_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL11getKeyValMDRN4llvm11LLVMContextEPKcS3_")
//</editor-fold>
public static Metadata /*P*/ getKeyValMD(final LLVMContext /*&*/ Context, /*const*/char$ptr/*char P*/ Key,
/*const*/char$ptr/*char P*/ Val) {
Metadata /*P*/ Ops[/*2*/] = new Metadata /*P*/ [/*2*/] {MDString.get(Context, Key), MDString.get(Context, Val)};
return MDTuple.get(Context, new ArrayRef<Metadata /*P*/ >(Ops, true));
}
// Parse an MDTuple representing (Key, Val) pair.
//<editor-fold defaultstate="collapsed" desc="getVal">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 88,
FQN="getVal", NM="_ZL6getValPN4llvm7MDTupleEPKcRy",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL6getValPN4llvm7MDTupleEPKcRy")
//</editor-fold>
public static boolean getVal(MDTuple /*P*/ MD, /*const*/char$ptr/*char P*/ Key, final ulong$ref/*uint64_t &*/ Val) {
if (!(MD != null)) {
return false;
}
if (MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
ConstantAsMetadata /*P*/ ValMD = dyn_cast_ConstantAsMetadata(MD.getOperand(1));
if (!(KeyMD != null) || !(ValMD != null)) {
return false;
}
if (!KeyMD.getString().equals(/*STRINGREF_STR*/Key)) {
return false;
}
Val.$set(cast_ConstantInt(ValMD.getValue()).getZExtValue());
return true;
}
// Check if an MDTuple represents a (Key, Val) pair.
//<editor-fold defaultstate="collapsed" desc="isKeyValuePair">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 104,
FQN="isKeyValuePair", NM="_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL14isKeyValuePairPN4llvm7MDTupleEPKcS3_")
//</editor-fold>
public static boolean isKeyValuePair(MDTuple /*P*/ MD, /*const*/char$ptr/*char P*/ Key, /*const*/char$ptr/*char P*/ Val) {
if (!(MD != null) || MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
MDString /*P*/ ValMD = dyn_cast_MDString(MD.getOperand(1));
if (!(KeyMD != null) || !(ValMD != null)) {
return false;
}
if (!KeyMD.getString().equals(/*STRINGREF_STR*/Key) || !ValMD.getString().equals(/*STRINGREF_STR*/Val)) {
return false;
}
return true;
}
// Parse an MDTuple representing detailed summary.
//<editor-fold defaultstate="collapsed" desc="getSummaryFromMD">
@Converted(kind = Converted.Kind.MANUAL_COMPILATION,
source = "${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp", line = 117,
FQN="getSummaryFromMD", NM="_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.llvm.ir/llvmToClangType ${LLVM_SRC}/llvm/lib/IR/ProfileSummary.cpp -nm=_ZL16getSummaryFromMDPN4llvm7MDTupleERSt6vectorINS_19ProfileSummaryEntryESaIS3_EE")
//</editor-fold>
public static boolean getSummaryFromMD(MDTuple /*P*/ MD, final std.vector<ProfileSummaryEntry> /*&*/ Summary) {
if (!(MD != null) || MD.getNumOperands() != 2) {
return false;
}
MDString /*P*/ KeyMD = dyn_cast_MDString(MD.getOperand(0));
if (!(KeyMD != null) || !KeyMD.getString().equals(/*STRINGREF_STR*/"DetailedSummary")) {
return false;
}
MDTuple /*P*/ EntriesMD = dyn_cast_MDTuple(MD.getOperand(1));
if (!(EntriesMD != null)) {
return false;
}
for (final /*const*/ MDOperand /*&*/ /*&*/ MDOp : EntriesMD.operands()) {
MDTuple /*P*/ EntryMD = dyn_cast_MDTuple(MDOp);
if (!(EntryMD != null) || EntryMD.getNumOperands() != 3) {
return false;
}
ConstantAsMetadata /*P*/ Op0 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(0));
ConstantAsMetadata /*P*/ Op1 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(1));
ConstantAsMetadata /*P*/ Op2 = dyn_cast_ConstantAsMetadata(EntryMD.getOperand(2));
if (!(Op0 != null) || !(Op1 != null) || !(Op2 != null)) {
return false;
}
Summary.emplace_back(new ProfileSummaryEntry($ulong2uint(cast_ConstantInt(Op0.getValue()).getZExtValue()),
cast_ConstantInt(Op1.getValue()).getZExtValue(),
cast_ConstantInt(Op2.getValue()).getZExtValue()));
}
return true;
}
} // END OF class ProfileSummaryStatics
| 10,420 | 0.690979 | 0.677255 | 215 | 47.465115 | 48.513508 | 494 | false | false | 0 | 0 | 0 | 0 | 79 | 0.030326 | 0.67907 | false | false | 0 |
7b7741e427b864a622fff0ec3934b18dc78dd659 | 8,289,286,926,573 | 12a3f87ddfaffba9858ef1e1fb736201960c20f2 | /src/Procesos/Actividad26/Cuenta.java | fdd1d45adfe95135deb4197a3002308b3eb2ccc6 | []
| no_license | migueldam91/PSP | https://github.com/migueldam91/PSP | e6f5b3ae7910cbd99ffb77170e3c6ce22b94fabc | 5e197e60ba137d7d78913480894031bc436e0de6 | refs/heads/master | 2021-01-10T06:31:13.238000 | 2015-12-02T21:52:08 | 2015-12-02T21:52:08 | 44,738,805 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Procesos.Actividad26;
public class Cuenta {
private int saldo = 0;
private int maxSaldoCuenta = 3000;
private boolean flagTope = false;
public boolean isFlagTope() {
return flagTope;
}
public void setFlagTope(boolean flagTope) {
this.flagTope = flagTope;
}
public Cuenta(int saldo, int maxSaldoCuenta) {
super();
this.saldo = saldo;
this.maxSaldoCuenta = maxSaldoCuenta;
}
public int getSaldo() {
return saldo;
}
synchronized public void ingresarDinero(int dinero, int maxSaldoCuenta) {
int sumaSaldo = saldo + dinero;
if (!(sumaSaldo > maxSaldoCuenta)) {
this.saldo += dinero;
} else {
flagTope = true;
System.out.println("Lo sentimos, esta cuenta tiene un máximo de " + maxSaldoCuenta + "euros");
System.out.println("saldo " + saldo + " Suma de la operacion "+ sumaSaldo);
}
}
synchronized public void hacerReintegro(int dinero) {
if (saldo >= 0 && saldo >= dinero) {
this.saldo -= dinero;
} else {
System.out.println("No hay saldo suficiente");
flagTope = true;
}
}
public int getMaxSaldoCuenta() {
return maxSaldoCuenta;
}
public void setMaxSaldoCuenta(int maxSaldoCuenta) {
this.maxSaldoCuenta = maxSaldoCuenta;
}
public void setSaldo(int saldo) {
this.saldo = saldo;
}
}
| ISO-8859-1 | Java | 1,272 | java | Cuenta.java | Java | []
| null | []
| package Procesos.Actividad26;
public class Cuenta {
private int saldo = 0;
private int maxSaldoCuenta = 3000;
private boolean flagTope = false;
public boolean isFlagTope() {
return flagTope;
}
public void setFlagTope(boolean flagTope) {
this.flagTope = flagTope;
}
public Cuenta(int saldo, int maxSaldoCuenta) {
super();
this.saldo = saldo;
this.maxSaldoCuenta = maxSaldoCuenta;
}
public int getSaldo() {
return saldo;
}
synchronized public void ingresarDinero(int dinero, int maxSaldoCuenta) {
int sumaSaldo = saldo + dinero;
if (!(sumaSaldo > maxSaldoCuenta)) {
this.saldo += dinero;
} else {
flagTope = true;
System.out.println("Lo sentimos, esta cuenta tiene un máximo de " + maxSaldoCuenta + "euros");
System.out.println("saldo " + saldo + " Suma de la operacion "+ sumaSaldo);
}
}
synchronized public void hacerReintegro(int dinero) {
if (saldo >= 0 && saldo >= dinero) {
this.saldo -= dinero;
} else {
System.out.println("No hay saldo suficiente");
flagTope = true;
}
}
public int getMaxSaldoCuenta() {
return maxSaldoCuenta;
}
public void setMaxSaldoCuenta(int maxSaldoCuenta) {
this.maxSaldoCuenta = maxSaldoCuenta;
}
public void setSaldo(int saldo) {
this.saldo = saldo;
}
}
| 1,272 | 0.691581 | 0.685287 | 59 | 20.542374 | 21.837088 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.661017 | false | false | 0 |
b30632d91eaaf7bc661bae0affa528799aa88c87 | 19,258,633,385,859 | d83b68759a7145e21d05d6f9a91a3f4ae1deac01 | /Encryption.java | 64db1580fa73c7efbd9451a7aa37b3b5301190bc | []
| no_license | MBAYIsunga/Enforcing-Privacy-with-Cryptography | https://github.com/MBAYIsunga/Enforcing-Privacy-with-Cryptography | eefbf630454a1b716964a00668a9eb5de46e9b9a | 0c720f412dd46c47aa8eee88aebc086683937f85 | refs/heads/master | 2023-03-16T01:35:34.659000 | 2019-05-28T20:43:26 | 2019-05-28T20:43:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package cryptography;
/**
*
* @author Titan
*/
public class Encryption {
private int data,
firstDigit,
secondDigit,
thirdDigit,
fourthDigit;
public Encryption(int data){
this.data = data;
}
public int getData(){
return data;
}
private void splitDigits(){
firstDigit = ((data % 10000) / 1000);
secondDigit = ((data % 1000) / 100);
thirdDigit = ((data % 100) / 10);
fourthDigit = (data % 10);
}
private void swap(){
int temp;
temp = firstDigit;
firstDigit = thirdDigit;
thirdDigit = temp;
temp = secondDigit;
secondDigit = fourthDigit;
fourthDigit = temp;
}
private void printEncryptedData(){
System.out.printf("Encrypted data: %d%d%d%d%n", firstDigit, secondDigit, thirdDigit, fourthDigit);
}
public void encrypt(){
splitDigits();
//Replace each digit with the result of adding 7 to the digit
//Get the remainder after dividing new value by 10
firstDigit = (firstDigit + 7) % 10;
secondDigit = (secondDigit + 7) % 10;
thirdDigit = (thirdDigit + 7) % 10;
fourthDigit = (fourthDigit + 7) % 10;
//Swap the first digit with the third, and swap the second digit with
//the fourth.
swap();
//Print the encypted integer
printEncryptedData();
}
}//END ENCRYPTION
| UTF-8 | Java | 1,575 | java | Encryption.java | Java | [
{
"context": "\npackage cryptography;\n\n/**\n *\n * @author Titan\n */\npublic class Encryption {\n private int dat",
"end": 47,
"score": 0.99587082862854,
"start": 42,
"tag": "NAME",
"value": "Titan"
}
]
| null | []
|
package cryptography;
/**
*
* @author Titan
*/
public class Encryption {
private int data,
firstDigit,
secondDigit,
thirdDigit,
fourthDigit;
public Encryption(int data){
this.data = data;
}
public int getData(){
return data;
}
private void splitDigits(){
firstDigit = ((data % 10000) / 1000);
secondDigit = ((data % 1000) / 100);
thirdDigit = ((data % 100) / 10);
fourthDigit = (data % 10);
}
private void swap(){
int temp;
temp = firstDigit;
firstDigit = thirdDigit;
thirdDigit = temp;
temp = secondDigit;
secondDigit = fourthDigit;
fourthDigit = temp;
}
private void printEncryptedData(){
System.out.printf("Encrypted data: %d%d%d%d%n", firstDigit, secondDigit, thirdDigit, fourthDigit);
}
public void encrypt(){
splitDigits();
//Replace each digit with the result of adding 7 to the digit
//Get the remainder after dividing new value by 10
firstDigit = (firstDigit + 7) % 10;
secondDigit = (secondDigit + 7) % 10;
thirdDigit = (thirdDigit + 7) % 10;
fourthDigit = (fourthDigit + 7) % 10;
//Swap the first digit with the third, and swap the second digit with
//the fourth.
swap();
//Print the encypted integer
printEncryptedData();
}
}//END ENCRYPTION
| 1,575 | 0.526984 | 0.502857 | 64 | 23.578125 | 19.882313 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
2a8333ef542ecde524c423a7f8cb90171188387c | 13,872,744,404,135 | 93a647af093f1ddac5bb3320ce45f6d6dfae80cb | /iiop/src/main/java/org/jboss/iiop/csiv2/SASTargetInterceptor.java | 746f773eca487633d78861d19fb7eb3d10f259f9 | []
| no_license | dcreado/jbossas6 | https://github.com/dcreado/jbossas6 | a311cc26e279f0d0f6967dbe34d06af0a032c681 | 8230db72d8afc0c70054c64c6f8e98037f03ae13 | refs/heads/master | 2021-03-12T19:46:40.571000 | 2013-04-23T23:42:49 | 2013-04-23T23:42:49 | 9,553,661 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.iiop.csiv2;
/***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/
import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.MARSHAL;
import org.omg.CORBA.NO_PERMISSION;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.ORB;
import org.omg.CSI.CompleteEstablishContext;
import org.omg.CSI.ContextError;
import org.omg.CSI.EstablishContext;
import org.omg.CSI.GSS_NT_ExportedNameHelper;
import org.omg.CSI.ITTPrincipalName;
import org.omg.CSI.IdentityToken;
import org.omg.CSI.MTEstablishContext;
import org.omg.CSI.MTMessageInContext;
import org.omg.CSI.SASContextBody;
import org.omg.CSI.SASContextBodyHelper;
import org.omg.GSSUP.ErrorToken;
import org.omg.GSSUP.ErrorTokenHelper;
import org.omg.GSSUP.GSS_UP_S_G_UNSPECIFIED;
import org.omg.GSSUP.InitialContextToken;
import org.omg.IOP.Codec;
import org.omg.IOP.CodecPackage.FormatMismatch;
import org.omg.IOP.CodecPackage.TypeMismatch;
import org.omg.IOP.CodecPackage.InvalidTypeForEncoding;
import org.omg.IOP.ServiceContext;
import org.omg.PortableInterceptor.ServerRequestInfo;
import org.omg.PortableInterceptor.ServerRequestInterceptor;
import org.jboss.iiop.CorbaORBService;
import org.jboss.logging.Logger;
/**
* This implementation of
* <code>org.omg.PortableInterceptor.ServerRequestInterceptor</code>
* extracts the security attribute service (SAS) context from incoming IIOP
* and inserts SAS messages into the SAS context of outgoing IIOP replies.
*
* @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a>
* @version $Revision: 81018 $
*/
public class SASTargetInterceptor
extends LocalObject
implements ServerRequestInterceptor
{
// Static fields and initializers ---------------------------------
private static final Logger log =
Logger.getLogger(SASTargetInterceptor.class);
private static final boolean traceEnabled = log.isTraceEnabled();
private static final int sasContextId =
org.omg.IOP.SecurityAttributeService.value;
private static final byte[] empty = new byte[0];
private static final IdentityToken absent;
/** Scratch field for <code>CompleteEstablishContext<code> messages */
private static final SASContextBody msgBodyCtxAccepted;
/** Ready-to-go <code>CompleteEstablishContext<code> message
with context id set to zero */
private static final Any msgCtx0Accepted;
static
{
// initialize absent
absent = new IdentityToken();
absent.absent(true);
// initialize msgBodyCtxAccepted
// (Note that "context stateful" is always set to false. Even if the
// client wants a stateful context, we negotiate the context down to
// stateless.)
CompleteEstablishContext ctxAccepted =
new CompleteEstablishContext(0, /* context id */
false, /* context stateful */
new byte[0] /* no final token */);
msgBodyCtxAccepted = new SASContextBody();
msgBodyCtxAccepted.complete_msg(ctxAccepted);
// initialize msgCtx0Accepted
msgCtx0Accepted = createMsgCtxAccepted(0);
}
// Static methods ------------------------------------------------
private static Any createMsgCtxAccepted(long contextId)
{
Any any = ORB.init().create_any();
synchronized (msgBodyCtxAccepted)
{
msgBodyCtxAccepted.complete_msg().client_context_id = contextId;
SASContextBodyHelper.insert(any, msgBodyCtxAccepted);
}
return any;
}
// Fields ---------------------------------------------------------
private final Codec codec;
/** Scratch field for <code>ContextError<code> messages */
private final SASContextBody msgBodyCtxError;
/** Ready-to-go <code>ContextError<code> message with context id set to
zero and major status "invalid evidence" */
private final Any msgCtx0Rejected;
private ThreadLocal threadLocalData = new ThreadLocal() {
protected synchronized Object initialValue()
{
return new CurrentRequestInfo(); // see nested class below
}
};
// Nested class -------------------------------------------------
/**
* The <code>CurrentRequestInfo</code> class holds SAS information
* associated with IIOP request handled by the current thread.
*/
private static class CurrentRequestInfo
{
boolean sasContextReceived;
boolean authenticationTokenReceived;
byte[] incomingUsername;
byte[] incomingPassword;
byte[] incomingTargetName;
IdentityToken incomingIdentity;
byte[] incomingPrincipalName;
long contextId;
Any sasReply;
boolean sasReplyIsAccept; // true if sasReply is
// CompleteEstablishContext (for
// interoperability with IONA's ASP 6.0)
CurrentRequestInfo()
{
}
}
// Private method ------------------------------------------------
private Any createMsgCtxError(long contextId, int majorStatus)
{
Any any = ORB.init().create_any();
synchronized (msgBodyCtxError)
{
msgBodyCtxError.error_msg().client_context_id = contextId;
msgBodyCtxError.error_msg().major_status = majorStatus;
SASContextBodyHelper.insert(any, msgBodyCtxError);
}
return any;
}
// Constructor ---------------------------------------------------
public SASTargetInterceptor(Codec codec)
{
this.codec = codec;
// build encapsulated GSSUP error token for ContextError messages
// (the error code within the error token is GSS_UP_S_G_UNSPECIFIED,
// which says nothing about the cause of the error)
ErrorToken errorToken = new ErrorToken(GSS_UP_S_G_UNSPECIFIED.value);
Any any = ORB.init().create_any();
byte[] encapsulatedErrorToken;
ErrorTokenHelper.insert(any, errorToken);
try
{
encapsulatedErrorToken = codec.encode_value(any);
}
catch (InvalidTypeForEncoding e)
{
throw new RuntimeException("Unexpected exception: " + e);
}
// initialize msgBodyCtxError
ContextError ctxError =
new ContextError(0, /* context id */
1, /* major status: invalid evidence */
1, /* minor status (always 1) */
encapsulatedErrorToken);
msgBodyCtxError = new SASContextBody();
msgBodyCtxError.error_msg(ctxError);
// initialize msgCtx0Rejected (major status: invalid evidence)
msgCtx0Rejected = createMsgCtxError(0, 1);
}
// Methods -------------------------------------------------------
/**
* Returns true if an SAS context arrived with the current IIOP request.
*/
boolean sasContextReceived()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.sasContextReceived;
}
/**
* Returns true if a client authentication token arrived with the
* current IIOP request.
*/
boolean authenticationTokenReceived()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.authenticationTokenReceived;
}
/**
* Returns the username that arrived in the current IIOP request.
*/
byte[] getIncomingUsername()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingUsername;
}
/**
* Returns the password that arrived in the current IIOP request.
*/
byte[] getIncomingPassword()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingPassword;
}
/**
* Returns the target name that arrived in the current IIOP request.
*/
byte[] getIncomingTargetName()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingTargetName;
}
/**
* Returns the <code>org.omg.CSI.IdentityToken<code> that arrived in
* the current IIOP request.
*/
IdentityToken getIncomingIdentity()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingIdentity;
}
/**
* Returns the principal name that arrived in the current IIOP request.
*/
byte[] getIncomingPrincipalName()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingPrincipalName;
}
/**
* Sets the outgoing SAS reply to <code>ContextError</code>, with major
* status "invalid evidence".
*/
void rejectIncomingContext()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
if (threadLocal.sasContextReceived)
{
threadLocal.sasReply =
(threadLocal.contextId == 0)
? msgCtx0Rejected
: createMsgCtxError(threadLocal.contextId,
1 /* major status: invalid evidence */);
threadLocal.sasReplyIsAccept = false;
}
}
// org.omg.PortableInterceptor.Interceptor operations ------------
public String name()
{
return "SASTargetInterceptor";
}
public void destroy()
{
// do nothing
}
// ServerRequestInterceptor operations ---------------------------
public void receive_request_service_contexts(ServerRequestInfo ri)
{
// do nothing
}
// ServerRequestInterceptor operations ---------------------------
public void receive_request(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("receive_request " + ri.operation());
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
threadLocal.sasContextReceived = false;
threadLocal.authenticationTokenReceived = false;
threadLocal.incomingUsername = empty;
threadLocal.incomingPassword = empty;
threadLocal.incomingTargetName = empty;
threadLocal.incomingIdentity = absent;
threadLocal.incomingPrincipalName = empty;
threadLocal.sasReply = null;
threadLocal.sasReplyIsAccept = false;
try
{
ServiceContext sc = ri.get_request_service_context(sasContextId);
Any any = codec.decode_value(sc.context_data,
SASContextBodyHelper.type());
SASContextBody contextBody = SASContextBodyHelper.extract(any);
if (contextBody == null)
{
// we're done
return;
}
else if (contextBody.discriminator() == MTMessageInContext.value)
{
// should not happen, as stateful context requests are always
// negotiated down to stateless in this implementation
long contextId =
contextBody.in_context_msg().client_context_id;
threadLocal.sasReply =
createMsgCtxError(contextId,
4 /* major status: no context */);
throw new NO_PERMISSION("SAS context does not exist.");
}
else if (contextBody.discriminator() == MTEstablishContext.value)
{
EstablishContext message = contextBody.establish_msg();
threadLocal.contextId = message.client_context_id;
threadLocal.sasContextReceived = true;
if (message.client_authentication_token != null
&& message.client_authentication_token.length > 0)
{
if (traceEnabled)
log.trace("received client authentication token");
InitialContextToken authToken =
CSIv2Util.decodeInitialContextToken(
message.client_authentication_token,
codec);
if (authToken == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode " +
"initial context token.");
}
threadLocal.incomingUsername = authToken.username;
threadLocal.incomingPassword = authToken.password;
threadLocal.incomingTargetName =
CSIv2Util.decodeGssExportedName(authToken.target_name);
if (threadLocal.incomingTargetName == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode target name " +
"in initial context token.");
}
threadLocal.authenticationTokenReceived = true;
}
if (message.identity_token != null)
{
if (traceEnabled)
log.trace("received identity token");
threadLocal.incomingIdentity = message.identity_token;
if (message.identity_token.discriminator() == ITTPrincipalName.value)
{
// Extract the RFC2743-encoded name
// from CDR encapsulation
Any a = codec.decode_value(
message.identity_token.principal_name(),
GSS_NT_ExportedNameHelper.type());
byte[] encodedName = GSS_NT_ExportedNameHelper.extract(a);
// Decode the principal name
threadLocal.incomingPrincipalName =
CSIv2Util.decodeGssExportedName(encodedName);
if (threadLocal.incomingPrincipalName == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode " +
"incoming principal name.");
}
}
}
threadLocal.sasReply = (threadLocal.contextId == 0) ?
msgCtx0Accepted :
createMsgCtxAccepted(threadLocal.contextId);
threadLocal.sasReplyIsAccept = true;
}
}
catch (BAD_PARAM e)
{
// no service context with sasContextId: do nothing
}
catch (FormatMismatch e)
{
throw new MARSHAL("Exception decoding context data in " +
"SASTargetInterceptor: " + e);
}
catch (TypeMismatch e)
{
throw new MARSHAL("Exception decoding context data in " +
"SASTargetInterceptor: " + e);
}
}
public void send_reply(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("send_reply " + ri.operation());
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
if (threadLocal.sasReply != null)
{
try
{
ServiceContext sc =
new ServiceContext(sasContextId,
codec.encode_value(threadLocal.sasReply));
ri.add_reply_service_context(sc, true);
}
catch (InvalidTypeForEncoding e)
{
throw new MARSHAL("Unexpected exception: " + e);
}
}
}
public void send_exception(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("send_exception " + ri.operation() + ": ");
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
// The check for sasReplyIsAccept below was added for interoperability
// with IONA's ASP 6.0, which throws an ArrayIndexOutOfBoundsException
// when it receives an IIOP reply carrying both an application exception
// and a SAS reply CompleteEstablishContext. The sasReplyIsAccept flag
// serves the purpose of refraining from sending an SAS accept
// (CompleteEstablishContext) reply together with an exception.
//
// The CSIv2 spec does not explicitly disallow an SAS accept in an
// IIOP exception reply.
//
if (threadLocal.sasReply != null &&
(!threadLocal.sasReplyIsAccept ||
CorbaORBService.getSendSASAcceptWithExceptionEnabledFlag() == true))
{
try
{
ServiceContext sc =
new ServiceContext(sasContextId,
codec.encode_value(threadLocal.sasReply));
ri.add_reply_service_context(sc, true);
}
catch (InvalidTypeForEncoding e)
{
throw new MARSHAL("Unexpected exception: " + e);
}
}
}
public void send_other(ServerRequestInfo ri)
{
// Do nothing. According to the SAS spec, LOCATION_FORWARD reply
// carries no SAS message.
}
}
| UTF-8 | Java | 19,345 | java | SASTargetInterceptor.java | Java | [
{
"context": "going IIOP replies.\n *\n * @author <a href=\"mailto:reverbel@ime.usp.br\">Francisco Reverbel</a>\n * @version $Revision: 81",
"end": 2822,
"score": 0.9996741414070129,
"start": 2803,
"tag": "EMAIL",
"value": "reverbel@ime.usp.br"
},
{
"context": "*\n * @author <a href=\"mailto:reverbel@ime.usp.br\">Francisco Reverbel</a>\n * @version $Revision: 81018 $\n */\npublic cla",
"end": 2842,
"score": 0.9998767971992493,
"start": 2824,
"tag": "NAME",
"value": "Francisco Reverbel"
},
{
"context": "name = empty;\n threadLocal.incomingPassword = empty;\n threadLocal.incomingTargetName = empty;\n ",
"end": 11728,
"score": 0.6830319166183472,
"start": 11723,
"tag": "PASSWORD",
"value": "empty"
},
{
"context": " }\n threadLocal.incomingUsername = authToken.username;\n threadLocal.incomin",
"end": 14153,
"score": 0.805016279220581,
"start": 14149,
"tag": "USERNAME",
"value": "auth"
},
{
"context": " threadLocal.incomingUsername = authToken.username;\n threadLocal.incomingPassword = au",
"end": 14167,
"score": 0.8977605104446411,
"start": 14159,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ame;\n threadLocal.incomingPassword = authToken.password;\n threadLocal.incomingTargetName = ",
"end": 14233,
"score": 0.9989514946937561,
"start": 14215,
"tag": "PASSWORD",
"value": "authToken.password"
}
]
| null | []
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.iiop.csiv2;
/***************************************
* *
* JBoss: The OpenSource J2EE WebOS *
* *
* Distributable under LGPL license. *
* See terms of license at gnu.org. *
* *
***************************************/
import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.MARSHAL;
import org.omg.CORBA.NO_PERMISSION;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.ORB;
import org.omg.CSI.CompleteEstablishContext;
import org.omg.CSI.ContextError;
import org.omg.CSI.EstablishContext;
import org.omg.CSI.GSS_NT_ExportedNameHelper;
import org.omg.CSI.ITTPrincipalName;
import org.omg.CSI.IdentityToken;
import org.omg.CSI.MTEstablishContext;
import org.omg.CSI.MTMessageInContext;
import org.omg.CSI.SASContextBody;
import org.omg.CSI.SASContextBodyHelper;
import org.omg.GSSUP.ErrorToken;
import org.omg.GSSUP.ErrorTokenHelper;
import org.omg.GSSUP.GSS_UP_S_G_UNSPECIFIED;
import org.omg.GSSUP.InitialContextToken;
import org.omg.IOP.Codec;
import org.omg.IOP.CodecPackage.FormatMismatch;
import org.omg.IOP.CodecPackage.TypeMismatch;
import org.omg.IOP.CodecPackage.InvalidTypeForEncoding;
import org.omg.IOP.ServiceContext;
import org.omg.PortableInterceptor.ServerRequestInfo;
import org.omg.PortableInterceptor.ServerRequestInterceptor;
import org.jboss.iiop.CorbaORBService;
import org.jboss.logging.Logger;
/**
* This implementation of
* <code>org.omg.PortableInterceptor.ServerRequestInterceptor</code>
* extracts the security attribute service (SAS) context from incoming IIOP
* and inserts SAS messages into the SAS context of outgoing IIOP replies.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision: 81018 $
*/
public class SASTargetInterceptor
extends LocalObject
implements ServerRequestInterceptor
{
// Static fields and initializers ---------------------------------
private static final Logger log =
Logger.getLogger(SASTargetInterceptor.class);
private static final boolean traceEnabled = log.isTraceEnabled();
private static final int sasContextId =
org.omg.IOP.SecurityAttributeService.value;
private static final byte[] empty = new byte[0];
private static final IdentityToken absent;
/** Scratch field for <code>CompleteEstablishContext<code> messages */
private static final SASContextBody msgBodyCtxAccepted;
/** Ready-to-go <code>CompleteEstablishContext<code> message
with context id set to zero */
private static final Any msgCtx0Accepted;
static
{
// initialize absent
absent = new IdentityToken();
absent.absent(true);
// initialize msgBodyCtxAccepted
// (Note that "context stateful" is always set to false. Even if the
// client wants a stateful context, we negotiate the context down to
// stateless.)
CompleteEstablishContext ctxAccepted =
new CompleteEstablishContext(0, /* context id */
false, /* context stateful */
new byte[0] /* no final token */);
msgBodyCtxAccepted = new SASContextBody();
msgBodyCtxAccepted.complete_msg(ctxAccepted);
// initialize msgCtx0Accepted
msgCtx0Accepted = createMsgCtxAccepted(0);
}
// Static methods ------------------------------------------------
private static Any createMsgCtxAccepted(long contextId)
{
Any any = ORB.init().create_any();
synchronized (msgBodyCtxAccepted)
{
msgBodyCtxAccepted.complete_msg().client_context_id = contextId;
SASContextBodyHelper.insert(any, msgBodyCtxAccepted);
}
return any;
}
// Fields ---------------------------------------------------------
private final Codec codec;
/** Scratch field for <code>ContextError<code> messages */
private final SASContextBody msgBodyCtxError;
/** Ready-to-go <code>ContextError<code> message with context id set to
zero and major status "invalid evidence" */
private final Any msgCtx0Rejected;
private ThreadLocal threadLocalData = new ThreadLocal() {
protected synchronized Object initialValue()
{
return new CurrentRequestInfo(); // see nested class below
}
};
// Nested class -------------------------------------------------
/**
* The <code>CurrentRequestInfo</code> class holds SAS information
* associated with IIOP request handled by the current thread.
*/
private static class CurrentRequestInfo
{
boolean sasContextReceived;
boolean authenticationTokenReceived;
byte[] incomingUsername;
byte[] incomingPassword;
byte[] incomingTargetName;
IdentityToken incomingIdentity;
byte[] incomingPrincipalName;
long contextId;
Any sasReply;
boolean sasReplyIsAccept; // true if sasReply is
// CompleteEstablishContext (for
// interoperability with IONA's ASP 6.0)
CurrentRequestInfo()
{
}
}
// Private method ------------------------------------------------
private Any createMsgCtxError(long contextId, int majorStatus)
{
Any any = ORB.init().create_any();
synchronized (msgBodyCtxError)
{
msgBodyCtxError.error_msg().client_context_id = contextId;
msgBodyCtxError.error_msg().major_status = majorStatus;
SASContextBodyHelper.insert(any, msgBodyCtxError);
}
return any;
}
// Constructor ---------------------------------------------------
public SASTargetInterceptor(Codec codec)
{
this.codec = codec;
// build encapsulated GSSUP error token for ContextError messages
// (the error code within the error token is GSS_UP_S_G_UNSPECIFIED,
// which says nothing about the cause of the error)
ErrorToken errorToken = new ErrorToken(GSS_UP_S_G_UNSPECIFIED.value);
Any any = ORB.init().create_any();
byte[] encapsulatedErrorToken;
ErrorTokenHelper.insert(any, errorToken);
try
{
encapsulatedErrorToken = codec.encode_value(any);
}
catch (InvalidTypeForEncoding e)
{
throw new RuntimeException("Unexpected exception: " + e);
}
// initialize msgBodyCtxError
ContextError ctxError =
new ContextError(0, /* context id */
1, /* major status: invalid evidence */
1, /* minor status (always 1) */
encapsulatedErrorToken);
msgBodyCtxError = new SASContextBody();
msgBodyCtxError.error_msg(ctxError);
// initialize msgCtx0Rejected (major status: invalid evidence)
msgCtx0Rejected = createMsgCtxError(0, 1);
}
// Methods -------------------------------------------------------
/**
* Returns true if an SAS context arrived with the current IIOP request.
*/
boolean sasContextReceived()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.sasContextReceived;
}
/**
* Returns true if a client authentication token arrived with the
* current IIOP request.
*/
boolean authenticationTokenReceived()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.authenticationTokenReceived;
}
/**
* Returns the username that arrived in the current IIOP request.
*/
byte[] getIncomingUsername()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingUsername;
}
/**
* Returns the password that arrived in the current IIOP request.
*/
byte[] getIncomingPassword()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingPassword;
}
/**
* Returns the target name that arrived in the current IIOP request.
*/
byte[] getIncomingTargetName()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingTargetName;
}
/**
* Returns the <code>org.omg.CSI.IdentityToken<code> that arrived in
* the current IIOP request.
*/
IdentityToken getIncomingIdentity()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingIdentity;
}
/**
* Returns the principal name that arrived in the current IIOP request.
*/
byte[] getIncomingPrincipalName()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
return threadLocal.incomingPrincipalName;
}
/**
* Sets the outgoing SAS reply to <code>ContextError</code>, with major
* status "invalid evidence".
*/
void rejectIncomingContext()
{
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
if (threadLocal.sasContextReceived)
{
threadLocal.sasReply =
(threadLocal.contextId == 0)
? msgCtx0Rejected
: createMsgCtxError(threadLocal.contextId,
1 /* major status: invalid evidence */);
threadLocal.sasReplyIsAccept = false;
}
}
// org.omg.PortableInterceptor.Interceptor operations ------------
public String name()
{
return "SASTargetInterceptor";
}
public void destroy()
{
// do nothing
}
// ServerRequestInterceptor operations ---------------------------
public void receive_request_service_contexts(ServerRequestInfo ri)
{
// do nothing
}
// ServerRequestInterceptor operations ---------------------------
public void receive_request(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("receive_request " + ri.operation());
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
threadLocal.sasContextReceived = false;
threadLocal.authenticationTokenReceived = false;
threadLocal.incomingUsername = empty;
threadLocal.incomingPassword = <PASSWORD>;
threadLocal.incomingTargetName = empty;
threadLocal.incomingIdentity = absent;
threadLocal.incomingPrincipalName = empty;
threadLocal.sasReply = null;
threadLocal.sasReplyIsAccept = false;
try
{
ServiceContext sc = ri.get_request_service_context(sasContextId);
Any any = codec.decode_value(sc.context_data,
SASContextBodyHelper.type());
SASContextBody contextBody = SASContextBodyHelper.extract(any);
if (contextBody == null)
{
// we're done
return;
}
else if (contextBody.discriminator() == MTMessageInContext.value)
{
// should not happen, as stateful context requests are always
// negotiated down to stateless in this implementation
long contextId =
contextBody.in_context_msg().client_context_id;
threadLocal.sasReply =
createMsgCtxError(contextId,
4 /* major status: no context */);
throw new NO_PERMISSION("SAS context does not exist.");
}
else if (contextBody.discriminator() == MTEstablishContext.value)
{
EstablishContext message = contextBody.establish_msg();
threadLocal.contextId = message.client_context_id;
threadLocal.sasContextReceived = true;
if (message.client_authentication_token != null
&& message.client_authentication_token.length > 0)
{
if (traceEnabled)
log.trace("received client authentication token");
InitialContextToken authToken =
CSIv2Util.decodeInitialContextToken(
message.client_authentication_token,
codec);
if (authToken == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode " +
"initial context token.");
}
threadLocal.incomingUsername = authToken.username;
threadLocal.incomingPassword = <PASSWORD>;
threadLocal.incomingTargetName =
CSIv2Util.decodeGssExportedName(authToken.target_name);
if (threadLocal.incomingTargetName == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode target name " +
"in initial context token.");
}
threadLocal.authenticationTokenReceived = true;
}
if (message.identity_token != null)
{
if (traceEnabled)
log.trace("received identity token");
threadLocal.incomingIdentity = message.identity_token;
if (message.identity_token.discriminator() == ITTPrincipalName.value)
{
// Extract the RFC2743-encoded name
// from CDR encapsulation
Any a = codec.decode_value(
message.identity_token.principal_name(),
GSS_NT_ExportedNameHelper.type());
byte[] encodedName = GSS_NT_ExportedNameHelper.extract(a);
// Decode the principal name
threadLocal.incomingPrincipalName =
CSIv2Util.decodeGssExportedName(encodedName);
if (threadLocal.incomingPrincipalName == null)
{
threadLocal.sasReply =
createMsgCtxError(message.client_context_id,
2 /* major status:
invalid mechanism */);
throw new NO_PERMISSION("Could not decode " +
"incoming principal name.");
}
}
}
threadLocal.sasReply = (threadLocal.contextId == 0) ?
msgCtx0Accepted :
createMsgCtxAccepted(threadLocal.contextId);
threadLocal.sasReplyIsAccept = true;
}
}
catch (BAD_PARAM e)
{
// no service context with sasContextId: do nothing
}
catch (FormatMismatch e)
{
throw new MARSHAL("Exception decoding context data in " +
"SASTargetInterceptor: " + e);
}
catch (TypeMismatch e)
{
throw new MARSHAL("Exception decoding context data in " +
"SASTargetInterceptor: " + e);
}
}
public void send_reply(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("send_reply " + ri.operation());
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
if (threadLocal.sasReply != null)
{
try
{
ServiceContext sc =
new ServiceContext(sasContextId,
codec.encode_value(threadLocal.sasReply));
ri.add_reply_service_context(sc, true);
}
catch (InvalidTypeForEncoding e)
{
throw new MARSHAL("Unexpected exception: " + e);
}
}
}
public void send_exception(ServerRequestInfo ri)
{
if (traceEnabled)
log.trace("send_exception " + ri.operation() + ": ");
CurrentRequestInfo threadLocal =
(CurrentRequestInfo)threadLocalData.get();
// The check for sasReplyIsAccept below was added for interoperability
// with IONA's ASP 6.0, which throws an ArrayIndexOutOfBoundsException
// when it receives an IIOP reply carrying both an application exception
// and a SAS reply CompleteEstablishContext. The sasReplyIsAccept flag
// serves the purpose of refraining from sending an SAS accept
// (CompleteEstablishContext) reply together with an exception.
//
// The CSIv2 spec does not explicitly disallow an SAS accept in an
// IIOP exception reply.
//
if (threadLocal.sasReply != null &&
(!threadLocal.sasReplyIsAccept ||
CorbaORBService.getSendSASAcceptWithExceptionEnabledFlag() == true))
{
try
{
ServiceContext sc =
new ServiceContext(sasContextId,
codec.encode_value(threadLocal.sasReply));
ri.add_reply_service_context(sc, true);
}
catch (InvalidTypeForEncoding e)
{
throw new MARSHAL("Unexpected exception: " + e);
}
}
}
public void send_other(ServerRequestInfo ri)
{
// Do nothing. According to the SAS spec, LOCATION_FORWARD reply
// carries no SAS message.
}
}
| 19,318 | 0.583148 | 0.579943 | 537 | 35.024208 | 25.242094 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361266 | false | false | 0 |
c645fde7b74e6d06f1a8b75851b7ee2fe85c45c8 | 16,630,113,430,347 | 16c357d4c901ab5a017be0a3554efb37665a8932 | /business-service/orderservice-server/src/main/java/com/fshop/order/service/impl/OrderRpcServiceImpl.java | c75af6f8a94d4cfe3d8fad1f1d6643694e5c4f70 | [
"Apache-2.0"
]
| permissive | XuRepository/fshop | https://github.com/XuRepository/fshop | 9213a565ea956076d0bf3a27602645e20ccb7662 | 3a797a0f956b3d7efdc7d6e84b1f3681c75b6191 | refs/heads/master | 2023-03-15T23:38:31.365000 | 2020-09-29T05:06:08 | 2020-09-29T05:06:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2020 rannuo1010@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fshop.order.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.fshop.order.mapper.WarehouseStockMapper;
import com.fshop.order.rpc.OrderRpcService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* Description: 订单 RPC 服务
*
* @author rannuo1010@gmail.com
* @date 2020/2/22
*/
@Component
@Service(version = "1.0.0", interfaceClass = OrderRpcService.class)
public class OrderRpcServiceImpl implements OrderRpcService {
@Resource
private WarehouseStockMapper warehouseStockMapper;
@HystrixCommand
@Override
public int getProductStockNum(long productId) {
return warehouseStockMapper.selectStockNumByProductId(productId);
}
}
| UTF-8 | Java | 1,424 | java | OrderRpcServiceImpl.java | Java | [
{
"context": "/*\n * Copyright 2020 rannuo1010@gmail.com\n *\n * Licensed under the Apache License, Version ",
"end": 41,
"score": 0.9999223947525024,
"start": 21,
"tag": "EMAIL",
"value": "rannuo1010@gmail.com"
},
{
"context": "urce;\n\n/**\n * Description: 订单 RPC 服务\n *\n * @author rannuo1010@gmail.com\n * @date 2020/2/22\n */\n@Component\n@Service(versio",
"end": 1011,
"score": 0.9999234676361084,
"start": 991,
"tag": "EMAIL",
"value": "rannuo1010@gmail.com"
}
]
| null | []
| /*
* Copyright 2020 <EMAIL>
*
* 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.fshop.order.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.fshop.order.mapper.WarehouseStockMapper;
import com.fshop.order.rpc.OrderRpcService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* Description: 订单 RPC 服务
*
* @author <EMAIL>
* @date 2020/2/22
*/
@Component
@Service(version = "1.0.0", interfaceClass = OrderRpcService.class)
public class OrderRpcServiceImpl implements OrderRpcService {
@Resource
private WarehouseStockMapper warehouseStockMapper;
@HystrixCommand
@Override
public int getProductStockNum(long productId) {
return warehouseStockMapper.selectStockNumByProductId(productId);
}
}
| 1,398 | 0.764831 | 0.746469 | 45 | 30.466667 | 26.821716 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
3450d13abe923ff6998481cb508d2135173d964f | 9,466,107,946,423 | 2d0eb387f210b66915629f57977632b6bc5d892d | /src/com/company/homework7Member/member/service/impl/MemberServiceImpl.java | f292c1434156b01f2a209fe262ac387a8ff9bd67 | []
| no_license | hwangilyong/education_ | https://github.com/hwangilyong/education_ | c0ba8b5c80fa5106dc65acb07b5f5986cd2492b1 | 8fce8bd17c3d5e13d667224fce9e3ec0590d6331 | refs/heads/master | 2022-12-21T06:15:12.268000 | 2020-09-28T10:53:48 | 2020-09-28T10:53:48 | 299,280,779 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.homework7Member.member.service.impl;
import com.company.homework7Member.member.entity.MemberData;
import com.company.homework7Member.member.entity.MemberVO;
import com.company.homework7Member.member.service.MemberService;
import com.company.homework7Member.member.service.MemberValidationService;
import java.util.Scanner;
import java.util.regex.Pattern;
public class MemberServiceImpl extends MemberValidationServiceImpl implements MemberService, MemberValidationService {
private MemberData memberData = new MemberData();
private MemberVO currentUser;
// public void setMemberData(MemberData memberData){
// this.memberData = memberData;
// }
public void setCurrentUser(MemberVO currentUser){
this.currentUser = currentUser;
}
public MemberVO getCurrentUser(){
return currentUser;
}
public void logout(){
currentUser = null;
}
@Override
//public void memberRegister(MemberVO memberVO) throws Exception {//유저 가입
public void memberRegister() {
Scanner scanner = new Scanner(System.in);
boolean flag = true;
MemberVO memberVO = null;
do {
try {
while(true) {
try {
System.out.println("--[아이디 입력]--");
String userId = scanner.nextLine();
if (inputValidation(userId)) {
throw new Exception("아이디를 입력해주십시오");
}
if (memberDuplicationCheck(userId)) {
throw new Exception("아이디 중복");
}
memberVO = new MemberVO();
memberVO.setUserId(userId);
}catch(Exception e){
System.out.println(e.getMessage());
}
break;
}
while (true) {
try {
System.out.println("--[비밀번호 입력]--");
String userPassword = scanner.nextLine();
if (inputValidation(userPassword)) {
throw new Exception("비밀번호를 입력해주십시오");
}
if(!passwordValidation(userPassword)){
throw new Exception("입력 형식이 맞지않습니다.");
}
memberVO.setUserPassword(userPassword);
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
while (true) {
try {
System.out.println("--[비밀번호 재 입력]--");
String confirmPassword = scanner.nextLine();
if (inputValidation(confirmPassword)) {
throw new Exception("확인 비밀번호를 입력해주십시오");
}
memberVO.setConfirmPassword(confirmPassword);
if (!memberVO.passwordCheck()) {
throw new Exception("입력한 비밀번호와 다릅니다.");
}
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
while(true){
try {
System.out.println("--[이름 입력]--");
String userName = scanner.nextLine();
if (inputValidation(userName)) {
throw new Exception("이름을 입력해 주십시오");
}
if(!nameValidation(userName)){
throw new Exception("입력형식이 맞지 않습니다");
}
memberVO.setUserName(userName);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[이메일 입력]--");
String userEmail = scanner.nextLine();
if(inputValidation(userEmail)){
throw new Exception("이메일을 입력해 주십시오");
}
if(!emailVaildation(userEmail)){
throw new Exception("입력형식이 맞지 않습니다.");
}
memberVO.setUserEmail(userEmail);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[취미 입력]--");
String hobby = scanner.nextLine();
if(inputValidation(hobby)){
throw new Exception("취미를 입력해 주십시오");
}
memberVO.setHobby(hobby);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[특기 입력]--");
String specialty = scanner.nextLine();
if(inputValidation(specialty)){
throw new Exception("특기를 입력해 주십시오");
}
memberVO.setSpecialty(specialty);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[전화번호 입력]--");
System.out.println("-을 제외하고 입력해 주세요");
String phoneNum = scanner.nextLine();
if(inputValidation(phoneNum)){
throw new Exception("전화번호를 입력해 주십시오");
}
if(!phoneNumValidation(phoneNum)){
throw new Exception("정확히 입력하여 주십시오");
}
memberVO.setPhoneNum(phoneNum);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[생일 입력]--");
System.out.println("EX) 19900221 8자리 입력해주십시오");
int userBirth = scanner.nextInt();
if(inputValidation(userBirth)){
throw new Exception("생일을 입력해 주십시오");
}
birthValidation(userBirth);
memberVO.setUserBirth(userBirth);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
String[] sex = new String[]{"남자", "여자"};
try{
System.out.println("--[성별 입력]--");
System.out.println("[1 : 남자][2 : 여자]");
int choice = scanner.nextInt();
if(choice < 1 || choice > 2){
throw new Exception("1,2 둘중 하나 입력해주십시오");
}
memberVO.setUserSex(sex[choice - 1]);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[프로필 사진 파일 입력]--");
String fileName = scanner.nextLine();
if(!imageValidation(fileName)){
throw new Exception("지원 되지않는 파일확장자 입니다.");
}
memberVO.setFileName(fileName);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[주소 입력]--");
String userAddress = addressInfo();
memberVO.setUserAddress(userAddress);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
flag = false;
} while (flag);
memberData.setMemberVOList(memberVO);
}
@Override
//public void memberLogin(String userId, String userPassword) throws Exception {//로그인
public MemberVO memberLogin() throws Exception {
Scanner scanner = new Scanner(System.in);
MemberVO memberVO = null;
System.out.println("아이디 입력");
String userId = scanner.nextLine();
memberVO = selectByUserId(userId);
if(memberVO == null){
throw new Exception("아이디가 맞지않습니다");
}
System.out.println("비밀번호 입력");
String userPassword = scanner.nextLine();
if(!memberVO.loginPasswordCheck(userPassword)){
throw new Exception("비밀번호가 틀립니다.");
}
return memberVO;
}
@Override
public MemberVO selectByUserId(String userId) {//유저 검색
MemberVO memberVO = null;
for (int index = 0; index < memberData.getMemberVOList().length; index++) {
if (userId.equals(memberData.getMemberVO(index).getUserId())) {
memberVO = memberData.getMemberVO(index);
}
}
return memberVO;
}
@Override
public boolean memberDuplicationCheck(String userId) {
MemberVO memberVO = selectByUserId(userId);
if (memberVO != null) {
return true;
}
return false;
}
@Override
public void listAll() throws Exception {//전체 출력
MemberVO[] memberData = this.memberData.getMemberVOList();
for(MemberVO memberVO : memberData){
memberVO.ppp();
}
}
@Override
public String addressInfo() throws Exception {
Scanner scanner = new Scanner(System.in);
String[] addressInfos = {"중구", "남동구", "남구", "동구", "연수구", "부평구", "계양구", "서구", "종로구", "서대문구", "광진구", "강북구", "노원구", "성동구",
"동대문구", "중랑구", "도봉구", "강동구", "강남구", "송파구", "강서구", "구로구", "금천구", "중구", "마포구", "맛있구", "오지구", "지리구", "렛잇구",
"얼씨구"};
String cho = "ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ";
String[] hangle = { "[가-깋]", "[나-닣]", "[다-딯]", "[라-맇]", "[마-밓]", "[바-빟]", "[사-싷]", "[아-잏]", "[자-짛]",
"[차-칳]", "[카-킿]", "[타-팋]", "[파-핗]", "[하-힣]" };
String userAddress = "";
while(true){
System.out.println("주소 검색");
String search = scanner.nextLine();
String pattern2 = " ";
for(int index = 0; index < search.length(); index++){
if(cho.indexOf(search.charAt(index)) != -1) {
pattern2 += hangle[cho.indexOf(search.charAt(index))];
}else{
pattern2 += search.charAt(index);
}
}
String test3 = "((.?.?" + pattern2.trim() + ".?.?)+(\\d{1,3}|)+)";
String test = "";
int count = 0;
System.out.println("----[검색결과]----");
for (String addr : addressInfos) {
if (Pattern.matches(test3, addr)) {
count++;
System.out.println("TEST : " + addr);
test += count + "." + addr + " ";
}
}
if(count != 0){
String[] result = test.split(" ");
//(test.indexOf(choice + ".");
for(String res : result){
System.out.println(res);
}
System.out.println("주소 선택 숫자입력");
int choice = scanner.nextInt();
userAddress = result[choice - 1].substring(2);
break;
}
System.out.println("검색결과 없습니다.");
}
return userAddress;
}
}
| UTF-8 | Java | 13,816 | java | MemberServiceImpl.java | Java | [
{
"context": " }\n\n memberVO.setUserName(userName);\n break;\n ",
"end": 3954,
"score": 0.9030747413635254,
"start": 3946,
"tag": "USERNAME",
"value": "userName"
}
]
| null | []
| package com.company.homework7Member.member.service.impl;
import com.company.homework7Member.member.entity.MemberData;
import com.company.homework7Member.member.entity.MemberVO;
import com.company.homework7Member.member.service.MemberService;
import com.company.homework7Member.member.service.MemberValidationService;
import java.util.Scanner;
import java.util.regex.Pattern;
public class MemberServiceImpl extends MemberValidationServiceImpl implements MemberService, MemberValidationService {
private MemberData memberData = new MemberData();
private MemberVO currentUser;
// public void setMemberData(MemberData memberData){
// this.memberData = memberData;
// }
public void setCurrentUser(MemberVO currentUser){
this.currentUser = currentUser;
}
public MemberVO getCurrentUser(){
return currentUser;
}
public void logout(){
currentUser = null;
}
@Override
//public void memberRegister(MemberVO memberVO) throws Exception {//유저 가입
public void memberRegister() {
Scanner scanner = new Scanner(System.in);
boolean flag = true;
MemberVO memberVO = null;
do {
try {
while(true) {
try {
System.out.println("--[아이디 입력]--");
String userId = scanner.nextLine();
if (inputValidation(userId)) {
throw new Exception("아이디를 입력해주십시오");
}
if (memberDuplicationCheck(userId)) {
throw new Exception("아이디 중복");
}
memberVO = new MemberVO();
memberVO.setUserId(userId);
}catch(Exception e){
System.out.println(e.getMessage());
}
break;
}
while (true) {
try {
System.out.println("--[비밀번호 입력]--");
String userPassword = scanner.nextLine();
if (inputValidation(userPassword)) {
throw new Exception("비밀번호를 입력해주십시오");
}
if(!passwordValidation(userPassword)){
throw new Exception("입력 형식이 맞지않습니다.");
}
memberVO.setUserPassword(userPassword);
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
while (true) {
try {
System.out.println("--[비밀번호 재 입력]--");
String confirmPassword = scanner.nextLine();
if (inputValidation(confirmPassword)) {
throw new Exception("확인 비밀번호를 입력해주십시오");
}
memberVO.setConfirmPassword(confirmPassword);
if (!memberVO.passwordCheck()) {
throw new Exception("입력한 비밀번호와 다릅니다.");
}
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
while(true){
try {
System.out.println("--[이름 입력]--");
String userName = scanner.nextLine();
if (inputValidation(userName)) {
throw new Exception("이름을 입력해 주십시오");
}
if(!nameValidation(userName)){
throw new Exception("입력형식이 맞지 않습니다");
}
memberVO.setUserName(userName);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[이메일 입력]--");
String userEmail = scanner.nextLine();
if(inputValidation(userEmail)){
throw new Exception("이메일을 입력해 주십시오");
}
if(!emailVaildation(userEmail)){
throw new Exception("입력형식이 맞지 않습니다.");
}
memberVO.setUserEmail(userEmail);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[취미 입력]--");
String hobby = scanner.nextLine();
if(inputValidation(hobby)){
throw new Exception("취미를 입력해 주십시오");
}
memberVO.setHobby(hobby);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[특기 입력]--");
String specialty = scanner.nextLine();
if(inputValidation(specialty)){
throw new Exception("특기를 입력해 주십시오");
}
memberVO.setSpecialty(specialty);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[전화번호 입력]--");
System.out.println("-을 제외하고 입력해 주세요");
String phoneNum = scanner.nextLine();
if(inputValidation(phoneNum)){
throw new Exception("전화번호를 입력해 주십시오");
}
if(!phoneNumValidation(phoneNum)){
throw new Exception("정확히 입력하여 주십시오");
}
memberVO.setPhoneNum(phoneNum);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[생일 입력]--");
System.out.println("EX) 19900221 8자리 입력해주십시오");
int userBirth = scanner.nextInt();
if(inputValidation(userBirth)){
throw new Exception("생일을 입력해 주십시오");
}
birthValidation(userBirth);
memberVO.setUserBirth(userBirth);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
String[] sex = new String[]{"남자", "여자"};
try{
System.out.println("--[성별 입력]--");
System.out.println("[1 : 남자][2 : 여자]");
int choice = scanner.nextInt();
if(choice < 1 || choice > 2){
throw new Exception("1,2 둘중 하나 입력해주십시오");
}
memberVO.setUserSex(sex[choice - 1]);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[프로필 사진 파일 입력]--");
String fileName = scanner.nextLine();
if(!imageValidation(fileName)){
throw new Exception("지원 되지않는 파일확장자 입니다.");
}
memberVO.setFileName(fileName);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
while(true){
try{
System.out.println("--[주소 입력]--");
String userAddress = addressInfo();
memberVO.setUserAddress(userAddress);
break;
}catch(Exception e){
System.out.println(e.getMessage());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
flag = false;
} while (flag);
memberData.setMemberVOList(memberVO);
}
@Override
//public void memberLogin(String userId, String userPassword) throws Exception {//로그인
public MemberVO memberLogin() throws Exception {
Scanner scanner = new Scanner(System.in);
MemberVO memberVO = null;
System.out.println("아이디 입력");
String userId = scanner.nextLine();
memberVO = selectByUserId(userId);
if(memberVO == null){
throw new Exception("아이디가 맞지않습니다");
}
System.out.println("비밀번호 입력");
String userPassword = scanner.nextLine();
if(!memberVO.loginPasswordCheck(userPassword)){
throw new Exception("비밀번호가 틀립니다.");
}
return memberVO;
}
@Override
public MemberVO selectByUserId(String userId) {//유저 검색
MemberVO memberVO = null;
for (int index = 0; index < memberData.getMemberVOList().length; index++) {
if (userId.equals(memberData.getMemberVO(index).getUserId())) {
memberVO = memberData.getMemberVO(index);
}
}
return memberVO;
}
@Override
public boolean memberDuplicationCheck(String userId) {
MemberVO memberVO = selectByUserId(userId);
if (memberVO != null) {
return true;
}
return false;
}
@Override
public void listAll() throws Exception {//전체 출력
MemberVO[] memberData = this.memberData.getMemberVOList();
for(MemberVO memberVO : memberData){
memberVO.ppp();
}
}
@Override
public String addressInfo() throws Exception {
Scanner scanner = new Scanner(System.in);
String[] addressInfos = {"중구", "남동구", "남구", "동구", "연수구", "부평구", "계양구", "서구", "종로구", "서대문구", "광진구", "강북구", "노원구", "성동구",
"동대문구", "중랑구", "도봉구", "강동구", "강남구", "송파구", "강서구", "구로구", "금천구", "중구", "마포구", "맛있구", "오지구", "지리구", "렛잇구",
"얼씨구"};
String cho = "ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ";
String[] hangle = { "[가-깋]", "[나-닣]", "[다-딯]", "[라-맇]", "[마-밓]", "[바-빟]", "[사-싷]", "[아-잏]", "[자-짛]",
"[차-칳]", "[카-킿]", "[타-팋]", "[파-핗]", "[하-힣]" };
String userAddress = "";
while(true){
System.out.println("주소 검색");
String search = scanner.nextLine();
String pattern2 = " ";
for(int index = 0; index < search.length(); index++){
if(cho.indexOf(search.charAt(index)) != -1) {
pattern2 += hangle[cho.indexOf(search.charAt(index))];
}else{
pattern2 += search.charAt(index);
}
}
String test3 = "((.?.?" + pattern2.trim() + ".?.?)+(\\d{1,3}|)+)";
String test = "";
int count = 0;
System.out.println("----[검색결과]----");
for (String addr : addressInfos) {
if (Pattern.matches(test3, addr)) {
count++;
System.out.println("TEST : " + addr);
test += count + "." + addr + " ";
}
}
if(count != 0){
String[] result = test.split(" ");
//(test.indexOf(choice + ".");
for(String res : result){
System.out.println(res);
}
System.out.println("주소 선택 숫자입력");
int choice = scanner.nextInt();
userAddress = result[choice - 1].substring(2);
break;
}
System.out.println("검색결과 없습니다.");
}
return userAddress;
}
}
| 13,816 | 0.421355 | 0.418558 | 388 | 32.164948 | 25.085289 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520619 | false | false | 0 |
f1e6daba8cfeab7c7878f8caacef5dd9e790ed15 | 19,559,281,104,868 | 60ea811887ec261c97f28ac1bae993959df545fc | /LeetCode/src/math/number_of1.java | 564efe6d4b933f8eeed1b3f81a49963d004cd1e6 | []
| no_license | luqili123/- | https://github.com/luqili123/- | d449d7f95ec1c72fab0ace7c3b624ca15d50c479 | 6b318cf680199d3167c7f4759f7577e18da221d5 | refs/heads/master | 2021-03-25T04:59:18.797000 | 2020-05-27T03:32:51 | 2020-05-27T03:32:51 | 247,590,963 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package math;
public class number_of1 {
public int NumberOf1(int n) {
//n : 10110100
//n-1 : 10110011
//n&(n-1) : 10110000
//每进行一次与运算,就会减少一个1,当n为0时,与运算的次数就是1的个数
int count=0;
while(n!=0){
n=n&(n-1);
count++;
}
return count;
}
}
| UTF-8 | Java | 357 | java | number_of1.java | Java | []
| null | []
| package math;
public class number_of1 {
public int NumberOf1(int n) {
//n : 10110100
//n-1 : 10110011
//n&(n-1) : 10110000
//每进行一次与运算,就会减少一个1,当n为0时,与运算的次数就是1的个数
int count=0;
while(n!=0){
n=n&(n-1);
count++;
}
return count;
}
}
| 357 | 0.511864 | 0.39661 | 17 | 15.352942 | 10.889504 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.823529 | false | false | 0 |
cce6a35ae33cb4a33fa2e64fbbfa3c427db18c62 | 29,274,497,131,267 | 959a9ad0507b202076af07ef86a07673bc4d159b | /2016_take2/AoC2016_21.java | 0a57e7fad0bb9ff0c1136fd6d28b333f6e899074 | []
| no_license | JureRot/adventofcode | https://github.com/JureRot/adventofcode | ad43f4af133e4f42afcf7baedf3e924d22985d22 | ad8040311857663359651435932eb08a50651772 | refs/heads/master | 2022-11-02T03:17:11.799000 | 2022-11-01T20:19:13 | 2022-11-01T20:19:13 | 120,766,224 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
class AoC2016_21 {
public static String swapPos(String str, int x, int y) {
//swaps letters at x and y
char a = str.charAt(x);
char b = str.charAt(y);
if (x < y) { //a (x) is first
str = str.substring(0, x) + b + str.substring(x+1, y) + a + str.substring(y+1);
} else { //b (y) is first
str = str.substring(0, y) + a + str.substring(y+1, x) + b + str.substring(x+1);
}
return str;
}
public static String swapLet(String str, char a, char b) { //maybe change char with String
//swaps letters a and b (actual letters, where a was, now is b; and reverse) (always ony one pair)
int x = str.indexOf(a);
int y = str.indexOf(b);
if (x < y) { //a (x) is first
str = str.substring(0, x) + b + str.substring(x+1, y) + a + str.substring(y+1);
} else { //b (y) is first
str = str.substring(0, y) + a + str.substring(y+1, x) + b + str.substring(x+1);
}
return str;
}
public static String rotateL(String str, int x) {
//rotate x times left (move front to end x times)
for (int i=0; i<x; i++) {
str = str.substring(1) + str.charAt(0);
}
return str;
}
public static String rotateR(String str, int x) {
//rotate x times left (move end to front x times)
for (int i=0; i<x; i++) {
str = str.charAt(str.length()-1) + str.substring(0, str.length()-1);
}
return str;
}
public static String rotateN(String str, char a) { //maybe change char with String
//rotate (1 + index(a) (+1 if index(a)>=4)) times right
int x = str.indexOf(a);
int n = 1 + x;
if (x >= 4) { //if index at least 4 we add one shift
n += 1;
}
return rotateR(str, n);
}
public static String rotateNRev(String str, char a) { //maybe change char with String
//reverse of rotateN (n = x/2 (+1 if x even or zero) or (+5 if odd or not zero)) works only for len 8 (more info in analysis)
int x = str.indexOf(a);
int n = x / 2;
if (x%2==1 || x==0) {
n += 1;
} else {
n += 5;
}
return rotateL(str, n);
}
public static String reverse(String str, int x, int y) {
//reverse substring from x to y (inclusive)
String output = str.substring(0, x); //new temp string with unchanged part before the range
for (int i=y; i>=x; i--) { //we go backward through range
output += str.charAt(i);
}
output += str.substring(y+1); //we add the remaining unchanged part after the range
return output;
}
public static String move(String str, int x, int y) {
//moves leter at x to so that is now at y
char a = str.charAt(x);
str = str.replace(String.valueOf(a), ""); //remove char at x ((String) used, because replace can have char,char or str,str, (and we want str,str for ""))
str = str.substring(0, y) + a + str.substring(y);
return str;
}
public static void main(String[] args) throws IOException {
long startTime = System.nanoTime();
//vars
String password = "abcdefgh";
//second part
ArrayList<String[]> lines = new ArrayList<>();
String password2 = "fbgdceah";
Scanner sc = new Scanner(new File("input2016_21.txt"));
while (sc.hasNextLine()) {
String[] lineSplit = sc.nextLine().split(" ");
if (lineSplit[0].equals("swap")) {
if (lineSplit[1].equals("position")) { //swap position
password = swapPos(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
} else if (lineSplit[1].equals("letter")) { //swap letter
password = swapLet(password, lineSplit[2].charAt(0), lineSplit[5].charAt(0));
}
} else if (lineSplit[0].equals("rotate")) {
if (lineSplit[1].equals("left")) { //rotate left
password = rotateL(password, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("right")) { //rotate right
password = rotateR(password, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("based")) { //rotate based on index
password = rotateN(password, lineSplit[6].charAt(0));
}
} else if (lineSplit[0].equals("reverse")) { //reverse
password = reverse(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[4]));
} else if (lineSplit[0].equals("move")) { //move
password = move(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
}
//second part
lines.add(lineSplit);
}
sc.close();
System.out.println("1. password after scrambling 'abcdefgh': " + password);
//second part (could be done by brute-force (checking all 8! (only 40320) possible inputs and checking the output))
for (int i=lines.size()-1; i>=0; i--) { //we go in reverse
String[] lineSplit = lines.get(i);
if (lineSplit[0].equals("swap")) {
if (lineSplit[1].equals("position")) { //swap position same in reverse
password2 = swapPos(password2, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
} else if (lineSplit[1].equals("letter")) { //swap letter same in reverse
password2 = swapLet(password2, lineSplit[2].charAt(0), lineSplit[5].charAt(0));
}
} else if (lineSplit[0].equals("rotate")) {
if (lineSplit[1].equals("left")) { //rotate left becomes rotate right in reverse
password2 = rotateR(password2, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("right")) { //rotate right becomes rotate left in reverse
password2 = rotateL(password2, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("based")) { //rotate based on index has new function
password2 = rotateNRev(password2, lineSplit[6].charAt(0));
}
} else if (lineSplit[0].equals("reverse")) { //reverse is same in reverse (xD)
password2 = reverse(password2, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[4]));
} else if (lineSplit[0].equals("move")) { //move reverses the parameters in reverse
password2 = move(password2, Integer.parseInt(lineSplit[5]), Integer.parseInt(lineSplit[2]));
}
}
System.out.println("2. password that is scrambeled into 'fbgdceah': " + password2);
long endTime = System.nanoTime();
System.out.println("Time :" + Double.toString((endTime-startTime)/1000000000.0) + " s");
}
} | UTF-8 | Java | 7,185 | java | AoC2016_21.java | Java | [
{
"context": "ime();\n\n //vars\n String password = \"abcdefgh\";\n\n //second part\n ArrayList<String",
"end": 3409,
"score": 0.997703492641449,
"start": 3401,
"tag": "PASSWORD",
"value": "abcdefgh"
},
{
"context": " = new ArrayList<>();\n String password2 = \"fbgdceah\";\n\n Scanner sc = new Scanner(new File(\"inp",
"end": 3526,
"score": 0.999517560005188,
"start": 3518,
"tag": "PASSWORD",
"value": "fbgdceah"
}
]
| null | []
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
class AoC2016_21 {
public static String swapPos(String str, int x, int y) {
//swaps letters at x and y
char a = str.charAt(x);
char b = str.charAt(y);
if (x < y) { //a (x) is first
str = str.substring(0, x) + b + str.substring(x+1, y) + a + str.substring(y+1);
} else { //b (y) is first
str = str.substring(0, y) + a + str.substring(y+1, x) + b + str.substring(x+1);
}
return str;
}
public static String swapLet(String str, char a, char b) { //maybe change char with String
//swaps letters a and b (actual letters, where a was, now is b; and reverse) (always ony one pair)
int x = str.indexOf(a);
int y = str.indexOf(b);
if (x < y) { //a (x) is first
str = str.substring(0, x) + b + str.substring(x+1, y) + a + str.substring(y+1);
} else { //b (y) is first
str = str.substring(0, y) + a + str.substring(y+1, x) + b + str.substring(x+1);
}
return str;
}
public static String rotateL(String str, int x) {
//rotate x times left (move front to end x times)
for (int i=0; i<x; i++) {
str = str.substring(1) + str.charAt(0);
}
return str;
}
public static String rotateR(String str, int x) {
//rotate x times left (move end to front x times)
for (int i=0; i<x; i++) {
str = str.charAt(str.length()-1) + str.substring(0, str.length()-1);
}
return str;
}
public static String rotateN(String str, char a) { //maybe change char with String
//rotate (1 + index(a) (+1 if index(a)>=4)) times right
int x = str.indexOf(a);
int n = 1 + x;
if (x >= 4) { //if index at least 4 we add one shift
n += 1;
}
return rotateR(str, n);
}
public static String rotateNRev(String str, char a) { //maybe change char with String
//reverse of rotateN (n = x/2 (+1 if x even or zero) or (+5 if odd or not zero)) works only for len 8 (more info in analysis)
int x = str.indexOf(a);
int n = x / 2;
if (x%2==1 || x==0) {
n += 1;
} else {
n += 5;
}
return rotateL(str, n);
}
public static String reverse(String str, int x, int y) {
//reverse substring from x to y (inclusive)
String output = str.substring(0, x); //new temp string with unchanged part before the range
for (int i=y; i>=x; i--) { //we go backward through range
output += str.charAt(i);
}
output += str.substring(y+1); //we add the remaining unchanged part after the range
return output;
}
public static String move(String str, int x, int y) {
//moves leter at x to so that is now at y
char a = str.charAt(x);
str = str.replace(String.valueOf(a), ""); //remove char at x ((String) used, because replace can have char,char or str,str, (and we want str,str for ""))
str = str.substring(0, y) + a + str.substring(y);
return str;
}
public static void main(String[] args) throws IOException {
long startTime = System.nanoTime();
//vars
String password = "<PASSWORD>";
//second part
ArrayList<String[]> lines = new ArrayList<>();
String password2 = "<PASSWORD>";
Scanner sc = new Scanner(new File("input2016_21.txt"));
while (sc.hasNextLine()) {
String[] lineSplit = sc.nextLine().split(" ");
if (lineSplit[0].equals("swap")) {
if (lineSplit[1].equals("position")) { //swap position
password = swapPos(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
} else if (lineSplit[1].equals("letter")) { //swap letter
password = swapLet(password, lineSplit[2].charAt(0), lineSplit[5].charAt(0));
}
} else if (lineSplit[0].equals("rotate")) {
if (lineSplit[1].equals("left")) { //rotate left
password = rotateL(password, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("right")) { //rotate right
password = rotateR(password, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("based")) { //rotate based on index
password = rotateN(password, lineSplit[6].charAt(0));
}
} else if (lineSplit[0].equals("reverse")) { //reverse
password = reverse(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[4]));
} else if (lineSplit[0].equals("move")) { //move
password = move(password, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
}
//second part
lines.add(lineSplit);
}
sc.close();
System.out.println("1. password after scrambling 'abcdefgh': " + password);
//second part (could be done by brute-force (checking all 8! (only 40320) possible inputs and checking the output))
for (int i=lines.size()-1; i>=0; i--) { //we go in reverse
String[] lineSplit = lines.get(i);
if (lineSplit[0].equals("swap")) {
if (lineSplit[1].equals("position")) { //swap position same in reverse
password2 = swapPos(password2, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[5]));
} else if (lineSplit[1].equals("letter")) { //swap letter same in reverse
password2 = swapLet(password2, lineSplit[2].charAt(0), lineSplit[5].charAt(0));
}
} else if (lineSplit[0].equals("rotate")) {
if (lineSplit[1].equals("left")) { //rotate left becomes rotate right in reverse
password2 = rotateR(password2, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("right")) { //rotate right becomes rotate left in reverse
password2 = rotateL(password2, Integer.parseInt(lineSplit[2]));
} else if (lineSplit[1].equals("based")) { //rotate based on index has new function
password2 = rotateNRev(password2, lineSplit[6].charAt(0));
}
} else if (lineSplit[0].equals("reverse")) { //reverse is same in reverse (xD)
password2 = reverse(password2, Integer.parseInt(lineSplit[2]), Integer.parseInt(lineSplit[4]));
} else if (lineSplit[0].equals("move")) { //move reverses the parameters in reverse
password2 = move(password2, Integer.parseInt(lineSplit[5]), Integer.parseInt(lineSplit[2]));
}
}
System.out.println("2. password that is scrambeled into 'fbgdceah': " + password2);
long endTime = System.nanoTime();
System.out.println("Time :" + Double.toString((endTime-startTime)/1000000000.0) + " s");
}
} | 7,189 | 0.553514 | 0.534864 | 177 | 39.598869 | 37.0616 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723164 | false | false | 0 |
324cbd29fa36be81f20cf4272c87e1c14542ed00 | 10,857,677,381,742 | 427bb384e5b7e7c3f5893e1723bcf53ef877fd80 | /src/main/java/dev/unworthiness/discordbot/commands/cmds/economy/admin/SetGetMuggedCdCommand.java | 48854c381b65e3ce9265bb7f6577f2846aee81cb | []
| no_license | mikanelson/pogchampbot | https://github.com/mikanelson/pogchampbot | 28dc77536ac1d446029fe64be3f29c3248becc93 | 68d33086dbf74310651b5f2179a9b5ef5ff9c0aa | refs/heads/master | 2022-10-11T14:34:58.061000 | 2020-06-11T16:14:43 | 2020-06-11T16:14:43 | 270,395,129 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.unworthiness.discordbot.commands.cmds.economy.admin;
import dev.unworthiness.discordbot.commands.CommandContext;
import dev.unworthiness.discordbot.commands.ICommand;
import dev.unworthiness.discordbot.database.SQLiteDataSource;
import dev.unworthiness.discordbot.database.economy.EconomyHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
public class SetGetMuggedCdCommand implements ICommand {
@Override
public void handle(CommandContext ctx) {
TextChannel channel = ctx.getChannel();
List<String> args = ctx.getArgs();
Member member = ctx.getMember();
if (!member.hasPermission(Permission.ADMINISTRATOR)) {
channel.sendMessage("You must have administrator permissions to use this command").queue();
}
if (args.isEmpty()) {
channel.sendMessage("No cooldown provided").queue();
}
long newCd = Long.parseLong(args.get(0));
updateMuggedCd(ctx.getGuild().getIdLong(), newCd);
channel.sendMessageFormat("Mug victim cooldown has been set to `%s`", newCd).queue();
}
@Override
public String getName() {
return "setmuggedcd";
}
@Override
public String getHelp() {
return "Sets cooldown, in seconds, for how often users can be mugged";
}
private void updateMuggedCd(long guildId, long cd) {
EconomyHandler.MUG_VICTIM_COOLDOWNS.put(guildId, cd);
Connection connection = null;
try {
connection = SQLiteDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement statement =
connection
// language=SQLite
.prepareStatement("UPDATE guild_settings SET mug_victim_cd = ? WHERE guild_id = ?")) {
statement.setLong(1, cd);
statement.setString(2, String.valueOf(guildId));
statement.executeUpdate();
statement.closeOnCompletion();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,149 | java | SetGetMuggedCdCommand.java | Java | []
| null | []
| package dev.unworthiness.discordbot.commands.cmds.economy.admin;
import dev.unworthiness.discordbot.commands.CommandContext;
import dev.unworthiness.discordbot.commands.ICommand;
import dev.unworthiness.discordbot.database.SQLiteDataSource;
import dev.unworthiness.discordbot.database.economy.EconomyHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
public class SetGetMuggedCdCommand implements ICommand {
@Override
public void handle(CommandContext ctx) {
TextChannel channel = ctx.getChannel();
List<String> args = ctx.getArgs();
Member member = ctx.getMember();
if (!member.hasPermission(Permission.ADMINISTRATOR)) {
channel.sendMessage("You must have administrator permissions to use this command").queue();
}
if (args.isEmpty()) {
channel.sendMessage("No cooldown provided").queue();
}
long newCd = Long.parseLong(args.get(0));
updateMuggedCd(ctx.getGuild().getIdLong(), newCd);
channel.sendMessageFormat("Mug victim cooldown has been set to `%s`", newCd).queue();
}
@Override
public String getName() {
return "setmuggedcd";
}
@Override
public String getHelp() {
return "Sets cooldown, in seconds, for how often users can be mugged";
}
private void updateMuggedCd(long guildId, long cd) {
EconomyHandler.MUG_VICTIM_COOLDOWNS.put(guildId, cd);
Connection connection = null;
try {
connection = SQLiteDataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
try (PreparedStatement statement =
connection
// language=SQLite
.prepareStatement("UPDATE guild_settings SET mug_victim_cd = ? WHERE guild_id = ?")) {
statement.setLong(1, cd);
statement.setString(2, String.valueOf(guildId));
statement.executeUpdate();
statement.closeOnCompletion();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 2,149 | 0.712424 | 0.709632 | 65 | 32.061539 | 24.820511 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 0 |
c1be60985ab70e5ea0fd2671527889549ff18aaa | 10,067,403,373,113 | 8e7fe482bfeba240d755b52500bbe8b55da36a38 | /java-programs/src/com/personal/java8features/Test.java | e89dd04d07963a6e66a1c59000869e9805acebac | []
| no_license | santoshhpgs/MY_REPO | https://github.com/santoshhpgs/MY_REPO | 91021a7412812f98ba152a4f8701ce76f6010f69 | 99316d7182212cca76c9b7154fc99a5d53918c66 | refs/heads/master | 2022-12-27T15:56:30.259000 | 2022-12-11T04:01:41 | 2022-12-11T04:04:27 | 158,778,959 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.personal.java8features;
public class Test {
public static void main(String[] args) {
/*
* Function<Integer,Integer> f=i->i*i; System.out.println("the square of 4 is :"
* +f.apply(4));
*/
/*
* String filter = "(listID contains '*rej*')";
* System.out.println(filter.split("contains")[1].replaceAll("\\)",
* "").replaceAll("\\'", "").replaceAll("\\*", "%").trim());
*/
/*
* Map<String,String> filterMap = new HashMap<>();
*
* if(filter.contains("and")) { String[] filtertokens = filter.split("and"); for
* (String tokens : filtertokens)
* filterMap.put(tokens.split("contains")[0].replaceAll("[^a-zA-Z0-9]", ""),
* tokens.split("contains")[1].replaceAll("\\)", "").replaceAll("\\'",
* "").replaceAll("\\*", "%")); }
*
* System.out.println("Map >>"+filterMap);
*/
// System.out.println(check.split("contains")[1].replaceAll("[^a-zA-Z0-9]",
// "%"));
// System.out.println(check.split("contains")[0]);
// String[] arrOfStr = check.split("contains:");
// System.out.println(check.split("contains:")[1].replaceAll("\\)",
// "").replaceAll("\\'", "").replace("*", "%"));
// System.out.println("STR >>"+check);
// String str = check.replaceAll("[^a-zA-Z0-9]", " ");
// System.out.println("STR >>"+str);
// replace("*", "%")
// for (String a : arrOfStr)
// System.out.println(a);
/*
* String str = "order.listID"; String[] arrOfStr = str.split("order.");
* System.out.println(arrOfStr.length); System.out.println(arrOfStr[1]);
*
* for (String a : arrOfStr) System.out.println(a);
*/
/*
* Map<String,Object> filterMap = new HashMap<String, Object>();
*
* int pageNum = 0; int pageSize = 20;
*
* filterMap.put("pageNum",pageNum); filterMap.put("pageSize",pageSize);
*/
/*
* String check = "order.modificationDetails.updatedBy"; String[] arrOfStr =
* check.split("\\."); System.out.println(arrOfStr.length);
* System.out.println(arrOfStr[arrOfStr.length-1]); for (String a : arrOfStr)
* System.out.println(a);
*/
/*
* Map<String,String> filterMap = new HashMap<>(); String filter =
* "((listID contains 'fsda') or (keyword contains 'fsda'))"; //String filter =
* "((listID contains '4343') and (updatedBy contains '4322'))"; String[]
* filtertokens = filter.split(" or "); for (String tokens : filtertokens) {
* System.out.println(tokens);
* filterMap.put(tokens.split("contains")[0].replaceAll("[^a-zA-Z0-9]", ""),
* tokens.split("contains")[1].replaceAll("\\)", "").replaceAll("\\'",
* "").replaceAll("\\*", "%").trim()); } System.out.println(filterMap);
*/
/*
* HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
*
* // Mapping string values to int keys hash_map.put(10, "Geeks");
* hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25,
* "Welcomes"); hash_map.put(30, "You"); System.out.println(hash_map);
* hash_map.remove(20); System.out.println(hash_map);
*/
/*
* List<Integer> al = new CopyOnWriteArrayList(); Object obj = al;
* System.out.println(obj.getClass().isInstance(obj));
*
* al.add(10); al.add(20); al.add(30); al.add(1); al.add(2);
* System.out.println(al); for(Integer i :al) { al.remove(i);
* System.out.println(al); }
*/
// String check = "order.updatedDate";
// System.out.println(check.split("order.")[1]);
/*
* String test = "Santosh"; String one = "%San"; String two = ""; String Three =
* ""; String four = ""; System.out.println(one.split("%")[1]);
* System.out.println(test.startsWith(one.split("%")[1]));
*/
// System.out.println(test.matches("San"));
// System.out.println(test.toLowerCase().replaceAll("[^a-zA-Z0-9]",""));
/*
* ArrayList al = new ArrayList(); al.add(1); al.add(2); al.add(3); al.add(4);
* al.add(5); System.out.println(al.stream().getClass().getName()); LocalDate ld
* = LocalDate.now(); System.out.println(ld);
*/
/*
* ArrayList al = new ArrayList(); al.add(1); al.add(2); al.add(3); al.add(4);
* al.add(5); System.out.println(al.stream().getClass().getName()); LocalDate ld
* = LocalDate.now(); System.out.println(ld);
*/
// normal execution
InterfA ia = new ClassA();
ia.methodA();
// lambda
InterfA ialamda = () -> System.out.println("method one execution....");
ialamda.methodA();
// normal excecution sum method
InterfB ib = new ClassB();
ib.sum(2, 3);
// lambda execution sum method
InterfB iblambda = (a, b) -> System.out.println("sum is >>" + (a + b));
iblambda.sum(2, 3);
// normal excecution sqr method
InterfC ic = new ClassC();
System.out.println("square is >" + ic.sqr(5));
// lambda execution sqr method
InterfC iclambda = (a) -> a * a;
System.out.println("square is >" + iclambda.sqr(5));
}
}
| UTF-8 | Java | 4,815 | java | Test.java | Java | [
{
"context": "pping string values to int keys hash_map.put(10, \"Geeks\");\n\t\t * hash_map.put(15, \"4\"); hash_map.put(20, \"",
"end": 2787,
"score": 0.9280341267585754,
"start": 2782,
"tag": "NAME",
"value": "Geeks"
},
{
"context": "\");\n\t\t * hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25,\n\t\t * \"Welcomes\"); hash_map.pu",
"end": 2842,
"score": 0.8733267784118652,
"start": 2837,
"tag": "NAME",
"value": "Geeks"
},
{
"context": "hash_map.put(20, \"Geeks\"); hash_map.put(25,\n\t\t * \"Welcomes\"); hash_map.put(30, \"You\"); System.out.println(ha",
"end": 2877,
"score": 0.6063710451126099,
"start": 2869,
"tag": "NAME",
"value": "Welcomes"
}
]
| null | []
| package com.personal.java8features;
public class Test {
public static void main(String[] args) {
/*
* Function<Integer,Integer> f=i->i*i; System.out.println("the square of 4 is :"
* +f.apply(4));
*/
/*
* String filter = "(listID contains '*rej*')";
* System.out.println(filter.split("contains")[1].replaceAll("\\)",
* "").replaceAll("\\'", "").replaceAll("\\*", "%").trim());
*/
/*
* Map<String,String> filterMap = new HashMap<>();
*
* if(filter.contains("and")) { String[] filtertokens = filter.split("and"); for
* (String tokens : filtertokens)
* filterMap.put(tokens.split("contains")[0].replaceAll("[^a-zA-Z0-9]", ""),
* tokens.split("contains")[1].replaceAll("\\)", "").replaceAll("\\'",
* "").replaceAll("\\*", "%")); }
*
* System.out.println("Map >>"+filterMap);
*/
// System.out.println(check.split("contains")[1].replaceAll("[^a-zA-Z0-9]",
// "%"));
// System.out.println(check.split("contains")[0]);
// String[] arrOfStr = check.split("contains:");
// System.out.println(check.split("contains:")[1].replaceAll("\\)",
// "").replaceAll("\\'", "").replace("*", "%"));
// System.out.println("STR >>"+check);
// String str = check.replaceAll("[^a-zA-Z0-9]", " ");
// System.out.println("STR >>"+str);
// replace("*", "%")
// for (String a : arrOfStr)
// System.out.println(a);
/*
* String str = "order.listID"; String[] arrOfStr = str.split("order.");
* System.out.println(arrOfStr.length); System.out.println(arrOfStr[1]);
*
* for (String a : arrOfStr) System.out.println(a);
*/
/*
* Map<String,Object> filterMap = new HashMap<String, Object>();
*
* int pageNum = 0; int pageSize = 20;
*
* filterMap.put("pageNum",pageNum); filterMap.put("pageSize",pageSize);
*/
/*
* String check = "order.modificationDetails.updatedBy"; String[] arrOfStr =
* check.split("\\."); System.out.println(arrOfStr.length);
* System.out.println(arrOfStr[arrOfStr.length-1]); for (String a : arrOfStr)
* System.out.println(a);
*/
/*
* Map<String,String> filterMap = new HashMap<>(); String filter =
* "((listID contains 'fsda') or (keyword contains 'fsda'))"; //String filter =
* "((listID contains '4343') and (updatedBy contains '4322'))"; String[]
* filtertokens = filter.split(" or "); for (String tokens : filtertokens) {
* System.out.println(tokens);
* filterMap.put(tokens.split("contains")[0].replaceAll("[^a-zA-Z0-9]", ""),
* tokens.split("contains")[1].replaceAll("\\)", "").replaceAll("\\'",
* "").replaceAll("\\*", "%").trim()); } System.out.println(filterMap);
*/
/*
* HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
*
* // Mapping string values to int keys hash_map.put(10, "Geeks");
* hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25,
* "Welcomes"); hash_map.put(30, "You"); System.out.println(hash_map);
* hash_map.remove(20); System.out.println(hash_map);
*/
/*
* List<Integer> al = new CopyOnWriteArrayList(); Object obj = al;
* System.out.println(obj.getClass().isInstance(obj));
*
* al.add(10); al.add(20); al.add(30); al.add(1); al.add(2);
* System.out.println(al); for(Integer i :al) { al.remove(i);
* System.out.println(al); }
*/
// String check = "order.updatedDate";
// System.out.println(check.split("order.")[1]);
/*
* String test = "Santosh"; String one = "%San"; String two = ""; String Three =
* ""; String four = ""; System.out.println(one.split("%")[1]);
* System.out.println(test.startsWith(one.split("%")[1]));
*/
// System.out.println(test.matches("San"));
// System.out.println(test.toLowerCase().replaceAll("[^a-zA-Z0-9]",""));
/*
* ArrayList al = new ArrayList(); al.add(1); al.add(2); al.add(3); al.add(4);
* al.add(5); System.out.println(al.stream().getClass().getName()); LocalDate ld
* = LocalDate.now(); System.out.println(ld);
*/
/*
* ArrayList al = new ArrayList(); al.add(1); al.add(2); al.add(3); al.add(4);
* al.add(5); System.out.println(al.stream().getClass().getName()); LocalDate ld
* = LocalDate.now(); System.out.println(ld);
*/
// normal execution
InterfA ia = new ClassA();
ia.methodA();
// lambda
InterfA ialamda = () -> System.out.println("method one execution....");
ialamda.methodA();
// normal excecution sum method
InterfB ib = new ClassB();
ib.sum(2, 3);
// lambda execution sum method
InterfB iblambda = (a, b) -> System.out.println("sum is >>" + (a + b));
iblambda.sum(2, 3);
// normal excecution sqr method
InterfC ic = new ClassC();
System.out.println("square is >" + ic.sqr(5));
// lambda execution sqr method
InterfC iclambda = (a) -> a * a;
System.out.println("square is >" + iclambda.sqr(5));
}
}
| 4,815 | 0.595016 | 0.579647 | 141 | 33.148937 | 29.564196 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.602837 | false | false | 0 |
fbfefc123daff87acfddbe4b0b782f745ea4f589 | 3,813,930,986,075 | 321f8fdee293915ed5dd3434d2190229a0a0bda4 | /app/src/main/java/com/inspektorat/kadelebak/view/kade_village/adapter/VillageAdapter.java | 43479c9649ec998c581fdf7b54c9b77ad56330fa | []
| no_license | sugengekosaputro/KADELebak | https://github.com/sugengekosaputro/KADELebak | 05178b7a14e952dabdd9acc2c9ad0522f269fbea | c084742480e033a7e9b12b1a889167ea58bf3a70 | refs/heads/master | 2021-06-30T06:57:03.938000 | 2020-11-30T01:52:20 | 2020-11-30T01:52:20 | 216,157,092 | 0 | 0 | null | false | 2020-11-29T05:28:57 | 2019-10-19T05:59:16 | 2020-11-27T03:40:08 | 2020-11-29T05:28:56 | 1,072 | 0 | 0 | 0 | Java | false | false | package com.inspektorat.kadelebak.view.kade_village.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import com.inspektorat.kadelebak.Constant;
import com.inspektorat.kadelebak.R;
import com.inspektorat.kadelebak.entity.InstitutionEntity;
import com.inspektorat.kadelebak.view.kade_support.adapter.SupportAdapter;
import com.inspektorat.kadelebak.view.kade_village.entity.Institution;
import com.inspektorat.kadelebak.view.kade_village.presenter.VillagePresenter;
import com.inspektorat.kadelebak.view.kade_village.view.DetailVillageActivity;
import com.inspektorat.kadelebak.view.kade_village.view.VillageView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class VillageAdapter extends RecyclerView.Adapter<VillageAdapter.ViewHolder> implements Filterable {
private Context context;
private List<InstitutionEntity> institutionList;
private List<InstitutionEntity> institutionFilter;
private VillageView.Detail detail;
private VillagePresenter presenter;
public VillageAdapter(Context context, List<InstitutionEntity> institutionList) {
this.context = context;
this.institutionList = institutionList;
this.institutionFilter = new ArrayList<>(institutionList);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_village, parent, false);
return new VillageAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
InstitutionEntity institution = institutionList.get(position);
holder.position = position;
holder.villageName.setText(institution.getName());
holder.cardView.setOnClickListener(view -> {
Bundle bundle = new Bundle();
Intent intent = new Intent(context, DetailVillageActivity.class);
bundle.putSerializable(Constant.SERIALIZABLE_VILLAGE, institution);
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
});
}
@Override
public int getItemCount() {
return (institutionList.size() > 0) ? institutionList.size() : 0;
}
private void setViewDetail(VillageView.Detail detail){
this.detail = detail;
}
@Override
public Filter getFilter() {
return filterList;
}
private Filter filterList = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<InstitutionEntity> filterList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
filterList.addAll(institutionFilter);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
for (InstitutionEntity item : institutionFilter) {
if (item.getName().toLowerCase().contains(filterPattern)) {
filterList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
institutionList.clear();
institutionList.addAll((List)filterResults.values);
notifyDataSetChanged();
}
};
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.cv_item_village)
CardView cardView;
@BindView(R.id.tv_item_village_name)
TextView villageName;
int position;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}
| UTF-8 | Java | 4,486 | java | VillageAdapter.java | Java | []
| null | []
| package com.inspektorat.kadelebak.view.kade_village.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import com.inspektorat.kadelebak.Constant;
import com.inspektorat.kadelebak.R;
import com.inspektorat.kadelebak.entity.InstitutionEntity;
import com.inspektorat.kadelebak.view.kade_support.adapter.SupportAdapter;
import com.inspektorat.kadelebak.view.kade_village.entity.Institution;
import com.inspektorat.kadelebak.view.kade_village.presenter.VillagePresenter;
import com.inspektorat.kadelebak.view.kade_village.view.DetailVillageActivity;
import com.inspektorat.kadelebak.view.kade_village.view.VillageView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class VillageAdapter extends RecyclerView.Adapter<VillageAdapter.ViewHolder> implements Filterable {
private Context context;
private List<InstitutionEntity> institutionList;
private List<InstitutionEntity> institutionFilter;
private VillageView.Detail detail;
private VillagePresenter presenter;
public VillageAdapter(Context context, List<InstitutionEntity> institutionList) {
this.context = context;
this.institutionList = institutionList;
this.institutionFilter = new ArrayList<>(institutionList);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_village, parent, false);
return new VillageAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
InstitutionEntity institution = institutionList.get(position);
holder.position = position;
holder.villageName.setText(institution.getName());
holder.cardView.setOnClickListener(view -> {
Bundle bundle = new Bundle();
Intent intent = new Intent(context, DetailVillageActivity.class);
bundle.putSerializable(Constant.SERIALIZABLE_VILLAGE, institution);
intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
});
}
@Override
public int getItemCount() {
return (institutionList.size() > 0) ? institutionList.size() : 0;
}
private void setViewDetail(VillageView.Detail detail){
this.detail = detail;
}
@Override
public Filter getFilter() {
return filterList;
}
private Filter filterList = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<InstitutionEntity> filterList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
filterList.addAll(institutionFilter);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
for (InstitutionEntity item : institutionFilter) {
if (item.getName().toLowerCase().contains(filterPattern)) {
filterList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
institutionList.clear();
institutionList.addAll((List)filterResults.values);
notifyDataSetChanged();
}
};
public class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.cv_item_village)
CardView cardView;
@BindView(R.id.tv_item_village_name)
TextView villageName;
int position;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}
| 4,486 | 0.695274 | 0.694605 | 129 | 33.775192 | 27.031202 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604651 | false | false | 0 |
dd2ebf911b136866ed0d068a8a9709e7a92044ce | 27,453,430,966,601 | 61f511c9bf0db1a9685ec1a82642d817d8a76bd0 | /src/vista/vistaRegistrar2.java | 956bee67b71062c07ff55835927bc08791e8051f | []
| no_license | ItzelRendon/Fleetock2.0 | https://github.com/ItzelRendon/Fleetock2.0 | bd8086a09e89ff3bf8926605e2618f20368470a5 | c2711118161772d9fe83d3a555e904820873bd13 | refs/heads/master | 2020-03-22T04:02:45.356000 | 2018-07-28T15:21:02 | 2018-07-28T15:21:02 | 139,469,114 | 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 vista;
/**
*
* @author Holi
*/
public class vistaRegistrar2 extends javax.swing.JPanel {
/**
* Creates new form x
*/
public vistaRegistrar2() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel3 = new javax.swing.JPanel();
chbx_Playa = new javax.swing.JCheckBox();
chbx_Montania = new javax.swing.JCheckBox();
chbx_Desierto = new javax.swing.JCheckBox();
chbx_Bosque = new javax.swing.JCheckBox();
chbx_Selva = new javax.swing.JCheckBox();
chbx_sabana = new javax.swing.JCheckBox();
chbx_manglar = new javax.swing.JCheckBox();
chbx_glaciar = new javax.swing.JCheckBox();
chbx_ciudad = new javax.swing.JCheckBox();
btn_listo = new javax.swing.JButton();
lbl_Playa1 = new javax.swing.JLabel();
lbl_Playa3 = new javax.swing.JLabel();
lbl_Playa7 = new javax.swing.JLabel();
lbl_Playa8 = new javax.swing.JLabel();
lbl_Playa9 = new javax.swing.JLabel();
lbl_Playa10 = new javax.swing.JLabel();
lbl_Playa11 = new javax.swing.JLabel();
lbl_Playa12 = new javax.swing.JLabel();
lbl_Playa13 = new javax.swing.JLabel();
lblHora = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
jLabel5.setText("Seleccione sus preferencias de destino");
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
chbx_Playa.setBackground(new java.awt.Color(255, 255, 255));
chbx_Playa.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Playa.setText("Playa");
chbx_Playa.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Playa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_PlayaActionPerformed(evt);
}
});
chbx_Montania.setBackground(new java.awt.Color(255, 255, 255));
chbx_Montania.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Montania.setText("Montaña");
chbx_Montania.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Montania.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_MontaniaActionPerformed(evt);
}
});
chbx_Desierto.setBackground(new java.awt.Color(255, 255, 255));
chbx_Desierto.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Desierto.setText("Desierto");
chbx_Desierto.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Desierto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_DesiertoActionPerformed(evt);
}
});
chbx_Bosque.setBackground(new java.awt.Color(255, 255, 255));
chbx_Bosque.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Bosque.setText("Bosque");
chbx_Bosque.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Bosque.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_BosqueActionPerformed(evt);
}
});
chbx_Selva.setBackground(new java.awt.Color(255, 255, 255));
chbx_Selva.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Selva.setText("Selva");
chbx_Selva.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Selva.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_SelvaActionPerformed(evt);
}
});
chbx_sabana.setBackground(new java.awt.Color(255, 255, 255));
chbx_sabana.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_sabana.setText("Sabana");
chbx_sabana.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_sabana.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_sabanaActionPerformed(evt);
}
});
chbx_manglar.setBackground(new java.awt.Color(255, 255, 255));
chbx_manglar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_manglar.setText("Manglar");
chbx_manglar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_manglar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_manglarActionPerformed(evt);
}
});
chbx_glaciar.setBackground(new java.awt.Color(255, 255, 255));
chbx_glaciar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_glaciar.setText("Glaciar");
chbx_glaciar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_glaciar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_glaciarActionPerformed(evt);
}
});
chbx_ciudad.setBackground(new java.awt.Color(255, 255, 255));
chbx_ciudad.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_ciudad.setText("Ciudad");
chbx_ciudad.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_ciudad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_ciudadActionPerformed(evt);
}
});
btn_listo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/listo.jpg"))); // NOI18N
btn_listo.setText("¡Listo!");
lbl_Playa1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/MONTAÑA.png"))); // NOI18N
lbl_Playa1.setToolTipText("");
lbl_Playa3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/DESIERTO.png"))); // NOI18N
lbl_Playa3.setToolTipText("");
lbl_Playa7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/chango.png"))); // NOI18N
lbl_Playa7.setToolTipText("");
lbl_Playa8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/manglar1.png"))); // NOI18N
lbl_Playa8.setToolTipText("");
lbl_Playa9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/BOSQUE.png"))); // NOI18N
lbl_Playa9.setToolTipText("");
lbl_Playa10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/CIUDAD.png"))); // NOI18N
lbl_Playa10.setToolTipText("");
lbl_Playa11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/GLACIAR.png"))); // NOI18N
lbl_Playa11.setToolTipText("");
lbl_Playa12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/PLAYA.png"))); // NOI18N
lbl_Playa12.setToolTipText("");
lbl_Playa13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/tigre.png"))); // NOI18N
lbl_Playa13.setToolTipText("");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(lbl_Playa12, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(chbx_Selva, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_Playa7, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(chbx_Playa, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa11, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_glaciar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(chbx_Montania, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_Playa1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(70, 70, 70)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_Desierto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_Bosque, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(70, 70, 70)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa10, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa13, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_sabana, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa8, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_manglar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(197, 197, 197)))
.addGap(30, 30, 30))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(227, 227, 227)
.addComponent(btn_listo, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa12, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(chbx_Montania)
.addComponent(chbx_Playa)
.addComponent(chbx_Desierto))
.addGap(48, 48, 48)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa11, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chbx_glaciar))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(chbx_Bosque)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa10, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chbx_ciudad)))
.addGap(32, 32, 32)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa8, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa7, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chbx_manglar)
.addComponent(chbx_Selva)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa13, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(chbx_sabana)))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(btn_listo, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(24, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jScrollPane1.setViewportView(jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(122, Short.MAX_VALUE)
.addComponent(jLabel5)
.addGap(115, 115, 115))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void chbx_PlayaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_PlayaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_PlayaActionPerformed
private void chbx_MontaniaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_MontaniaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_MontaniaActionPerformed
private void chbx_DesiertoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_DesiertoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_DesiertoActionPerformed
private void chbx_BosqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_BosqueActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_BosqueActionPerformed
private void chbx_SelvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_SelvaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_SelvaActionPerformed
private void chbx_sabanaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_sabanaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_sabanaActionPerformed
private void chbx_manglarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_manglarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_manglarActionPerformed
private void chbx_glaciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_glaciarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_glaciarActionPerformed
private void chbx_ciudadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_ciudadActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_ciudadActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btn_listo;
public javax.swing.JCheckBox chbx_Bosque;
public javax.swing.JCheckBox chbx_Desierto;
public javax.swing.JCheckBox chbx_Montania;
public javax.swing.JCheckBox chbx_Playa;
public javax.swing.JCheckBox chbx_Selva;
public javax.swing.JCheckBox chbx_ciudad;
public javax.swing.JCheckBox chbx_glaciar;
public javax.swing.JCheckBox chbx_manglar;
public javax.swing.JCheckBox chbx_sabana;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JLabel lblHora;
public javax.swing.JLabel lbl_Playa1;
public javax.swing.JLabel lbl_Playa10;
public javax.swing.JLabel lbl_Playa11;
public javax.swing.JLabel lbl_Playa12;
public javax.swing.JLabel lbl_Playa13;
public javax.swing.JLabel lbl_Playa3;
public javax.swing.JLabel lbl_Playa7;
public javax.swing.JLabel lbl_Playa8;
public javax.swing.JLabel lbl_Playa9;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 23,381 | java | vistaRegistrar2.java | Java | [
{
"context": " the editor.\n */\npackage vista;\n\n/**\n *\n * @author Holi\n */\npublic class vistaRegistrar2 extends javax",
"end": 220,
"score": 0.8507441878318787,
"start": 219,
"tag": "NAME",
"value": "H"
},
{
"context": "he editor.\n */\npackage vista;\n\n/**\n *\n * @author Holi\n */\npublic class vistaRegistrar2 extends javax.sw",
"end": 223,
"score": 0.8247761130332947,
"start": 220,
"tag": "USERNAME",
"value": "oli"
}
]
| 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 vista;
/**
*
* @author Holi
*/
public class vistaRegistrar2 extends javax.swing.JPanel {
/**
* Creates new form x
*/
public vistaRegistrar2() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jPanel3 = new javax.swing.JPanel();
chbx_Playa = new javax.swing.JCheckBox();
chbx_Montania = new javax.swing.JCheckBox();
chbx_Desierto = new javax.swing.JCheckBox();
chbx_Bosque = new javax.swing.JCheckBox();
chbx_Selva = new javax.swing.JCheckBox();
chbx_sabana = new javax.swing.JCheckBox();
chbx_manglar = new javax.swing.JCheckBox();
chbx_glaciar = new javax.swing.JCheckBox();
chbx_ciudad = new javax.swing.JCheckBox();
btn_listo = new javax.swing.JButton();
lbl_Playa1 = new javax.swing.JLabel();
lbl_Playa3 = new javax.swing.JLabel();
lbl_Playa7 = new javax.swing.JLabel();
lbl_Playa8 = new javax.swing.JLabel();
lbl_Playa9 = new javax.swing.JLabel();
lbl_Playa10 = new javax.swing.JLabel();
lbl_Playa11 = new javax.swing.JLabel();
lbl_Playa12 = new javax.swing.JLabel();
lbl_Playa13 = new javax.swing.JLabel();
lblHora = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
jLabel5.setText("Seleccione sus preferencias de destino");
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
chbx_Playa.setBackground(new java.awt.Color(255, 255, 255));
chbx_Playa.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Playa.setText("Playa");
chbx_Playa.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Playa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_PlayaActionPerformed(evt);
}
});
chbx_Montania.setBackground(new java.awt.Color(255, 255, 255));
chbx_Montania.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Montania.setText("Montaña");
chbx_Montania.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Montania.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_MontaniaActionPerformed(evt);
}
});
chbx_Desierto.setBackground(new java.awt.Color(255, 255, 255));
chbx_Desierto.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Desierto.setText("Desierto");
chbx_Desierto.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Desierto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_DesiertoActionPerformed(evt);
}
});
chbx_Bosque.setBackground(new java.awt.Color(255, 255, 255));
chbx_Bosque.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Bosque.setText("Bosque");
chbx_Bosque.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Bosque.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_BosqueActionPerformed(evt);
}
});
chbx_Selva.setBackground(new java.awt.Color(255, 255, 255));
chbx_Selva.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_Selva.setText("Selva");
chbx_Selva.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_Selva.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_SelvaActionPerformed(evt);
}
});
chbx_sabana.setBackground(new java.awt.Color(255, 255, 255));
chbx_sabana.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_sabana.setText("Sabana");
chbx_sabana.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_sabana.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_sabanaActionPerformed(evt);
}
});
chbx_manglar.setBackground(new java.awt.Color(255, 255, 255));
chbx_manglar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_manglar.setText("Manglar");
chbx_manglar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_manglar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_manglarActionPerformed(evt);
}
});
chbx_glaciar.setBackground(new java.awt.Color(255, 255, 255));
chbx_glaciar.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_glaciar.setText("Glaciar");
chbx_glaciar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_glaciar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_glaciarActionPerformed(evt);
}
});
chbx_ciudad.setBackground(new java.awt.Color(255, 255, 255));
chbx_ciudad.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
chbx_ciudad.setText("Ciudad");
chbx_ciudad.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
chbx_ciudad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbx_ciudadActionPerformed(evt);
}
});
btn_listo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/listo.jpg"))); // NOI18N
btn_listo.setText("¡Listo!");
lbl_Playa1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/MONTAÑA.png"))); // NOI18N
lbl_Playa1.setToolTipText("");
lbl_Playa3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/DESIERTO.png"))); // NOI18N
lbl_Playa3.setToolTipText("");
lbl_Playa7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/chango.png"))); // NOI18N
lbl_Playa7.setToolTipText("");
lbl_Playa8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/manglar1.png"))); // NOI18N
lbl_Playa8.setToolTipText("");
lbl_Playa9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/BOSQUE.png"))); // NOI18N
lbl_Playa9.setToolTipText("");
lbl_Playa10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/CIUDAD.png"))); // NOI18N
lbl_Playa10.setToolTipText("");
lbl_Playa11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/GLACIAR.png"))); // NOI18N
lbl_Playa11.setToolTipText("");
lbl_Playa12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/PLAYA.png"))); // NOI18N
lbl_Playa12.setToolTipText("");
lbl_Playa13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lbl_Playa13.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/destinos/tigre.png"))); // NOI18N
lbl_Playa13.setToolTipText("");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(lbl_Playa12, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(chbx_Selva, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_Playa7, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(chbx_Playa, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa11, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_glaciar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(chbx_Montania, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lbl_Playa1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(70, 70, 70)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_Desierto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_Bosque, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(70, 70, 70)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lbl_Playa10, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa13, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_sabana, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa8, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbx_manglar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(197, 197, 197)))
.addGap(30, 30, 30))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(227, 227, 227)
.addComponent(btn_listo, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa12, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(chbx_Montania)
.addComponent(chbx_Playa)
.addComponent(chbx_Desierto))
.addGap(48, 48, 48)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa11, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chbx_glaciar))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(chbx_Bosque)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa10, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chbx_ciudad)))
.addGap(32, 32, 32)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_Playa8, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lbl_Playa7, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(chbx_manglar)
.addComponent(chbx_Selva)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(lbl_Playa13, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(chbx_sabana)))
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(btn_listo, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(24, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
jScrollPane1.setViewportView(jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(122, Short.MAX_VALUE)
.addComponent(jLabel5)
.addGap(115, 115, 115))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel5)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void chbx_PlayaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_PlayaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_PlayaActionPerformed
private void chbx_MontaniaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_MontaniaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_MontaniaActionPerformed
private void chbx_DesiertoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_DesiertoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_DesiertoActionPerformed
private void chbx_BosqueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_BosqueActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_BosqueActionPerformed
private void chbx_SelvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_SelvaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_SelvaActionPerformed
private void chbx_sabanaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_sabanaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_sabanaActionPerformed
private void chbx_manglarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_manglarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_manglarActionPerformed
private void chbx_glaciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_glaciarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_glaciarActionPerformed
private void chbx_ciudadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbx_ciudadActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_chbx_ciudadActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JButton btn_listo;
public javax.swing.JCheckBox chbx_Bosque;
public javax.swing.JCheckBox chbx_Desierto;
public javax.swing.JCheckBox chbx_Montania;
public javax.swing.JCheckBox chbx_Playa;
public javax.swing.JCheckBox chbx_Selva;
public javax.swing.JCheckBox chbx_ciudad;
public javax.swing.JCheckBox chbx_glaciar;
public javax.swing.JCheckBox chbx_manglar;
public javax.swing.JCheckBox chbx_sabana;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JLabel lblHora;
public javax.swing.JLabel lbl_Playa1;
public javax.swing.JLabel lbl_Playa10;
public javax.swing.JLabel lbl_Playa11;
public javax.swing.JLabel lbl_Playa12;
public javax.swing.JLabel lbl_Playa13;
public javax.swing.JLabel lbl_Playa3;
public javax.swing.JLabel lbl_Playa7;
public javax.swing.JLabel lbl_Playa8;
public javax.swing.JLabel lbl_Playa9;
// End of variables declaration//GEN-END:variables
}
| 23,381 | 0.664599 | 0.642698 | 381 | 60.359581 | 42.039032 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.892388 | false | false | 0 |
cd89ce55efa4ee3cbf4be7e9836971f0225136a2 | 4,801,773,506,813 | 091663f3a19dcf244b9495a411bd5cb0ba50d18e | /src/main/java/com/api/practica/ingreso/IngresoBusiness.java | cd253d1ed1c0f7a1c0dd39d61c7c2f3269a29372 | []
| no_license | danielchungara1/api-practica | https://github.com/danielchungara1/api-practica | 607a382c5eb5109ad887aba334410a5da0d464a2 | 17ee7bfd4cede2aeadda551882fff28bed1fd806 | refs/heads/develop | 2022-07-08T13:54:01.238000 | 2020-04-21T01:31:03 | 2020-04-21T01:31:03 | 248,388,001 | 0 | 0 | null | false | 2022-01-21T23:40:20 | 2020-03-19T02:02:47 | 2020-04-21T01:31:26 | 2022-01-21T23:40:20 | 141 | 0 | 0 | 3 | Java | false | false | package com.api.practica.ingreso;
import com.api.practica.commons.ModelMapperWrapper;
import com.api.practica.exceptions.CredencialesInvalidasException;
import com.api.practica.exceptions.CustomException;
import com.api.practica.exceptions.EmailExistenteException;
import com.api.practica.security.JwtTokenProvider;
import com.api.practica.roles.Rol;
import com.api.practica.roles.RolRepository;
import com.api.practica.usuario.Usuario;
import com.api.practica.usuario.UsuarioRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class IngresoBusiness {
private static final Long ROL_USUARIO = Long.valueOf(2);
@Autowired
private UsuarioRepository usuarioRepository;
@Autowired
private RolRepository rolRepository;
@Autowired
private ModelMapperWrapper modelMapper;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtTokenProvider jwtTokenProvider;
public TokenDto autenticar(CredencialesDto usuario) {
Optional<Usuario> u = this.usuarioRepository.findByEmail(usuario.getEmail());
if (!u.isPresent()) {
throw new CredencialesInvalidasException("Usuario invalido.");
}
Usuario usuarioBd = u.get();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(usuario.getEmail(), usuario.getPassword()));
String token = jwtTokenProvider.createToken(usuarioBd.getEmail(), usuarioBd.getRoles());
TokenDto response = new TokenDto();
response.setToken(token);
return response;
} catch (AuthenticationException e) {
throw new CustomException("Usuario o contraseña invalidos.", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
public void registrar(CredencialesDto credencialesDto) {
if (this.usuarioRepository.existsByEmail(credencialesDto.getEmail())){
throw new EmailExistenteException("El email ingresado no esta disponible.");
}
credencialesDto.setPassword(passwordEncoder.encode(credencialesDto.getPassword()));
Usuario usuarioNuevo = modelMapper.map(credencialesDto, Usuario.class);
Rol rolUsuario = this.rolRepository.findById(ROL_USUARIO).get();
List<Rol> roles = new ArrayList<>();
roles.add(rolUsuario);
usuarioNuevo.setRoles(roles);
this.usuarioRepository.save(usuarioNuevo);
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public JwtTokenProvider getJwtTokenProvider() {
return jwtTokenProvider;
}
public void setJwtTokenProvider(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
public PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public UsuarioRepository getUsuarioRepository() {
return usuarioRepository;
}
public void setUsuarioRepository(UsuarioRepository usuarioRepository) {
this.usuarioRepository = usuarioRepository;
}
public ModelMapperWrapper getModelMapper() {
return modelMapper;
}
public void setModelMapper(ModelMapperWrapper modelMapper) {
this.modelMapper = modelMapper;
}
}
| UTF-8 | Java | 4,132 | java | IngresoBusiness.java | Java | []
| null | []
| package com.api.practica.ingreso;
import com.api.practica.commons.ModelMapperWrapper;
import com.api.practica.exceptions.CredencialesInvalidasException;
import com.api.practica.exceptions.CustomException;
import com.api.practica.exceptions.EmailExistenteException;
import com.api.practica.security.JwtTokenProvider;
import com.api.practica.roles.Rol;
import com.api.practica.roles.RolRepository;
import com.api.practica.usuario.Usuario;
import com.api.practica.usuario.UsuarioRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class IngresoBusiness {
private static final Long ROL_USUARIO = Long.valueOf(2);
@Autowired
private UsuarioRepository usuarioRepository;
@Autowired
private RolRepository rolRepository;
@Autowired
private ModelMapperWrapper modelMapper;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private JwtTokenProvider jwtTokenProvider;
public TokenDto autenticar(CredencialesDto usuario) {
Optional<Usuario> u = this.usuarioRepository.findByEmail(usuario.getEmail());
if (!u.isPresent()) {
throw new CredencialesInvalidasException("Usuario invalido.");
}
Usuario usuarioBd = u.get();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(usuario.getEmail(), usuario.getPassword()));
String token = jwtTokenProvider.createToken(usuarioBd.getEmail(), usuarioBd.getRoles());
TokenDto response = new TokenDto();
response.setToken(token);
return response;
} catch (AuthenticationException e) {
throw new CustomException("Usuario o contraseña invalidos.", HttpStatus.UNPROCESSABLE_ENTITY);
}
}
public void registrar(CredencialesDto credencialesDto) {
if (this.usuarioRepository.existsByEmail(credencialesDto.getEmail())){
throw new EmailExistenteException("El email ingresado no esta disponible.");
}
credencialesDto.setPassword(passwordEncoder.encode(credencialesDto.getPassword()));
Usuario usuarioNuevo = modelMapper.map(credencialesDto, Usuario.class);
Rol rolUsuario = this.rolRepository.findById(ROL_USUARIO).get();
List<Rol> roles = new ArrayList<>();
roles.add(rolUsuario);
usuarioNuevo.setRoles(roles);
this.usuarioRepository.save(usuarioNuevo);
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public JwtTokenProvider getJwtTokenProvider() {
return jwtTokenProvider;
}
public void setJwtTokenProvider(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
public PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public UsuarioRepository getUsuarioRepository() {
return usuarioRepository;
}
public void setUsuarioRepository(UsuarioRepository usuarioRepository) {
this.usuarioRepository = usuarioRepository;
}
public ModelMapperWrapper getModelMapper() {
return modelMapper;
}
public void setModelMapper(ModelMapperWrapper modelMapper) {
this.modelMapper = modelMapper;
}
}
| 4,132 | 0.743161 | 0.742919 | 130 | 30.776922 | 30.156328 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.446154 | false | false | 0 |
4266a6f887e5145419cb0a191abed040909fd7d0 | 21,827,023,842,419 | 441b16d5861b8239644007c3b64d56bdfd67bb92 | /plugins/org.eclipse.osee.jaxrs.server/src/org/eclipse/osee/jaxrs/server/internal/security/util/OseePrincipalImpl.java | 2d272836f5299cbcd47f5a40bffc63bd2746b327 | []
| no_license | sec00/osee-4 | https://github.com/sec00/osee-4 | baf9713306c7bfd6f5a12a153acb083bbdb2ce77 | 4644522f12d0e2a887434d09dffa55d32ed45f15 | refs/heads/master | 2021-05-19T04:04:07.608000 | 2018-11-15T23:29:55 | 2018-11-15T23:31:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (c) 2015 Boeing.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Boeing - initial API and implementation
*******************************************************************************/
package org.eclipse.osee.jaxrs.server.internal.security.util;
import java.util.Map;
import java.util.Set;
import org.eclipse.osee.framework.jdk.core.type.BaseIdentity;
import org.eclipse.osee.framework.jdk.core.type.OseePrincipal;
import org.eclipse.osee.framework.jdk.core.util.Strings;
/**
* @author Roberto E. Escobar
*/
public class OseePrincipalImpl extends BaseIdentity<Long>implements OseePrincipal {
private final String displayName;
private final String email;
private final String login;
private final String name;
private final String username;
private final boolean active;
private final boolean authenticated;
private final Set<String> roles;
private final Map<String, String> props;
public OseePrincipalImpl(Long uuid, String displayName, String email, String login, String name, String username, boolean active, boolean authenticated, Set<String> roles, Map<String, String> props) {
super(uuid);
this.displayName = displayName;
this.email = email;
this.login = login;
this.name = name;
this.username = username;
this.active = active;
this.authenticated = authenticated;
this.roles = roles;
this.props = props;
}
@Override
public String getName() {
return name;
}
@Override
public String getLogin() {
return login;
}
@Override
public Set<String> getRoles() {
return roles;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getUserName() {
return username;
}
@Override
public String getEmailAddress() {
return email;
}
@Override
public boolean isActive() {
return active;
}
@Override
public boolean isAuthenticated() {
return authenticated;
}
@Override
public Map<String, String> getProperties() {
return props;
}
@Override
public String getOseeGuid() {
String toReturn = "N/A";
if (props != null) {
String value = props.get("osee.guid");
if (Strings.isValid(value)) {
toReturn = value;
}
}
return toReturn;
}
}
| UTF-8 | Java | 2,688 | java | OseePrincipalImpl.java | Java | [
{
"context": ".org/legal/epl-v10.html\n *\n * Contributors:\n * Boeing - initial API and implementation\n ***************",
"end": 390,
"score": 0.9917962551116943,
"start": 384,
"tag": "NAME",
"value": "Boeing"
},
{
"context": "e.framework.jdk.core.util.Strings;\n\n/**\n * @author Roberto E. Escobar\n */\npublic class OseePrincipalImpl extends BaseId",
"end": 829,
"score": 0.9998853802680969,
"start": 811,
"tag": "NAME",
"value": "Roberto E. Escobar"
},
{
"context": "gin;\n this.name = name;\n this.username = username;\n this.active = active;\n this.authentic",
"end": 1603,
"score": 0.9915761947631836,
"start": 1595,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ride\n public String getUserName() {\n return username;\n }\n\n @Override\n public String getEmailAddr",
"end": 2091,
"score": 0.919761061668396,
"start": 2083,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| /*******************************************************************************
* Copyright (c) 2015 Boeing.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Boeing - initial API and implementation
*******************************************************************************/
package org.eclipse.osee.jaxrs.server.internal.security.util;
import java.util.Map;
import java.util.Set;
import org.eclipse.osee.framework.jdk.core.type.BaseIdentity;
import org.eclipse.osee.framework.jdk.core.type.OseePrincipal;
import org.eclipse.osee.framework.jdk.core.util.Strings;
/**
* @author <NAME>
*/
public class OseePrincipalImpl extends BaseIdentity<Long>implements OseePrincipal {
private final String displayName;
private final String email;
private final String login;
private final String name;
private final String username;
private final boolean active;
private final boolean authenticated;
private final Set<String> roles;
private final Map<String, String> props;
public OseePrincipalImpl(Long uuid, String displayName, String email, String login, String name, String username, boolean active, boolean authenticated, Set<String> roles, Map<String, String> props) {
super(uuid);
this.displayName = displayName;
this.email = email;
this.login = login;
this.name = name;
this.username = username;
this.active = active;
this.authenticated = authenticated;
this.roles = roles;
this.props = props;
}
@Override
public String getName() {
return name;
}
@Override
public String getLogin() {
return login;
}
@Override
public Set<String> getRoles() {
return roles;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public String getUserName() {
return username;
}
@Override
public String getEmailAddress() {
return email;
}
@Override
public boolean isActive() {
return active;
}
@Override
public boolean isAuthenticated() {
return authenticated;
}
@Override
public Map<String, String> getProperties() {
return props;
}
@Override
public String getOseeGuid() {
String toReturn = "N/A";
if (props != null) {
String value = props.get("osee.guid");
if (Strings.isValid(value)) {
toReturn = value;
}
}
return toReturn;
}
}
| 2,676 | 0.63244 | 0.629464 | 103 | 25.097088 | 26.721329 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.495146 | false | false | 0 |
ec67f489c2a811fa87d04816bdcc84f684e37f8e | 11,991,548,751,007 | 247930cd0816cac253bf6e050cf7b200b4ff195f | /src/main/java/com/pay/framework/util/PropertiesUtils.java | b6075340bd4414fe675e00f05904444da9419156 | []
| no_license | wangjiesheng/PayProject | https://github.com/wangjiesheng/PayProject | b3f9b9aa2e7a9660f8787ccabdacf89202110545 | c03f59c2a4834cc74bdb272da9d3c218b3a4d8cc | refs/heads/master | 2021-01-12T09:40:24.744000 | 2016-12-12T07:09:26 | 2016-12-12T07:09:26 | 76,230,165 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* 上海尤恩信息技术有限公司
* (c) Copyright 2015-2020 uenpay
* http://www.uenpay.com/
* FILENAME : PropertiesUtils.java
* PACKAGE : com.uenpay.porter.utils
* CREATE DATE : 2016年3月7日
* AUTHOR : chenbing
* MODIFIED BY :
* DESCRIPTION :
*/
package com.pay.framework.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.pay.entity.UenpayConstant;
/**
* @author chenbing
* Specification : 文档说明
*/
public class PropertiesUtils {
/**
* logger
*/
private static Logger log = LogManager.getLogger(PropertiesUtils.class);
private static Properties properties = new Properties();
static {
InputStream fis = null;
String configPath = null;
try {
String fileSeparator = System.getProperty(UenpayConstant.FILE_SEPARATOR);
String userHomedir = System.getProperty(UenpayConstant.USER_HOME);
configPath = userHomedir + fileSeparator + "payment-configure.properties";
log.debug("configure.properties配置文件的路径:"+configPath);
fis = new FileInputStream(configPath);
properties.load(fis);
} catch (Exception e) {
log.error("请检查payment-configure.properties是否在"+configPath+"路径下");
throw new Error(e);
}finally{
if(null != fis){
try {
fis.close();
} catch (IOException e) {
}
}
}
}
/**
* 获得属性里面的值
*
* @param key
* @return
*/
public static String getPropertiesVal(String key) {
return properties.getProperty(key);
}
}
| UTF-8 | Java | 1,672 | java | PropertiesUtils.java | Java | [
{
"context": " * CREATE DATE : 2016年3月7日\n * AUTHOR : chenbing\n * MODIFIED BY :\n *\t DESCRIPTION :\n */\npackag",
"end": 229,
"score": 0.9994731545448303,
"start": 221,
"tag": "USERNAME",
"value": "chenbing"
},
{
"context": "ort com.pay.entity.UenpayConstant;\n\n/**\n * @author chenbing\n * Specification : 文档说明\n */\npublic class Properti",
"end": 571,
"score": 0.9994118809700012,
"start": 563,
"tag": "USERNAME",
"value": "chenbing"
}
]
| null | []
| /**
* 上海尤恩信息技术有限公司
* (c) Copyright 2015-2020 uenpay
* http://www.uenpay.com/
* FILENAME : PropertiesUtils.java
* PACKAGE : com.uenpay.porter.utils
* CREATE DATE : 2016年3月7日
* AUTHOR : chenbing
* MODIFIED BY :
* DESCRIPTION :
*/
package com.pay.framework.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.pay.entity.UenpayConstant;
/**
* @author chenbing
* Specification : 文档说明
*/
public class PropertiesUtils {
/**
* logger
*/
private static Logger log = LogManager.getLogger(PropertiesUtils.class);
private static Properties properties = new Properties();
static {
InputStream fis = null;
String configPath = null;
try {
String fileSeparator = System.getProperty(UenpayConstant.FILE_SEPARATOR);
String userHomedir = System.getProperty(UenpayConstant.USER_HOME);
configPath = userHomedir + fileSeparator + "payment-configure.properties";
log.debug("configure.properties配置文件的路径:"+configPath);
fis = new FileInputStream(configPath);
properties.load(fis);
} catch (Exception e) {
log.error("请检查payment-configure.properties是否在"+configPath+"路径下");
throw new Error(e);
}finally{
if(null != fis){
try {
fis.close();
} catch (IOException e) {
}
}
}
}
/**
* 获得属性里面的值
*
* @param key
* @return
*/
public static String getPropertiesVal(String key) {
return properties.getProperty(key);
}
}
| 1,672 | 0.689786 | 0.679697 | 69 | 21.985508 | 20.677996 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.449275 | false | false | 0 |
0792075bad38bb3cb054544fb1774aa951dd3fea | 9,328,669,014,174 | 5ce1818d4622d5b5a64bb7f06fcc1da399a70003 | /213-HouseRobberII/Solution.java | 6c2ccf5f5f96c985eab646d258a513a5d6c255fa | []
| no_license | CHANGLI0914/LeetCode_G-C | https://github.com/CHANGLI0914/LeetCode_G-C | 11558b16b033bc50de17b054d38595507c2804ed | 1d38b0ee6e1c786f3c6dd7b72c149341fbf0e0db | refs/heads/master | 2020-12-29T01:42:43.852000 | 2020-12-23T21:59:36 | 2020-12-23T21:59:36 | 47,421,049 | 3 | 2 | null | false | 2015-12-18T13:26:08 | 2015-12-04T18:10:00 | 2015-12-10T07:35:49 | 2015-12-18T13:26:08 | 68 | 1 | 1 | 0 | Java | null | null | /**
* 213. House Robber II
* Tag: DP
* A simple follow up of House Robber. Classic DP problem.
* Chang Li at UC San Diego
* Feb. 21, 2016
*/
public class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
return Math.max(simpleRob(nums, 2, nums.length-2)+nums[0], simpleRob(nums, 1, nums.length-1));
}
/* Recursion Function: f(nums, start, end) = max(f(nums, start+2, end)+nums[start], f(nums, start+1, end)) */
public int simpleRob(int[] nums, int start, int end) {
if (end < start) {
return 0;
} else {
int second = 0;
int first = nums[end];
// Recursion by DP. ONLY USE O(1) SPACE!
int pos = end - start - 1;
while (pos >= 0) {
// Move forward 2 houses each time
// Or we can move forward 1 house each time and swap first and second
second = Math.max(first, nums[start+pos] + second);
first = Math.max(second, nums[start+pos-1] + first);
pos -= 2;
}
return (pos == -1) ? first : second;
}
}
public int simpleRob_On(int[] nums, int start, int end) {
if (end < start) {
return 0;
} else {
int[] table = new int[end - start + 1 + 1];
table[end - start + 1] = 0;
table[end - start] = nums[end];
// Recursion by DP
int pos = end - start - 1;
while (pos >= 0) {
table[pos] = Math.max((nums[start+pos] + table[pos+2]), table[pos+1]);
pos --;
}
return table[0];
}
}
}
| UTF-8 | Java | 1,730 | java | Solution.java | Java | []
| null | []
| /**
* 213. House Robber II
* Tag: DP
* A simple follow up of House Robber. Classic DP problem.
* Chang Li at UC San Diego
* Feb. 21, 2016
*/
public class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
return Math.max(simpleRob(nums, 2, nums.length-2)+nums[0], simpleRob(nums, 1, nums.length-1));
}
/* Recursion Function: f(nums, start, end) = max(f(nums, start+2, end)+nums[start], f(nums, start+1, end)) */
public int simpleRob(int[] nums, int start, int end) {
if (end < start) {
return 0;
} else {
int second = 0;
int first = nums[end];
// Recursion by DP. ONLY USE O(1) SPACE!
int pos = end - start - 1;
while (pos >= 0) {
// Move forward 2 houses each time
// Or we can move forward 1 house each time and swap first and second
second = Math.max(first, nums[start+pos] + second);
first = Math.max(second, nums[start+pos-1] + first);
pos -= 2;
}
return (pos == -1) ? first : second;
}
}
public int simpleRob_On(int[] nums, int start, int end) {
if (end < start) {
return 0;
} else {
int[] table = new int[end - start + 1 + 1];
table[end - start + 1] = 0;
table[end - start] = nums[end];
// Recursion by DP
int pos = end - start - 1;
while (pos >= 0) {
table[pos] = Math.max((nums[start+pos] + table[pos+2]), table[pos+1]);
pos --;
}
return table[0];
}
}
}
| 1,730 | 0.478035 | 0.456069 | 51 | 32.92157 | 26.406954 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.784314 | false | false | 0 |
34859d40ff6839af8a9ad2cbc756bcefaad1a15d | 17,961,553,280,242 | 04a46ac66456af9b337745d0f6872d1b757cc661 | /src/main/java/de/nils_witt/splan/models/ApiSearchStudent.java | 24109329557fbcb5bd6cef07d187ea1a021c6e5c | []
| no_license | Nils-witt/S-Plan_SchilD | https://github.com/Nils-witt/S-Plan_SchilD | bb0a360732c44901e17ed077903937f4dcd0bf29 | 169dd63ae1456c4e144f1aac0554796aab501da8 | refs/heads/main | 2023-03-08T22:16:08.539000 | 2022-04-15T12:11:27 | 2022-04-15T12:11:27 | 219,786,336 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2021.
*/
package de.nils_witt.splan.models;
public class ApiSearchStudent {
private final String firstname;
private final String lastname;
private final String birthday;
public ApiSearchStudent(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.birthday = "*";
}
}
| UTF-8 | Java | 379 | java | ApiSearchStudent.java | Java | []
| null | []
| /*
* Copyright (c) 2021.
*/
package de.nils_witt.splan.models;
public class ApiSearchStudent {
private final String firstname;
private final String lastname;
private final String birthday;
public ApiSearchStudent(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
this.birthday = "*";
}
}
| 379 | 0.667546 | 0.656992 | 18 | 20.055555 | 18.455568 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 0 |
2e1743c1d5ef4b3f8fe483abf2565c2749e27b83 | 16,243,566,376,315 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /data/libgdx/AndroidGL30_glGetSamplerParameteriv.java | 04fadeb6c0634195e8eac23f25c383e347bbd79a | []
| no_license | GabeOchieng/ggnn.tensorflow | https://github.com/GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278000 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// @Override
// public void glGetSamplerParameteriv(int sampler, int pname, int[] params, int offset) {
// GLES30.glGetSamplerParameteriv(sampler, pname, params, offset);
// }
@Override
public void glGetSamplerParameteriv(int sampler, int pname, java.nio.IntBuffer params) {
GLES30.glGetSamplerParameteriv(sampler, pname, params);
}
| UTF-8 | Java | 341 | java | AndroidGL30_glGetSamplerParameteriv.java | Java | []
| null | []
| //
// @Override
// public void glGetSamplerParameteriv(int sampler, int pname, int[] params, int offset) {
// GLES30.glGetSamplerParameteriv(sampler, pname, params, offset);
// }
@Override
public void glGetSamplerParameteriv(int sampler, int pname, java.nio.IntBuffer params) {
GLES30.glGetSamplerParameteriv(sampler, pname, params);
}
| 341 | 0.756598 | 0.744868 | 9 | 36.888889 | 36.032223 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 0 |
0d715421275c2b6085c1fbcc3307c1d5e06e82fc | 8,014,409,026,491 | 67604d0289ea70233a9da0a619521edd9ad1641a | /src/main/org/nlogo/prim/_breed.java | df0970a5c61c15291c3870abb5e15c70980e1171 | []
| no_license | VT-CHCI/NetLogo | https://github.com/VT-CHCI/NetLogo | 2a3f207c1a71e34c2726ced7ec296d8c212f2a20 | 380863baf1d0d403dde446e15d88b68033f338ae | refs/heads/5.x | 2020-12-25T13:52:13.339000 | 2016-02-19T16:18:51 | 2016-02-19T16:18:51 | 52,116,138 | 1 | 3 | null | true | 2016-02-19T21:01:02 | 2016-02-19T21:01:01 | 2016-02-18T16:27:56 | 2016-02-19T16:18:56 | 35,496 | 0 | 0 | 0 | null | null | null | // (C) Uri Wilensky. https://github.com/NetLogo/NetLogo
package org.nlogo.prim;
import org.nlogo.agent.AgentSet;
import org.nlogo.api.Syntax;
import org.nlogo.nvm.Context;
import org.nlogo.nvm.Reporter;
public final strictfp class _breed extends Reporter {
String breedName;
public _breed(String breedName) {
this.breedName = breedName;
}
@Override
public Syntax syntax() {
return Syntax.reporterSyntax(Syntax.TurtlesetType());
}
@Override
public String toString() {
return super.toString() + ":" + breedName;
}
@Override
public Object report(Context context) {
return report_1(context);
}
public AgentSet report_1(Context context) {
return world.getBreed(breedName);
}
}
| UTF-8 | Java | 728 | java | _breed.java | Java | [
{
"context": "// (C) Uri Wilensky. https://github.com/NetLogo/NetLogo\n\npackage org.",
"end": 19,
"score": 0.999724805355072,
"start": 7,
"tag": "NAME",
"value": "Uri Wilensky"
},
{
"context": "// (C) Uri Wilensky. https://github.com/NetLogo/NetLogo\n\npackage org.nlogo.prim;\n\nimport org.nlog",
"end": 47,
"score": 0.9905263781547546,
"start": 40,
"tag": "USERNAME",
"value": "NetLogo"
}
]
| null | []
| // (C) <NAME>. https://github.com/NetLogo/NetLogo
package org.nlogo.prim;
import org.nlogo.agent.AgentSet;
import org.nlogo.api.Syntax;
import org.nlogo.nvm.Context;
import org.nlogo.nvm.Reporter;
public final strictfp class _breed extends Reporter {
String breedName;
public _breed(String breedName) {
this.breedName = breedName;
}
@Override
public Syntax syntax() {
return Syntax.reporterSyntax(Syntax.TurtlesetType());
}
@Override
public String toString() {
return super.toString() + ":" + breedName;
}
@Override
public Object report(Context context) {
return report_1(context);
}
public AgentSet report_1(Context context) {
return world.getBreed(breedName);
}
}
| 722 | 0.707418 | 0.70467 | 35 | 19.799999 | 18.42948 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314286 | false | false | 0 |
6223947c642d8b4a2519c04340af5b4f16328016 | 23,613,730,209,001 | 22463ea564843ea9aed81b5c0ee50ebea966a2d9 | /src/main/java/com/_98point6/droptoken/model/factories/BoardFactory.java | e56f5af7542c557de05bf9d4204be1820407aa92 | []
| no_license | marceloandradep/droptoken | https://github.com/marceloandradep/droptoken | 102e4cc66cc10163a08622de70800101eb6ce008 | 201fad984fc764759456626aad024a7bfafc550d | refs/heads/master | 2022-04-13T10:42:04.379000 | 2020-04-10T23:14:38 | 2020-04-10T23:14:38 | 254,703,556 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com._98point6.droptoken.model.factories;
import com._98point6.droptoken.exceptions.InvalidBoardSizeException;
import com._98point6.droptoken.model.board.DefaultBoard;
import com._98point6.droptoken.model.interfaces.Board;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class BoardFactory {
static final int MIN_BOARD = 4;
private int maxBoard;
public BoardFactory(@Value("${game.max-board}") int maxBoard) {
this.maxBoard = maxBoard;
}
public Board create(int size) {
if (size < MIN_BOARD || size > maxBoard) {
throw new InvalidBoardSizeException();
}
return new DefaultBoard(size);
}
}
| UTF-8 | Java | 770 | java | BoardFactory.java | Java | []
| null | []
| package com._98point6.droptoken.model.factories;
import com._98point6.droptoken.exceptions.InvalidBoardSizeException;
import com._98point6.droptoken.model.board.DefaultBoard;
import com._98point6.droptoken.model.interfaces.Board;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class BoardFactory {
static final int MIN_BOARD = 4;
private int maxBoard;
public BoardFactory(@Value("${game.max-board}") int maxBoard) {
this.maxBoard = maxBoard;
}
public Board create(int size) {
if (size < MIN_BOARD || size > maxBoard) {
throw new InvalidBoardSizeException();
}
return new DefaultBoard(size);
}
}
| 770 | 0.697403 | 0.680519 | 28 | 26.5 | 23.26478 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false | 0 |
3ca98a4f76371c9a3080371185cc6bad11ddda95 | 14,104,672,666,691 | 1448c11f122972d86226c9dc830084231a676425 | /chapter_001/src/main/java/ru/job4j/array/MinDiapason.java | 1542bdc44037ad23ca47bbd8559bdb4eac937fdb | [
"Unlicense",
"MIT"
]
| permissive | ViktorJava/job4j | https://github.com/ViktorJava/job4j | d4c3a33bb242b42584f340c700b1a95c68e87046 | 1fdd3b7d13d9f1265ac34decfe7d92346ad6b545 | refs/heads/master | 2023-03-04T11:44:56.589000 | 2023-02-21T23:21:56 | 2023-02-21T23:21:56 | 204,279,948 | 6 | 2 | Unlicense | false | 2021-11-04T22:16:23 | 2019-08-25T10:36:41 | 2021-11-04T19:50:08 | 2021-11-04T22:16:23 | 1,082 | 2 | 1 | 73 | Java | false | false | package ru.job4j.array;
/**
* Поиск минимума в диапазоне.
*
* @author ViktorJava (gipsyscrew@gmail.com)
* @version 0.1
* @since 15.06.2021
*/
public class MinDiapason {
/**
* Метод поиска минимального значения элемента массива, в диапазоне.
*
* @param array Массив.
* @param start Начало диапазона.
* @param finish Конец диапазона.
* @return Минимальное значение.
*/
public static int findMin(int[] array, int start, int finish) {
int min = array[start];
for (int i = start + 1; i <= finish; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
}
| UTF-8 | Java | 818 | java | MinDiapason.java | Java | [
{
"context": "\n\n/**\n * Поиск минимума в диапазоне.\n *\n * @author ViktorJava (gipsyscrew@gmail.com)\n * @version 0.1\n * @since ",
"end": 84,
"score": 0.9997760057449341,
"start": 74,
"tag": "NAME",
"value": "ViktorJava"
},
{
"context": "к минимума в диапазоне.\n *\n * @author ViktorJava (gipsyscrew@gmail.com)\n * @version 0.1\n * @since 15.06.2021\n */\npublic ",
"end": 106,
"score": 0.9999279975891113,
"start": 86,
"tag": "EMAIL",
"value": "gipsyscrew@gmail.com"
}
]
| null | []
| package ru.job4j.array;
/**
* Поиск минимума в диапазоне.
*
* @author ViktorJava (<EMAIL>)
* @version 0.1
* @since 15.06.2021
*/
public class MinDiapason {
/**
* Метод поиска минимального значения элемента массива, в диапазоне.
*
* @param array Массив.
* @param start Начало диапазона.
* @param finish Конец диапазона.
* @return Минимальное значение.
*/
public static int findMin(int[] array, int start, int finish) {
int min = array[start];
for (int i = start + 1; i <= finish; i++) {
if (min > array[i]) {
min = array[i];
}
}
return min;
}
}
| 805 | 0.554745 | 0.537226 | 28 | 23.464285 | 19.105875 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.321429 | false | false | 0 |
b49d43af33545cda1670aadd223785e746bb7fd0 | 5,050,881,543,384 | dfbdbf4087bc5ac4456f2695b31b93397e999097 | /app/src/main/java/com/example/varungupta/election/loginScreen.java | 35de172b1edc7ca9cb4e37c4c0f59c9537d7a04c | []
| no_license | TheVarunGupta/ElectionApp | https://github.com/TheVarunGupta/ElectionApp | c55eab02e91ea9f76dc9fd5dc8c3352844e603ad | b599f89c789d88473dad569aba0a42ad20ef0558 | refs/heads/master | 2018-12-21T12:05:47.957000 | 2018-09-29T18:37:19 | 2018-09-29T18:37:19 | 108,437,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.varungupta.election;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.*;
public class loginScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("users");
final EditText aadhar = (EditText) findViewById(R.id.editText5);
final EditText pass = (EditText) findViewById(R.id.editText6);
Button loginButton = (Button) findViewById(R.id.Submit);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String aadharString = aadhar.getText().toString().trim();
final String password = pass.getText().toString().trim();
if(aadharString.length()!= 12)
{
Toast.makeText(loginScreen.this,"Please enter the proper AADHAR Number",Toast.LENGTH_SHORT).show();
}
else if(password.length() != 8 )
{
Toast.makeText(loginScreen.this,"Please enter the proper Password",Toast.LENGTH_SHORT).show();
}
else {
myRef.child(aadharString).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// TODO: handle the case where the data already exists
String pas=snapshot.child("DOB").getValue().toString();
if(pas.equalsIgnoreCase(password)) {
Toast.makeText(loginScreen.this, "Login Successfull", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(loginScreen.this,selectConstituency.class);
intent.putExtra("AADHAR",aadharString);
Boolean con1=(Boolean)snapshot.child("con1").getValue();
Boolean con2=(Boolean)snapshot.child("con1").getValue();
intent.putExtra("con1",con1);
intent.putExtra("con2",con2);
startActivity(intent);
loginScreen.this.overridePendingTransition(R.anim.fadein,R.anim.fadeout);
}
else
Toast.makeText(loginScreen.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
} else {
// TODO: handle the case where the data does not yet exist
Toast.makeText(loginScreen.this, "Does not exits", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError firebaseError) {
Toast.makeText(loginScreen.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
| UTF-8 | Java | 3,697 | java | loginScreen.java | Java | [
{
"context": "package com.example.varungupta.election;\n\nimport android.content.Intent;\nimport ",
"end": 30,
"score": 0.6728990077972412,
"start": 20,
"tag": "USERNAME",
"value": "varungupta"
}
]
| null | []
| package com.example.varungupta.election;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.*;
public class loginScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("users");
final EditText aadhar = (EditText) findViewById(R.id.editText5);
final EditText pass = (EditText) findViewById(R.id.editText6);
Button loginButton = (Button) findViewById(R.id.Submit);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String aadharString = aadhar.getText().toString().trim();
final String password = pass.getText().toString().trim();
if(aadharString.length()!= 12)
{
Toast.makeText(loginScreen.this,"Please enter the proper AADHAR Number",Toast.LENGTH_SHORT).show();
}
else if(password.length() != 8 )
{
Toast.makeText(loginScreen.this,"Please enter the proper Password",Toast.LENGTH_SHORT).show();
}
else {
myRef.child(aadharString).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
// TODO: handle the case where the data already exists
String pas=snapshot.child("DOB").getValue().toString();
if(pas.equalsIgnoreCase(password)) {
Toast.makeText(loginScreen.this, "Login Successfull", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(loginScreen.this,selectConstituency.class);
intent.putExtra("AADHAR",aadharString);
Boolean con1=(Boolean)snapshot.child("con1").getValue();
Boolean con2=(Boolean)snapshot.child("con1").getValue();
intent.putExtra("con1",con1);
intent.putExtra("con2",con2);
startActivity(intent);
loginScreen.this.overridePendingTransition(R.anim.fadein,R.anim.fadeout);
}
else
Toast.makeText(loginScreen.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
} else {
// TODO: handle the case where the data does not yet exist
Toast.makeText(loginScreen.this, "Does not exits", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError firebaseError) {
Toast.makeText(loginScreen.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
| 3,697 | 0.526643 | 0.522856 | 82 | 44.085365 | 35.720528 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.634146 | false | false | 0 |
5d6a5f08987665b338f4f4955f355fd2e78dd3c1 | 8,211,977,529,339 | e87f21f39a81f52d87acc2117651172dd30d581d | /app/src/main/java/com/tesis/galeria/galeria/task/GetObrasAsyncTask.java | 61477da45d799267e822c58446fa49b4398a08d9 | []
| no_license | danielpargas/GaleriaAndroid | https://github.com/danielpargas/GaleriaAndroid | 49c0debc38eb96e79848d4d1dfd92a7b6e7f5fe7 | 425edbf5ec9fbaeed8f6e29348582251031abd6f | refs/heads/master | 2021-06-04T23:01:14.920000 | 2016-09-12T20:54:44 | 2016-09-12T20:54:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tesis.galeria.galeria.task;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.tesis.galeria.R;
import com.tesis.galeria.galeria.adapter.ObraAdapter;
import com.tesis.galeria.galeria.db.ModelosDB;
import com.tesis.galeria.galeria.modelos.Lista.Obras;
import org.lucasr.twowayview.widget.TwoWayView;
/**
* Created by danie on 29/5/2016.
*/
public class GetObrasAsyncTask extends AsyncTask<Void, Void, Obras> {
private int idArtista;
private String mQuery;
private AppCompatActivity context;
private TwoWayView recycler;
private ViewGroup v;
private TextView tvEmpty;
private Button btnEmpty;
private ProgressWheel wheel;
public GetObrasAsyncTask(AppCompatActivity context, TwoWayView recycler, ViewGroup v, int idArtista) {
this.context = context;
this.recycler = recycler;
this.v = v;
this.idArtista = idArtista;
tvEmpty = (TextView) v.findViewById(R.id.tv_empty);
btnEmpty = (Button) v.findViewById(R.id.btn_empty);
wheel = (ProgressWheel) v.findViewById(R.id.progress_wheel);
}
public GetObrasAsyncTask(AppCompatActivity context, TwoWayView recycler, ViewGroup v) {
this(context, recycler, v, 0);
}
public GetObrasAsyncTask(String mQuery, AppCompatActivity context, TwoWayView recycler, ViewGroup v) {
this.idArtista = 0;
this.mQuery = mQuery;
this.context = context;
this.recycler = recycler;
this.v = v;
tvEmpty = (TextView) v.findViewById(R.id.tv_empty);
btnEmpty = (Button) v.findViewById(R.id.btn_empty);
wheel = (ProgressWheel) v.findViewById(R.id.progress_wheel);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (recycler.getAdapter() == null) {
wheel.setVisibility(View.VISIBLE);
}
tvEmpty.setVisibility(View.GONE);
btnEmpty.setVisibility(View.GONE);
}
@Override
protected Obras doInBackground(Void... params) {
if (mQuery != null && !mQuery.isEmpty()) {
return ModelosDB.getObras(mQuery);
} else if (idArtista > 0) {
return ModelosDB.getObrasArtista(idArtista);
} else {
return ModelosDB.getObras();
}
}
@Override
protected void onPostExecute(Obras obras) {
super.onPostExecute(obras);
wheel.setVisibility(View.GONE);
if (obras != null) {
if (obras.items != null) {
if (obras.items.size() > 0) {
Log.d("OBRAS", String.valueOf(obras.items.size()));
recycler.setAdapter(new ObraAdapter(context, obras.items));
tvEmpty.setVisibility(View.GONE);
btnEmpty.setVisibility(View.GONE);
} else {
tvEmpty.setVisibility(View.VISIBLE);
tvEmpty.setText(R.string.sin_obras);
}
} else {
tvEmpty.setText(context.getString(R.string.error));
tvEmpty.setVisibility(View.VISIBLE);
btnEmpty.setVisibility(View.VISIBLE);
}
} else {
tvEmpty.setText(context.getString(R.string.error));
tvEmpty.setVisibility(View.VISIBLE);
btnEmpty.setVisibility(View.VISIBLE);
}
}
}
| UTF-8 | Java | 3,612 | java | GetObrasAsyncTask.java | Java | [
{
"context": "r.twowayview.widget.TwoWayView;\n\n/**\n * Created by danie on 29/5/2016.\n */\npublic class GetObrasAsyncTask ",
"end": 575,
"score": 0.9975718259811401,
"start": 570,
"tag": "USERNAME",
"value": "danie"
}
]
| null | []
| package com.tesis.galeria.galeria.task;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.pnikosis.materialishprogress.ProgressWheel;
import com.tesis.galeria.R;
import com.tesis.galeria.galeria.adapter.ObraAdapter;
import com.tesis.galeria.galeria.db.ModelosDB;
import com.tesis.galeria.galeria.modelos.Lista.Obras;
import org.lucasr.twowayview.widget.TwoWayView;
/**
* Created by danie on 29/5/2016.
*/
public class GetObrasAsyncTask extends AsyncTask<Void, Void, Obras> {
private int idArtista;
private String mQuery;
private AppCompatActivity context;
private TwoWayView recycler;
private ViewGroup v;
private TextView tvEmpty;
private Button btnEmpty;
private ProgressWheel wheel;
public GetObrasAsyncTask(AppCompatActivity context, TwoWayView recycler, ViewGroup v, int idArtista) {
this.context = context;
this.recycler = recycler;
this.v = v;
this.idArtista = idArtista;
tvEmpty = (TextView) v.findViewById(R.id.tv_empty);
btnEmpty = (Button) v.findViewById(R.id.btn_empty);
wheel = (ProgressWheel) v.findViewById(R.id.progress_wheel);
}
public GetObrasAsyncTask(AppCompatActivity context, TwoWayView recycler, ViewGroup v) {
this(context, recycler, v, 0);
}
public GetObrasAsyncTask(String mQuery, AppCompatActivity context, TwoWayView recycler, ViewGroup v) {
this.idArtista = 0;
this.mQuery = mQuery;
this.context = context;
this.recycler = recycler;
this.v = v;
tvEmpty = (TextView) v.findViewById(R.id.tv_empty);
btnEmpty = (Button) v.findViewById(R.id.btn_empty);
wheel = (ProgressWheel) v.findViewById(R.id.progress_wheel);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (recycler.getAdapter() == null) {
wheel.setVisibility(View.VISIBLE);
}
tvEmpty.setVisibility(View.GONE);
btnEmpty.setVisibility(View.GONE);
}
@Override
protected Obras doInBackground(Void... params) {
if (mQuery != null && !mQuery.isEmpty()) {
return ModelosDB.getObras(mQuery);
} else if (idArtista > 0) {
return ModelosDB.getObrasArtista(idArtista);
} else {
return ModelosDB.getObras();
}
}
@Override
protected void onPostExecute(Obras obras) {
super.onPostExecute(obras);
wheel.setVisibility(View.GONE);
if (obras != null) {
if (obras.items != null) {
if (obras.items.size() > 0) {
Log.d("OBRAS", String.valueOf(obras.items.size()));
recycler.setAdapter(new ObraAdapter(context, obras.items));
tvEmpty.setVisibility(View.GONE);
btnEmpty.setVisibility(View.GONE);
} else {
tvEmpty.setVisibility(View.VISIBLE);
tvEmpty.setText(R.string.sin_obras);
}
} else {
tvEmpty.setText(context.getString(R.string.error));
tvEmpty.setVisibility(View.VISIBLE);
btnEmpty.setVisibility(View.VISIBLE);
}
} else {
tvEmpty.setText(context.getString(R.string.error));
tvEmpty.setVisibility(View.VISIBLE);
btnEmpty.setVisibility(View.VISIBLE);
}
}
}
| 3,612 | 0.630676 | 0.627353 | 113 | 30.964602 | 24.260361 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.654867 | false | false | 0 |
b3c480c63efa0a52d21b888a76d85edcce78b637 | 11,287,174,058,218 | 78b14aebeb672c1b5d62787fe7886f254953d7c9 | /src/keybinds/dao/Dao.java | 7cabf32501d9d40d1d316f12553a08ed2046d76e | []
| no_license | tomaldcallahan/keybind | https://github.com/tomaldcallahan/keybind | bae366b088654138b565a89067a6c0cb6f64f2d9 | 009609a899d4df1312967a08b52b939a296629b9 | refs/heads/master | 2021-04-30T06:10:30.071000 | 2018-02-13T21:19:32 | 2018-02-13T21:19:32 | 121,436,697 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package keybinds.dao;
import java.util.ArrayList;
import java.util.List;
import keybinds.dto.KeyBind;
import util.exception.HinaException;
import util.exception.HinaOrmapperException;
import util.ormapper.HinaOrmapper;
public class Dao {
/**
* 削除メソッド
* @param kind
* @param key
* @return
*/
public static int delete(String kind, String key) {
int result = 0;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "delete from keybinds where kind = ? and key = ?";
result = ho.excecutedUpdate(sql, kind, key);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in delete sql.", e);
}
return result;
}
/**
* インサートメソッド
* @param kind
* @param key
* @param name
* @param path
* @return
*/
public static int insert(String kind, String key, String name, String path) {
insertTime = System.currentTimeMillis();
int result = 0;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "insert into keybinds values( ?, ?, ?, ?) ";
ho.excecutedUpdate(sql, kind, key, path, name);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in insert sql.", e);
}
return result;
}
/**
* インサートした時間を保持
*/
private static long insertTime = 0;
/**
* kindを条件に検索するメソッド
* @param kind
* @return
*/
public static List<KeyBind> selectByKindl(String kind) {
List<KeyBind> keyBindList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds where kind = ?";
keyBindList = ho.excecuteQuery(sql, KeyBind.class, kind);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBindList;
}
public static KeyBind selectByKindlAndKey(String kind, String key) {
KeyBind keyBind = null;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds where kind = ? and key = ?";
keyBind = ho.executeQueryOne(sql, KeyBind.class, kind, key);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBind;
}
public static List<KeyBind> selectAll() {
List<KeyBind> keyBindList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds order by kind, key";
keyBindList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBindList;
}
/**
* 現在のkeyのリストを返却する
* @return
*/
public static List<KeyBind> getKeys() {
if (getKeysList != null && insertTime == getKeysTime)
return getKeysList;
getKeysList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select distinct key from keybinds";
getKeysList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in getKeys sql.", e);
}
return getKeysList;
}
private static long getKeysTime = 0;
private static List<KeyBind> getKeysList = null;
/**
* 現在のkindのリストを返却する
* @return
*/
public static List<KeyBind> getKinds() {
if (getKindsList != null && insertTime == getKindsTime)
return getKindsList;
getKindsList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select distinct kind from keybinds";
getKindsList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in getKinds sql.", e);
}
return getKindsList;
}
private static long getKindsTime = 0;
private static List<KeyBind> getKindsList = null;
}
| UTF-8 | Java | 4,033 | java | Dao.java | Java | []
| null | []
| package keybinds.dao;
import java.util.ArrayList;
import java.util.List;
import keybinds.dto.KeyBind;
import util.exception.HinaException;
import util.exception.HinaOrmapperException;
import util.ormapper.HinaOrmapper;
public class Dao {
/**
* 削除メソッド
* @param kind
* @param key
* @return
*/
public static int delete(String kind, String key) {
int result = 0;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "delete from keybinds where kind = ? and key = ?";
result = ho.excecutedUpdate(sql, kind, key);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in delete sql.", e);
}
return result;
}
/**
* インサートメソッド
* @param kind
* @param key
* @param name
* @param path
* @return
*/
public static int insert(String kind, String key, String name, String path) {
insertTime = System.currentTimeMillis();
int result = 0;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "insert into keybinds values( ?, ?, ?, ?) ";
ho.excecutedUpdate(sql, kind, key, path, name);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in insert sql.", e);
}
return result;
}
/**
* インサートした時間を保持
*/
private static long insertTime = 0;
/**
* kindを条件に検索するメソッド
* @param kind
* @return
*/
public static List<KeyBind> selectByKindl(String kind) {
List<KeyBind> keyBindList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds where kind = ?";
keyBindList = ho.excecuteQuery(sql, KeyBind.class, kind);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBindList;
}
public static KeyBind selectByKindlAndKey(String kind, String key) {
KeyBind keyBind = null;
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds where kind = ? and key = ?";
keyBind = ho.executeQueryOne(sql, KeyBind.class, kind, key);
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBind;
}
public static List<KeyBind> selectAll() {
List<KeyBind> keyBindList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select * from keybinds order by kind, key";
keyBindList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in selectByKind sql.", e);
}
return keyBindList;
}
/**
* 現在のkeyのリストを返却する
* @return
*/
public static List<KeyBind> getKeys() {
if (getKeysList != null && insertTime == getKeysTime)
return getKeysList;
getKeysList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select distinct key from keybinds";
getKeysList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in getKeys sql.", e);
}
return getKeysList;
}
private static long getKeysTime = 0;
private static List<KeyBind> getKeysList = null;
/**
* 現在のkindのリストを返却する
* @return
*/
public static List<KeyBind> getKinds() {
if (getKindsList != null && insertTime == getKindsTime)
return getKindsList;
getKindsList = new ArrayList<>();
try (HinaOrmapper ho = new HinaOrmapper()) {
String sql = "select distinct kind from keybinds";
getKindsList = ho.excecuteQuery(sql, KeyBind.class, new String[] {});
} catch (HinaOrmapperException e) {
throw new HinaException("exception in getKinds sql.", e);
}
return getKindsList;
}
private static long getKindsTime = 0;
private static List<KeyBind> getKindsList = null;
}
| 4,033 | 0.650115 | 0.648835 | 167 | 21.39521 | 23.002983 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.658683 | false | false | 0 |
fc315782a46a8b8b1c776067262789e32a8a9d78 | 30,588,757,097,852 | 101eeb315747420b60dd990fa2878f1aa1bfce50 | /ccm-parent/ccm-activemq/src/main/java/com/ccc/ccm/destinations/BaseDestinationController.java | 1a68b98c583c96f4a2a5428497963474f817760f | []
| no_license | markoradinovic/cccframework | https://github.com/markoradinovic/cccframework | 9b4c0db0ca468e123489c5582784eb557208358a | e9d9653913c8327a35e81466b86c12c8877ac53c | refs/heads/master | 2017-02-17T18:50:13.601000 | 2012-11-14T23:48:55 | 2012-11-14T23:48:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ccc.ccm.destinations;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Topic;
/**
* This is a base destination controller for use with
* managing destinations at run time.
* @author Adam Gibson
*
*/
public abstract class BaseDestinationController implements DestinationController {
@Override
public Set<Destination> destinations() {
Set<Destination> ret = new HashSet<Destination>();
for(String s : destinationInfo.keySet()) {
Map.Entry<Destination,MessageListener> entry=destinationInfo.get(s);
ret.add(entry.getKey());
}
return ret;
}
@Override
public void addDestination(Destination destination) {
destinations.add(destination);
}
@Override
public void removeDestination(Destination destination) {
destinations.remove(destination);
}
@Override
public Destination destinationWithName(String name) {
Destination ret= destinationInfo.get(name).getKey();
if(ret==null) {
for(Destination d : destinations) {
String match=null;
if(d instanceof Queue) {
Queue q=(Queue) d;
try {
match=q.getQueueName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(d instanceof Topic) {
Topic topic=(Topic) d;
try {
match=topic.getTopicName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(match!=null && match.equals(name))
return d;
}
}
else return ret;
return null;
}
@Override
public DestinationMatcher matcher() {
return destinationMatcher;
}
@Override
public void setMatcher(DestinationMatcher matcher) {
destinationMatcher=matcher;
}
@Override
public Set<MessageListener> listeners() {
Set<MessageListener> ret = new HashSet<MessageListener>();
for(String s : destinationInfo.keySet()) {
Map.Entry<Destination,MessageListener> entry=destinationInfo.get(s);
ret.add(entry.getValue());
}
return ret;
}
@Override
public void put(final Destination d, final MessageListener m) {
String name=null;
if(d instanceof Queue) {
Queue q=(Queue) d;
try {
name=q.getQueueName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(d instanceof Topic) {
Topic topic=(Topic) d;
try {
name=topic.getTopicName();
} catch (JMSException e) {
e.printStackTrace();
}
}
destinationInfo.put(name,new Map.Entry<Destination, MessageListener>(){
{
}
@Override
public Destination getKey() {
return d;
}
@Override
public MessageListener getValue() {
return m;
}
@Override
public MessageListener setValue(MessageListener value) {
this.value=value;
return value;
}
private MessageListener value;
});
}
@Override
public Map<String, Entry<Destination, MessageListener>> destinationIndex() {
return destinationInfo;
}
private Set<Destination> destinations = new HashSet<Destination>();
private Map<String,Map.Entry<Destination,MessageListener>> destinationInfo = new HashMap<String,Map.Entry<Destination,MessageListener>>();
private DestinationMatcher destinationMatcher;
}
| UTF-8 | Java | 3,287 | java | BaseDestinationController.java | Java | [
{
"context": "h\n * managing destinations at run time.\n * @author Adam Gibson\n *\n */\npublic abstract class BaseDestinationContr",
"end": 421,
"score": 0.9995638728141785,
"start": 410,
"tag": "NAME",
"value": "Adam Gibson"
}
]
| null | []
| package com.ccc.ccm.destinations;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Topic;
/**
* This is a base destination controller for use with
* managing destinations at run time.
* @author <NAME>
*
*/
public abstract class BaseDestinationController implements DestinationController {
@Override
public Set<Destination> destinations() {
Set<Destination> ret = new HashSet<Destination>();
for(String s : destinationInfo.keySet()) {
Map.Entry<Destination,MessageListener> entry=destinationInfo.get(s);
ret.add(entry.getKey());
}
return ret;
}
@Override
public void addDestination(Destination destination) {
destinations.add(destination);
}
@Override
public void removeDestination(Destination destination) {
destinations.remove(destination);
}
@Override
public Destination destinationWithName(String name) {
Destination ret= destinationInfo.get(name).getKey();
if(ret==null) {
for(Destination d : destinations) {
String match=null;
if(d instanceof Queue) {
Queue q=(Queue) d;
try {
match=q.getQueueName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(d instanceof Topic) {
Topic topic=(Topic) d;
try {
match=topic.getTopicName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(match!=null && match.equals(name))
return d;
}
}
else return ret;
return null;
}
@Override
public DestinationMatcher matcher() {
return destinationMatcher;
}
@Override
public void setMatcher(DestinationMatcher matcher) {
destinationMatcher=matcher;
}
@Override
public Set<MessageListener> listeners() {
Set<MessageListener> ret = new HashSet<MessageListener>();
for(String s : destinationInfo.keySet()) {
Map.Entry<Destination,MessageListener> entry=destinationInfo.get(s);
ret.add(entry.getValue());
}
return ret;
}
@Override
public void put(final Destination d, final MessageListener m) {
String name=null;
if(d instanceof Queue) {
Queue q=(Queue) d;
try {
name=q.getQueueName();
} catch (JMSException e) {
e.printStackTrace();
}
}
if(d instanceof Topic) {
Topic topic=(Topic) d;
try {
name=topic.getTopicName();
} catch (JMSException e) {
e.printStackTrace();
}
}
destinationInfo.put(name,new Map.Entry<Destination, MessageListener>(){
{
}
@Override
public Destination getKey() {
return d;
}
@Override
public MessageListener getValue() {
return m;
}
@Override
public MessageListener setValue(MessageListener value) {
this.value=value;
return value;
}
private MessageListener value;
});
}
@Override
public Map<String, Entry<Destination, MessageListener>> destinationIndex() {
return destinationInfo;
}
private Set<Destination> destinations = new HashSet<Destination>();
private Map<String,Map.Entry<Destination,MessageListener>> destinationInfo = new HashMap<String,Map.Entry<Destination,MessageListener>>();
private DestinationMatcher destinationMatcher;
}
| 3,282 | 0.697597 | 0.697597 | 153 | 20.48366 | 21.824644 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.267974 | false | false | 0 |
a146801fa5ad247b0e4552221643de830999e2f1 | 1,142,461,346,249 | 64894b3199c93c8a7328bbe00b4a21215d40d1a2 | /Java/src/Mode/SourceMethod.java | d9f053fe44a3c33490107a9cbcf076ef17b80914 | []
| no_license | gaojunhao/java | https://github.com/gaojunhao/java | 13300f674dd9fd5ded031f0df297d7aa3296c902 | 9b07194c7cc69d333ff0554288941e8db0e90d35 | refs/heads/master | 2021-06-12T07:39:52.177000 | 2017-02-28T00:53:20 | 2017-02-28T00:53:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Mode;
public class SourceMethod implements Source{
public void method1() {
// TODO Auto-generated method stub
System.out.println("method1~~");
}
public void method2() {
// TODO Auto-generated method stub
System.out.println("method2--");
}
}
| UTF-8 | Java | 265 | java | SourceMethod.java | Java | []
| null | []
| package Mode;
public class SourceMethod implements Source{
public void method1() {
// TODO Auto-generated method stub
System.out.println("method1~~");
}
public void method2() {
// TODO Auto-generated method stub
System.out.println("method2--");
}
}
| 265 | 0.69434 | 0.679245 | 15 | 16.666666 | 16.336735 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 0 |
c270fe65770e317bda2a28c51a1bf0505d337d8e | 4,784,593,628,164 | 6bc966044e60211d0dc80eb5ddeb23e50d95b9ef | /src/Abstract_Factory_Pattern/StuffedToysFactory.java | 36b81615d6ea6f70bd3ea6922075d458b1835b76 | []
| no_license | AbubakarMunir/CreationalDesignPatterns | https://github.com/AbubakarMunir/CreationalDesignPatterns | fc41500034f3d174254e37e41c8dcb75708fb480 | f83e2073a8374452d35629022d157099f1cdb093 | refs/heads/master | 2022-04-24T16:25:12.327000 | 2020-04-26T16:01:08 | 2020-04-26T16:01:08 | 259,070,501 | 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 Abstract_Factory_Pattern;
/**
*
* @author hp
*/
public class StuffedToysFactory extends AbstractFactory {
@Override
public StuffedToy getStuffedToys(String tname)
{
if(tname=="WinnieThePooh")
{
return new Pooh();
}
return null;
}
public ToyCar getToyCars(String cname)
{
return null;
}
}
| UTF-8 | Java | 667 | java | StuffedToysFactory.java | Java | [
{
"context": "e Abstract_Factory_Pattern;\r\n\r\n/**\r\n *\r\n * @author hp\r\n */\r\npublic class StuffedToysFactory extends Abstr",
"end": 249,
"score": 0.847178041934967,
"start": 247,
"tag": "USERNAME",
"value": "hp"
}
]
| 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 Abstract_Factory_Pattern;
/**
*
* @author hp
*/
public class StuffedToysFactory extends AbstractFactory {
@Override
public StuffedToy getStuffedToys(String tname)
{
if(tname=="WinnieThePooh")
{
return new Pooh();
}
return null;
}
public ToyCar getToyCars(String cname)
{
return null;
}
}
| 667 | 0.53973 | 0.53973 | 32 | 18.84375 | 20.921146 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.21875 | false | false | 0 |
1d42e3b90579a92cabdc597c24210145131025d1 | 17,669,495,470,809 | b09290852f6f0e6ea65094548ac618d07334a2ba | /src/main/java/com/abrajner/plagiarismdetector/fileparser/languageparser/JavaScriptParser.java | 4d810729f25d5ed99c4b8aed24f66d486d8a2092 | []
| no_license | abrajner/plagiarism-detector | https://github.com/abrajner/plagiarism-detector | b580a402baf5df91b901b1ca5402387337ee8fbb | ecd1ad52ea0cdb03ea04331630e109c257385cf6 | refs/heads/main | 2023-03-13T03:50:38.553000 | 2021-02-19T16:19:54 | 2021-02-19T16:19:54 | 311,070,153 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.abrajner.plagiarismdetector.fileparser.languageparser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.math.NumberUtils;
import com.abrajner.plagiarismdetector.fileparser.ParsedFile;
public class JavaScriptParser implements LanguageParser {
private ParsedFile parsedFile;
private final List<String> identifiers = new ArrayList<>();
final private static List<String> CHARACTERS_FROM_FUNCTION_DEFINITION = Arrays.asList("function", "=", ">", "{",
"}", "(", ")", ",", "var", "let", "const");
@Override
public void parse(final ParsedFile parsedFile) {
this.parsedFile = parsedFile;
this.identifiers.addAll(parsedFile.getIdentifiersByEquals());
parsedFile.getFileContentByInstructions().addAll(this.instructionsParser());
parsedFile.getFileContentByFunctions().addAll(this.functionsParser());
this.parsedFile.getIdentifiers().addAll(this.identifiers);
}
private List<List<String>> instructionsParser() {
return CommonParser.getInstructionsFromFile(this.parsedFile);
}
private List<List<String>> functionsParser() {
final List<List<String>> result = new ArrayList<>();
final List<List<String>> fileContent = new ArrayList<>(this.parsedFile.getFileContentByInstructions());
int k = 0;
boolean isFunctionEntered = false;
int numberOfEnteredBrackets = 0;
result.add(new ArrayList<>());
for(final List<String> line: fileContent){
boolean isInstructionWithFunctionDefinition = false;
boolean createNewArrayForFunction = false;
if(line.contains("function")){
createNewArrayForFunction = true;
}
for(final String currentValue: line){
if(createNewArrayForFunction){
createNewArrayForFunction = false;
result.add(new ArrayList<>());
k ++;
result.get(k).add(currentValue);
isInstructionWithFunctionDefinition = true;
continue;
}
if(isInstructionWithFunctionDefinition){
if(!CHARACTERS_FROM_FUNCTION_DEFINITION.contains(currentValue) && !NumberUtils.isCreatable(currentValue)
&& !this.identifiers.contains(currentValue)){
this.identifiers.add(currentValue);
}
}
if("{".equals(currentValue) && isInstructionWithFunctionDefinition){
numberOfEnteredBrackets++;
isFunctionEntered = true;
}
if ("}".equals(currentValue)){
numberOfEnteredBrackets--;
if(isFunctionEntered && numberOfEnteredBrackets<1) {
result.get(k).add(currentValue);
isFunctionEntered = false;
continue;
}
}
result.get(k).add(currentValue);
}
}
return result; }
}
| UTF-8 | Java | 3,224 | java | JavaScriptParser.java | Java | []
| null | []
| package com.abrajner.plagiarismdetector.fileparser.languageparser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.math.NumberUtils;
import com.abrajner.plagiarismdetector.fileparser.ParsedFile;
public class JavaScriptParser implements LanguageParser {
private ParsedFile parsedFile;
private final List<String> identifiers = new ArrayList<>();
final private static List<String> CHARACTERS_FROM_FUNCTION_DEFINITION = Arrays.asList("function", "=", ">", "{",
"}", "(", ")", ",", "var", "let", "const");
@Override
public void parse(final ParsedFile parsedFile) {
this.parsedFile = parsedFile;
this.identifiers.addAll(parsedFile.getIdentifiersByEquals());
parsedFile.getFileContentByInstructions().addAll(this.instructionsParser());
parsedFile.getFileContentByFunctions().addAll(this.functionsParser());
this.parsedFile.getIdentifiers().addAll(this.identifiers);
}
private List<List<String>> instructionsParser() {
return CommonParser.getInstructionsFromFile(this.parsedFile);
}
private List<List<String>> functionsParser() {
final List<List<String>> result = new ArrayList<>();
final List<List<String>> fileContent = new ArrayList<>(this.parsedFile.getFileContentByInstructions());
int k = 0;
boolean isFunctionEntered = false;
int numberOfEnteredBrackets = 0;
result.add(new ArrayList<>());
for(final List<String> line: fileContent){
boolean isInstructionWithFunctionDefinition = false;
boolean createNewArrayForFunction = false;
if(line.contains("function")){
createNewArrayForFunction = true;
}
for(final String currentValue: line){
if(createNewArrayForFunction){
createNewArrayForFunction = false;
result.add(new ArrayList<>());
k ++;
result.get(k).add(currentValue);
isInstructionWithFunctionDefinition = true;
continue;
}
if(isInstructionWithFunctionDefinition){
if(!CHARACTERS_FROM_FUNCTION_DEFINITION.contains(currentValue) && !NumberUtils.isCreatable(currentValue)
&& !this.identifiers.contains(currentValue)){
this.identifiers.add(currentValue);
}
}
if("{".equals(currentValue) && isInstructionWithFunctionDefinition){
numberOfEnteredBrackets++;
isFunctionEntered = true;
}
if ("}".equals(currentValue)){
numberOfEnteredBrackets--;
if(isFunctionEntered && numberOfEnteredBrackets<1) {
result.get(k).add(currentValue);
isFunctionEntered = false;
continue;
}
}
result.get(k).add(currentValue);
}
}
return result; }
}
| 3,224 | 0.583437 | 0.582196 | 78 | 40.333332 | 27.804567 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.641026 | false | false | 0 |
6430a5076e605e4da35e45bc52cb826110990d1b | 18,262,200,968,368 | 850504b8b3e6da8aa31580849872930ab2bd6d31 | /src/controller/DepositoController.java | cac92ffe8659acf3264b849b14f828b3774b5a13 | []
| no_license | diegomunhoz/PIM-UNIP | https://github.com/diegomunhoz/PIM-UNIP | 8de7b51e256a43ce39b287c6baba6afc260f2f46 | 8ec10991fe03d47eb30129fecbd6cee6130c15f3 | refs/heads/master | 2020-03-22T22:35:20.756000 | 2018-07-13T14:38:27 | 2018-07-13T14:38:27 | 140,759,527 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import dao.ContaDAO;
import dao.MovimentoDAO;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.Conta;
import model.Movimento;
import view.DepositoPrincipal;
public class DepositoController {
private DepositoPrincipal viewDeposito;
private List<Conta> listaContas;
private Double deposito;
private Movimento movimento;
public DepositoController(DepositoPrincipal viewDeposito) {
this.viewDeposito = viewDeposito;
}
public void efetuarDeposito() {
int idConta = Integer.parseInt(this.viewDeposito.getJtfConta().getText());
int idAgencia = Integer.parseInt(this.viewDeposito.getJtfAgencia().getText());
try {
listaContas = new ContaDAO().buscarTodos();
for (Conta conta : listaContas) {
if (conta.getIdConta().equals(idConta) && conta.getAgenciaIdAgencia().getIdAgencia().equals(idAgencia)) {
if (this.viewDeposito.getJtfValorDeposito().getText().equals(null)) {
JOptionPane.showConfirmDialog(null, "E NECESSÁRIO INFORMAR O VALOR!");
}else{
deposito = Double.parseDouble(this.viewDeposito.getJtfValorDeposito().getText());
double saldo = conta.getSaldoTotalConta();
saldo = saldo + deposito;
conta.setSaldoTotalConta(saldo);
new ContaDAO().salvar(conta);
movimento = new Movimento();
movimento.setDataMovimento(new Date());
movimento.setHoraMovimento(new Date());
movimento.setDescricaoServico("DEPOSITO");
movimento.setValorMovimento(deposito);
movimento.setContaIdConta(conta);
new MovimentoDAO().salvar(movimento);
JOptionPane.showMessageDialog(null, "DEPOSITO EFETUADO COM SUCESSO!");
this.viewDeposito.getJtfAgencia().setText(null);
this.viewDeposito.getJtfConta().setText(null);
this.viewDeposito.getJtfValorDeposito().setText(null);
this.viewDeposito.getjComboBox1().setSelectedIndex(0);
break;
}
} else {
JOptionPane.showMessageDialog(null, "AGENCIA E CONTA NÃO CADASTRADA");
}
}
} catch (Exception ex) {
Logger.getLogger(DepositoController.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | UTF-8 | Java | 2,796 | java | DepositoController.java | Java | []
| null | []
| package controller;
import dao.ContaDAO;
import dao.MovimentoDAO;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.Conta;
import model.Movimento;
import view.DepositoPrincipal;
public class DepositoController {
private DepositoPrincipal viewDeposito;
private List<Conta> listaContas;
private Double deposito;
private Movimento movimento;
public DepositoController(DepositoPrincipal viewDeposito) {
this.viewDeposito = viewDeposito;
}
public void efetuarDeposito() {
int idConta = Integer.parseInt(this.viewDeposito.getJtfConta().getText());
int idAgencia = Integer.parseInt(this.viewDeposito.getJtfAgencia().getText());
try {
listaContas = new ContaDAO().buscarTodos();
for (Conta conta : listaContas) {
if (conta.getIdConta().equals(idConta) && conta.getAgenciaIdAgencia().getIdAgencia().equals(idAgencia)) {
if (this.viewDeposito.getJtfValorDeposito().getText().equals(null)) {
JOptionPane.showConfirmDialog(null, "E NECESSÁRIO INFORMAR O VALOR!");
}else{
deposito = Double.parseDouble(this.viewDeposito.getJtfValorDeposito().getText());
double saldo = conta.getSaldoTotalConta();
saldo = saldo + deposito;
conta.setSaldoTotalConta(saldo);
new ContaDAO().salvar(conta);
movimento = new Movimento();
movimento.setDataMovimento(new Date());
movimento.setHoraMovimento(new Date());
movimento.setDescricaoServico("DEPOSITO");
movimento.setValorMovimento(deposito);
movimento.setContaIdConta(conta);
new MovimentoDAO().salvar(movimento);
JOptionPane.showMessageDialog(null, "DEPOSITO EFETUADO COM SUCESSO!");
this.viewDeposito.getJtfAgencia().setText(null);
this.viewDeposito.getJtfConta().setText(null);
this.viewDeposito.getJtfValorDeposito().setText(null);
this.viewDeposito.getjComboBox1().setSelectedIndex(0);
break;
}
} else {
JOptionPane.showMessageDialog(null, "AGENCIA E CONTA NÃO CADASTRADA");
}
}
} catch (Exception ex) {
Logger.getLogger(DepositoController.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 2,796 | 0.578024 | 0.577309 | 64 | 42.671875 | 30.670147 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703125 | false | false | 0 |
1b36fb1570f61cf79edd27e06dadfaa59fe50cbc | 9,242,769,622,686 | 88ada4099d10997cf3a6e8e32c2cbf5a03efa5d9 | /src/aircraftModels/MilitaryPlane.java | a8618d3e448ce763d25196d0acd5aef266944f8c | []
| no_license | jelena997/AirTrafficControl | https://github.com/jelena997/AirTrafficControl | 036ac788ce84faf557adf795823f23da48b449c1 | bd9f9cd4f4a5cfb14ca618392095e80fbfb73a6f | refs/heads/master | 2020-08-31T05:27:29.535000 | 2019-10-30T19:22:51 | 2019-10-30T19:22:51 | 217,722,006 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aircraftModels;
import java.util.HashMap;
import interfaces.AttackingTarget;
import interfaces.CarryingWeapons;
import people.Person;
import simulator.Map;
import simulator.Simulator;
public class MilitaryPlane extends Airplane implements CarryingWeapons, AttackingTarget{
private boolean hostMilitaryPlane;
public boolean isInAir;
public MilitaryPlane() {
super();
}
public MilitaryPlane(String model, String id, int height, int speedOfFlight,HashMap<String, String>characteristics, Person[] persons,boolean status ) {
super(model,id,height,speedOfFlight,characteristics,persons);
this.hostMilitaryPlane=status;
isInAir=true;
}
public void setIsInAir(boolean status) {
isInAir=status;
}
public boolean IsHost() {
return hostMilitaryPlane;
}
@Override
public void run() {
if(!hostMilitaryPlane) isForeignMilitaryObjectPresent=true;
if ("U".equals(characteristics.get("Position"))) {
int column=Integer.parseInt(characteristics.get("Column position"));
for (int position = 0; position < Map.getNumberRows(); position++) {
//if (isDestroyed) return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[position][column].getSize() != 0)
{
if (checkIfCrashHappenedUpOrDown(position,column, "U")) {
Simulator.militaryThreads.remove(this);
return;
}
} else {
this.updateMapUpOrDownMoving(position,column, "U");
if(position==(Map.getNumberRows()-1)) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("D".equals(characteristics.get("Position"))) {
int column=Integer.parseInt(characteristics.get("Column position"));
for (int position = Map.getNumberRows() - 1; position >= 0; position--) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[position][column].getSize() != 0) {
if (checkIfCrashHappenedUpOrDown(position,column, "D")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapUpOrDownMoving(position,column, "D");
if(position==0) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("L".equals(characteristics.get("Position"))) {
int row=Integer.parseInt(characteristics.get("Row position"));
for (int position = 0; position < Map.getNumberColumns(); position++) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[row][position].getSize() != 0) {
if (checkIfCrashHappenedLeftOrRight(row,position, "L")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapLeftOrRightMoving(row,position, "L");
if(position==(Map.getNumberColumns()-1)) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("R".equals(characteristics.get("Position"))) {
int row=Integer.parseInt(characteristics.get("Row position"));
for (int position = Map.getNumberColumns() - 1; position >= 0; position--) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[row][position].getSize() != 0) {
if (checkIfCrashHappenedLeftOrRight(row,position, "R")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapLeftOrRightMoving(row,position, "R");
if(position==0) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
}
}
| UTF-8 | Java | 4,141 | java | MilitaryPlane.java | Java | []
| null | []
| package aircraftModels;
import java.util.HashMap;
import interfaces.AttackingTarget;
import interfaces.CarryingWeapons;
import people.Person;
import simulator.Map;
import simulator.Simulator;
public class MilitaryPlane extends Airplane implements CarryingWeapons, AttackingTarget{
private boolean hostMilitaryPlane;
public boolean isInAir;
public MilitaryPlane() {
super();
}
public MilitaryPlane(String model, String id, int height, int speedOfFlight,HashMap<String, String>characteristics, Person[] persons,boolean status ) {
super(model,id,height,speedOfFlight,characteristics,persons);
this.hostMilitaryPlane=status;
isInAir=true;
}
public void setIsInAir(boolean status) {
isInAir=status;
}
public boolean IsHost() {
return hostMilitaryPlane;
}
@Override
public void run() {
if(!hostMilitaryPlane) isForeignMilitaryObjectPresent=true;
if ("U".equals(characteristics.get("Position"))) {
int column=Integer.parseInt(characteristics.get("Column position"));
for (int position = 0; position < Map.getNumberRows(); position++) {
//if (isDestroyed) return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[position][column].getSize() != 0)
{
if (checkIfCrashHappenedUpOrDown(position,column, "U")) {
Simulator.militaryThreads.remove(this);
return;
}
} else {
this.updateMapUpOrDownMoving(position,column, "U");
if(position==(Map.getNumberRows()-1)) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("D".equals(characteristics.get("Position"))) {
int column=Integer.parseInt(characteristics.get("Column position"));
for (int position = Map.getNumberRows() - 1; position >= 0; position--) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[position][column].getSize() != 0) {
if (checkIfCrashHappenedUpOrDown(position,column, "D")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapUpOrDownMoving(position,column, "D");
if(position==0) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("L".equals(characteristics.get("Position"))) {
int row=Integer.parseInt(characteristics.get("Row position"));
for (int position = 0; position < Map.getNumberColumns(); position++) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[row][position].getSize() != 0) {
if (checkIfCrashHappenedLeftOrRight(row,position, "L")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapLeftOrRightMoving(row,position, "L");
if(position==(Map.getNumberColumns()-1)) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
else if ("R".equals(characteristics.get("Position"))) {
int row=Integer.parseInt(characteristics.get("Row position"));
for (int position = Map.getNumberColumns() - 1; position >= 0; position--) {
//if (isDestroyed)
//return;
if (checkIfIsCrashedAircraft()) {
Simulator.militaryThreads.remove(this);
return;
}
synchronized (Simulator.monitor) {
if (Map.matrix[row][position].getSize() != 0) {
if (checkIfCrashHappenedLeftOrRight(row,position, "R")) {
Simulator.militaryThreads.remove(this);
return;
}
}
else {
this.updateMapLeftOrRightMoving(row,position, "R");
if(position==0) Simulator.militaryThreads.remove(this);
}
}
tSleep(speedOfFlight);
}
}
}
}
| 4,141 | 0.639218 | 0.635837 | 164 | 24.25 | 26.617979 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.97561 | false | false | 0 |
89ee1b878805da37920165384b2b518b3ac777fe | 10,496,900,124,917 | cded047b108ca12c125076c0db18b57f7002b301 | /LTA_DB_Project/LTA/src/com/fym/lta/DTO/DepartmentDto.java | 78100a7f586d16fff3b43699981fac4ab6d58646 | []
| no_license | IslamReda/Locations-Tracker-Application | https://github.com/IslamReda/Locations-Tracker-Application | 1ae99c7afd2260863f4e11bb1b025aba30e23d21 | 6af48fde741ff01b6923f9096811da5af25c7882 | refs/heads/master | 2023-03-21T03:15:33.310000 | 2021-03-14T09:21:08 | 2021-03-14T09:21:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fym.lta.DTO;
import java.util.List;
/**class to define department attributes with setters, getters and constructors
*/
public class DepartmentDto {
/* department id */
private int id;
/* department code */
private String code;
/* department name */
private String name;
/* department faculty */
private FacultyDto faculty;
/* list of staff members of department */
private List<StaffDto> depart_staff;
/* list of department stages */
private List<StageDto> Stages;
/* courses of department */
private CourseDepartDto courses;
/* department search key */
private String search;
/* list of buildings for department */
private List<BuildingDto> buildings;
/**
* class constructor from name
* @param name string
*/
public DepartmentDto(String name) {
this.name = name;
}
/**
* class constructor from id attribute
* @param id int
*/
public DepartmentDto(int id) {
this.id = id;
}
/**
* seatch attribute setter
* @param search string
*/
public void setSearch(String search) {
this.search = search;
}
/**
* search attribute getter
* @return seatch string
*/
public String getSearch() {
return search;
}
/**
* faculty attribute setter
* @param faculty
*/
public void setFaculty(FacultyDto faculty) {
this.faculty = faculty;
}
/**
* faculty attribute getter
* @return faculty
*/
public FacultyDto getFaculty() {
return faculty;
}
/**
* building of department attribute setter
* @param building
*/
public void setBuilding(DepartBuildingDto building) {
this.building = building;
}
/**
* building of department attribute getter
* @return building
*/
public DepartBuildingDto getBuilding() {
return building;
}
/**
* list of department staff members setter
* @param depart_staff list
*/
public void setDepart_staff(List<StaffDto> depart_staff) {
this.depart_staff = depart_staff;
}
/**
* list of department staff members getter
* @return list of staff members
*/
public List<StaffDto> getDepart_staff() {
return depart_staff;
}
/**
* list of department stages setter
* @param Stages
*/
public void setStages(List<StageDto> Stages) {
this.Stages = Stages;
}
/**
*list of deoartment stages attribute getter
* @return list of stages
*/
public List<StageDto> getStages() {
return Stages;
}
/**
* course of department attribute setter
* @param courses
*/
public void setCourses(CourseDepartDto courses) {
this.courses = courses;
}
/**
* courses of department attribute getter
* @return courses
*/
public CourseDepartDto getCourses() {
return courses;
}
/**
* class main constructor
*/
public DepartmentDto() {
super();
}
/**
* code attribute setter
* @param code string
*/
public void setCode(String code) {
this.code = code;
}
/**
* code attribute getter
* @return code string
*/
public String getCode() {
return code;
}
/**
* constructor of code, name and id
* @param code
* @param name
* @param id
*/
public DepartmentDto(String code, String name, int id) {
this.code = code;
this.name = name;
this.id = id;
}
/**
* name attribute setter
* @param name string
*/
public void setName(String name) {
this.name = name;
}
/**
* name attribute getter
* @return name string
*/
public String getName() {
return name;
}
/**
* id attribute setter
* @param id int
*/
public void setId(int id) {
this.id = id;
}
/**
* id attribute getter
* @return id int
*/
public int getId() {
return id;
}
/**
* list of buildings attribute setter
* @param buildings list
*/
public void setBuildings(List<BuildingDto> buildings) {
this.buildings = buildings;
}
/**
* list of buildings attribute getter
* @return buildings list
*/
public List<BuildingDto> getBuildings() {
return buildings;
}
private StageDto stage;
private DepartBuildingDto building;
public void setStage(StageDto stage) {
this.stage = stage;
}
public StageDto getStage() {
return stage;
}
}
| UTF-8 | Java | 4,745 | java | DepartmentDto.java | Java | []
| null | []
| package com.fym.lta.DTO;
import java.util.List;
/**class to define department attributes with setters, getters and constructors
*/
public class DepartmentDto {
/* department id */
private int id;
/* department code */
private String code;
/* department name */
private String name;
/* department faculty */
private FacultyDto faculty;
/* list of staff members of department */
private List<StaffDto> depart_staff;
/* list of department stages */
private List<StageDto> Stages;
/* courses of department */
private CourseDepartDto courses;
/* department search key */
private String search;
/* list of buildings for department */
private List<BuildingDto> buildings;
/**
* class constructor from name
* @param name string
*/
public DepartmentDto(String name) {
this.name = name;
}
/**
* class constructor from id attribute
* @param id int
*/
public DepartmentDto(int id) {
this.id = id;
}
/**
* seatch attribute setter
* @param search string
*/
public void setSearch(String search) {
this.search = search;
}
/**
* search attribute getter
* @return seatch string
*/
public String getSearch() {
return search;
}
/**
* faculty attribute setter
* @param faculty
*/
public void setFaculty(FacultyDto faculty) {
this.faculty = faculty;
}
/**
* faculty attribute getter
* @return faculty
*/
public FacultyDto getFaculty() {
return faculty;
}
/**
* building of department attribute setter
* @param building
*/
public void setBuilding(DepartBuildingDto building) {
this.building = building;
}
/**
* building of department attribute getter
* @return building
*/
public DepartBuildingDto getBuilding() {
return building;
}
/**
* list of department staff members setter
* @param depart_staff list
*/
public void setDepart_staff(List<StaffDto> depart_staff) {
this.depart_staff = depart_staff;
}
/**
* list of department staff members getter
* @return list of staff members
*/
public List<StaffDto> getDepart_staff() {
return depart_staff;
}
/**
* list of department stages setter
* @param Stages
*/
public void setStages(List<StageDto> Stages) {
this.Stages = Stages;
}
/**
*list of deoartment stages attribute getter
* @return list of stages
*/
public List<StageDto> getStages() {
return Stages;
}
/**
* course of department attribute setter
* @param courses
*/
public void setCourses(CourseDepartDto courses) {
this.courses = courses;
}
/**
* courses of department attribute getter
* @return courses
*/
public CourseDepartDto getCourses() {
return courses;
}
/**
* class main constructor
*/
public DepartmentDto() {
super();
}
/**
* code attribute setter
* @param code string
*/
public void setCode(String code) {
this.code = code;
}
/**
* code attribute getter
* @return code string
*/
public String getCode() {
return code;
}
/**
* constructor of code, name and id
* @param code
* @param name
* @param id
*/
public DepartmentDto(String code, String name, int id) {
this.code = code;
this.name = name;
this.id = id;
}
/**
* name attribute setter
* @param name string
*/
public void setName(String name) {
this.name = name;
}
/**
* name attribute getter
* @return name string
*/
public String getName() {
return name;
}
/**
* id attribute setter
* @param id int
*/
public void setId(int id) {
this.id = id;
}
/**
* id attribute getter
* @return id int
*/
public int getId() {
return id;
}
/**
* list of buildings attribute setter
* @param buildings list
*/
public void setBuildings(List<BuildingDto> buildings) {
this.buildings = buildings;
}
/**
* list of buildings attribute getter
* @return buildings list
*/
public List<BuildingDto> getBuildings() {
return buildings;
}
private StageDto stage;
private DepartBuildingDto building;
public void setStage(StageDto stage) {
this.stage = stage;
}
public StageDto getStage() {
return stage;
}
}
| 4,745 | 0.568809 | 0.568809 | 244 | 18.446722 | 16.011562 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.184426 | false | false | 0 |
ea24e06956f0c4af1b73b0b06af4270866981340 | 18,348,100,331,603 | c717ccc8463ad501e53bdd347516a1311dc2efe4 | /Braille/app/src/main/java/com/example/miseon/braille/ManualActivity.java | 6046662bb1f433409a76d5309424aee46807c4b3 | []
| no_license | 11mia/zoljak | https://github.com/11mia/zoljak | 0f47f58e8ff681fd880d676173f2d794a0c210a1 | 68512ff9b6dd8d473a872867047293fb6870e205 | refs/heads/master | 2021-09-13T14:48:20.880000 | 2018-05-01T11:36:09 | 2018-05-01T11:36:09 | 116,907,805 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.miseon.braille;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import uk.co.senab.photoview.PhotoViewAttacher;
public class ManualActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
int page;
ImageView im;
private ConstraintLayout main;
private static final int SWIPE_MIN_DISTANCE = 100;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureScanner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent it = getIntent();
page =it.getIntExtra("page",1);
im = (ImageView)this.findViewById(R.id.manualIV);
PhotoViewAttacher attacher;
attacher = new PhotoViewAttacher(im);
Resources res = getResources();
String str = "p"+page;
int id_img = res.getIdentifier(str, "drawable", getPackageName());
im.setImageResource(id_img);
setTitle("도움말("+page+"/12)");
gestureScanner = new GestureDetector(this);
main = (ConstraintLayout)findViewById(R.id.manualLayout);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureScanner.onTouchEvent(me);
}
public boolean onDown(MotionEvent e) {
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(page==12){
Toast toast = Toast.makeText(this,"마지막 페이지 입니다.",Toast.LENGTH_LONG);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
toast.show();
}else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",++page);
startActivity(it);
im.setImageResource(0);
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
finish();
}
}
// left to right swipe
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(page==1){
im.setImageResource(0);
finish();
}
else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",--page);
startActivity(it);
overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right);
im.setImageResource(0);
finish();
}
}
} catch (Exception e) {
}
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//onBackPressed();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickPrevious(View v){
if(page==1){
im.setImageResource(0);
finish();
}
else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",--page);
startActivity(it);
overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right);
im.setImageResource(0);
finish();
}
}
public void clickNext(View v){
if(page==12){
Toast toast = Toast.makeText(this,"마지막 페이지 입니다.",Toast.LENGTH_LONG);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
toast.show();
return;
}else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",++page);
startActivity(it);
im.setImageResource(0);
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
finish();
}
}
}
| UTF-8 | Java | 5,579 | java | ManualActivity.java | Java | [
{
"context": "package com.example.miseon.braille;\n\nimport android.content.Intent;\nimport",
"end": 24,
"score": 0.5915713906288147,
"start": 21,
"tag": "USERNAME",
"value": "ise"
}
]
| null | []
| package com.example.miseon.braille;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import uk.co.senab.photoview.PhotoViewAttacher;
public class ManualActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
int page;
ImageView im;
private ConstraintLayout main;
private static final int SWIPE_MIN_DISTANCE = 100;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private GestureDetector gestureScanner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent it = getIntent();
page =it.getIntExtra("page",1);
im = (ImageView)this.findViewById(R.id.manualIV);
PhotoViewAttacher attacher;
attacher = new PhotoViewAttacher(im);
Resources res = getResources();
String str = "p"+page;
int id_img = res.getIdentifier(str, "drawable", getPackageName());
im.setImageResource(id_img);
setTitle("도움말("+page+"/12)");
gestureScanner = new GestureDetector(this);
main = (ConstraintLayout)findViewById(R.id.manualLayout);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureScanner.onTouchEvent(me);
}
public boolean onDown(MotionEvent e) {
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(page==12){
Toast toast = Toast.makeText(this,"마지막 페이지 입니다.",Toast.LENGTH_LONG);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
toast.show();
}else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",++page);
startActivity(it);
im.setImageResource(0);
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
finish();
}
}
// left to right swipe
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
if(page==1){
im.setImageResource(0);
finish();
}
else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",--page);
startActivity(it);
overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right);
im.setImageResource(0);
finish();
}
}
} catch (Exception e) {
}
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//onBackPressed();
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void clickPrevious(View v){
if(page==1){
im.setImageResource(0);
finish();
}
else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",--page);
startActivity(it);
overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_out_right);
im.setImageResource(0);
finish();
}
}
public void clickNext(View v){
if(page==12){
Toast toast = Toast.makeText(this,"마지막 페이지 입니다.",Toast.LENGTH_LONG);
ViewGroup group = (ViewGroup) toast.getView();
TextView messageTextView = (TextView) group.getChildAt(0);
messageTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
toast.show();
return;
}else{
Intent it = new Intent(this,ManualActivity.class);
it.putExtra("page",++page);
startActivity(it);
im.setImageResource(0);
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left);
finish();
}
}
}
| 5,579 | 0.58967 | 0.582265 | 171 | 31.380117 | 27.125687 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 0 |
34e352e0e6a1c63923ad658c25391b699434a90c | 27,195,732,971,738 | 1a841d13176be91b7beb8d22d28c3361e7ff1af4 | /semaphore-admin-backend/src/main/java/it/uniroma2/sdcc/admintrafficcontrol/dao/MobileSensorDAO.java | 65bc2d9b34fc04b4cc2179cca0d9a7ce8431ecbd | []
| no_license | alfredo-milani/trafficcontrol | https://github.com/alfredo-milani/trafficcontrol | e1d3728924843b27a5112cf938394efa892b1b72 | d8571332cc523bf72e1db08fb7662d0f29f31ff1 | refs/heads/master | 2021-08-24T12:52:40.953000 | 2018-09-25T20:12:49 | 2018-09-25T20:12:49 | 133,148,201 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.uniroma2.sdcc.admintrafficcontrol.dao;
import it.uniroma2.sdcc.admintrafficcontrol.entity.MobileSensor;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MobileSensorDAO extends JpaRepository<MobileSensor, Long> {
}
| UTF-8 | Java | 259 | java | MobileSensorDAO.java | Java | []
| null | []
| package it.uniroma2.sdcc.admintrafficcontrol.dao;
import it.uniroma2.sdcc.admintrafficcontrol.entity.MobileSensor;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MobileSensorDAO extends JpaRepository<MobileSensor, Long> {
}
| 259 | 0.849421 | 0.841699 | 8 | 31.375 | 31.85882 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
32320bdce9f62c9cb261c5a6590dc72d03cd7292 | 5,849,745,521,067 | 6063ea33077de004542bc1bd4968dc7f6fc1c1d5 | /export_web_manager/src/main/java/cn/itcast/web/controller/cargo/ExtCproductController.java | 338ca5fba0832bffddb7a97b6072b68943f0d543 | []
| no_license | ChinZcode/export_parent | https://github.com/ChinZcode/export_parent | 9edb1cf063c8f95dbd6e11f29920b1f4da5f253a | 7e404506c9c0dc5b8b2549ff2edb928a57d21e68 | refs/heads/master | 2020-07-11T03:52:01.132000 | 2019-08-26T08:37:41 | 2019-08-26T08:39:18 | 204,439,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.itcast.web.controller.cargo;
import cn.itcast.domain.cargo.ExtCproduct;
import cn.itcast.domain.cargo.ExtCproductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ExtCproductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
@RequestMapping(value = "/cargo/extCproduct")
public class ExtCproductController extends BaseController{
@Reference
private FactoryService factoryService;
@Reference
private ExtCproductService extCproductService;
@RequestMapping(value = "/list")
public String list(String contractId, String contractProductId,
@RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "5")int pageSize){
//1.查询附件的生产厂家
FactoryExample factoryExample = new FactoryExample();
FactoryExample.Criteria criteria = factoryExample.createCriteria();
criteria.andCtypeEqualTo("附件");
List<Factory> factoryList = factoryService.findAll(factoryExample);
request.setAttribute("factoryList",factoryList);
//2.查询当前货物下的所有附件
ExtCproductExample extCproductExample = new ExtCproductExample();
ExtCproductExample.Criteria criteria1 = extCproductExample.createCriteria();
criteria1.andContractIdEqualTo(contractId);
PageInfo pageInfo = extCproductService.findByPage(extCproductExample,pageNum,pageSize);
request.setAttribute("pageInfo",pageInfo);
//3.设置页面的基本参数:id
request.setAttribute("contractId",contractId);
request.setAttribute("contractProductId",contractProductId);
return "cargo/extc/extc-list";
}
@RequestMapping(value = "/edit")
public String edit(ExtCproduct extCproduct){
extCproduct.setCompanyId(getLoginCompanyId());
extCproduct.setCompanyName(getLoginCompanyName());
if (StringUtils.isEmpty(extCproduct.getId())){
extCproductService.save(extCproduct);
}else {extCproductService.update(extCproduct);}
return "redirect:/cargo/extCproduct/list.do?contractId="+extCproduct.getContractId()+"&contractProductId="+extCproduct.getContractProductId();
}
/**
* 3. 附件修改(1)进入修改页面
* 请求地址:http://localhost:8080/cargo/extCproduct/toUpdate.do?id=0
*/
@RequestMapping("/toUpdate")
public String toUpdate(String id){
//3.1 根据附件id查询
ExtCproduct extCproduct = extCproductService.findById(id);
//3.2 查询附件工厂
FactoryExample factoryExample = new FactoryExample();
factoryExample.createCriteria().andCtypeEqualTo("附件");
List<Factory> factoryList = factoryService.findAll(factoryExample);
//3.3 保存
request.setAttribute("extCproduct",extCproduct);
request.setAttribute("factoryList",factoryList);
return "cargo/extc/extc-update";
}
/**
* 4. 删除附件
* 请求地址:http://localhost:8080/cargo/extCproduct/delete.do
* 请求参数:
* id 附件id
* contractId 购销合同id 【为了重定向到列表】
* contractProductId 货物id 【为了重定向到列表】
*/
@RequestMapping("/delete")
public String delete(String id,String contractId,String contractProductId){
// 调用service删除
extCproductService.delete(id);
return "redirect:/cargo/extCproduct/list.do?contractId="+
contractId + "&contractProductId=" + contractProductId;
}
//上传货物
@RequestMapping("/toImport")
public String toImport(String contractId){
request.setAttribute("contractId",contractId);
return "/cargo/product/product-import";
}
}
| UTF-8 | Java | 4,265 | java | ExtCproductController.java | Java | []
| null | []
| package cn.itcast.web.controller.cargo;
import cn.itcast.domain.cargo.ExtCproduct;
import cn.itcast.domain.cargo.ExtCproductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ExtCproductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
@RequestMapping(value = "/cargo/extCproduct")
public class ExtCproductController extends BaseController{
@Reference
private FactoryService factoryService;
@Reference
private ExtCproductService extCproductService;
@RequestMapping(value = "/list")
public String list(String contractId, String contractProductId,
@RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "5")int pageSize){
//1.查询附件的生产厂家
FactoryExample factoryExample = new FactoryExample();
FactoryExample.Criteria criteria = factoryExample.createCriteria();
criteria.andCtypeEqualTo("附件");
List<Factory> factoryList = factoryService.findAll(factoryExample);
request.setAttribute("factoryList",factoryList);
//2.查询当前货物下的所有附件
ExtCproductExample extCproductExample = new ExtCproductExample();
ExtCproductExample.Criteria criteria1 = extCproductExample.createCriteria();
criteria1.andContractIdEqualTo(contractId);
PageInfo pageInfo = extCproductService.findByPage(extCproductExample,pageNum,pageSize);
request.setAttribute("pageInfo",pageInfo);
//3.设置页面的基本参数:id
request.setAttribute("contractId",contractId);
request.setAttribute("contractProductId",contractProductId);
return "cargo/extc/extc-list";
}
@RequestMapping(value = "/edit")
public String edit(ExtCproduct extCproduct){
extCproduct.setCompanyId(getLoginCompanyId());
extCproduct.setCompanyName(getLoginCompanyName());
if (StringUtils.isEmpty(extCproduct.getId())){
extCproductService.save(extCproduct);
}else {extCproductService.update(extCproduct);}
return "redirect:/cargo/extCproduct/list.do?contractId="+extCproduct.getContractId()+"&contractProductId="+extCproduct.getContractProductId();
}
/**
* 3. 附件修改(1)进入修改页面
* 请求地址:http://localhost:8080/cargo/extCproduct/toUpdate.do?id=0
*/
@RequestMapping("/toUpdate")
public String toUpdate(String id){
//3.1 根据附件id查询
ExtCproduct extCproduct = extCproductService.findById(id);
//3.2 查询附件工厂
FactoryExample factoryExample = new FactoryExample();
factoryExample.createCriteria().andCtypeEqualTo("附件");
List<Factory> factoryList = factoryService.findAll(factoryExample);
//3.3 保存
request.setAttribute("extCproduct",extCproduct);
request.setAttribute("factoryList",factoryList);
return "cargo/extc/extc-update";
}
/**
* 4. 删除附件
* 请求地址:http://localhost:8080/cargo/extCproduct/delete.do
* 请求参数:
* id 附件id
* contractId 购销合同id 【为了重定向到列表】
* contractProductId 货物id 【为了重定向到列表】
*/
@RequestMapping("/delete")
public String delete(String id,String contractId,String contractProductId){
// 调用service删除
extCproductService.delete(id);
return "redirect:/cargo/extCproduct/list.do?contractId="+
contractId + "&contractProductId=" + contractProductId;
}
//上传货物
@RequestMapping("/toImport")
public String toImport(String contractId){
request.setAttribute("contractId",contractId);
return "/cargo/product/product-import";
}
}
| 4,265 | 0.708158 | 0.701959 | 100 | 39.330002 | 27.547434 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 0 |
09ae5dbd3fb8ccff2210a76a7aede15046e03413 | 16,355,235,463,359 | 1c9f4d5413d8e1bd8f305b1eb466cb6bb0977746 | /src/main/java/task5/Main.java | a2d3b017d309804c00ae4143146664d2135849c5 | []
| no_license | VenyaminBakhar/mysecondhomework | https://github.com/VenyaminBakhar/mysecondhomework | ac19477b9fe61bd57fe8556b17be8d25656dc070 | e8da7fb6e25806f4940ce5975d6008c9810c222d | refs/heads/master | 2020-12-30T11:01:38.101000 | 2017-07-30T23:56:18 | 2017-07-30T23:56:18 | 98,831,647 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package task5;
/**
* Created by Вениамин on 7/10/2017.
*/
public class Main {
public static void main(String[] args) {
Student student = new Student("lol");
student.addSubject(new Math(4.5));
student.addSubject(new Russian(5));
student.addSubject(new English(4));
student.addSubject(new Sport(3.2));
for (Subject subject : student.subjects){
System.out.println(subject.getMark()+" "+subject.getSubEnum());
}
}
}
| UTF-8 | Java | 501 | java | Main.java | Java | [
{
"context": "package task5;\n\n/**\n * Created by Вениамин on 7/10/2017.\n */\npublic class Main {\n public ",
"end": 42,
"score": 0.9998736381530762,
"start": 34,
"tag": "NAME",
"value": "Вениамин"
}
]
| null | []
| package task5;
/**
* Created by Вениамин on 7/10/2017.
*/
public class Main {
public static void main(String[] args) {
Student student = new Student("lol");
student.addSubject(new Math(4.5));
student.addSubject(new Russian(5));
student.addSubject(new English(4));
student.addSubject(new Sport(3.2));
for (Subject subject : student.subjects){
System.out.println(subject.getMark()+" "+subject.getSubEnum());
}
}
}
| 501 | 0.604463 | 0.576065 | 19 | 24.947369 | 22.302876 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 0 |
3cd000edae39e373c38bf8a14f8df30104a35bfc | 3,195,455,679,684 | 04a1cd84cda9d513e9e626e6fdef5e2e78391c11 | /src/Indice_P_P_L.java | 10b38c332c4f3bcd4dc32c58fcf39c9d39c60739 | []
| no_license | krazounet/SmartLogic | https://github.com/krazounet/SmartLogic | a0caa3702546bc0294c0fdb8ce19e466bdf6298d | 10f5630bae69637ec1698e823adc8ee710a25781 | refs/heads/master | 2023-06-01T14:27:49.698000 | 2021-06-23T17:23:52 | 2021-06-23T17:23:52 | 373,252,924 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import Enum.*;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//Le personage P est avec le personnage P dans la piece L
public final class Indice_P_P_L extends Indice{
List <Personne> list_personne;
Piece piece;
public Indice_P_P_L(String desc, boolean negation,List<Personne> lp, Piece piece) {
super.typeIndice =TypeIndice.P_P_L;
super.description=desc;
super.negation=negation;
super.localisationIndice=LocalisationIndice.LIGNE;
this.list_personne = lp;
this.piece = piece;
}
@Override
public boolean check(Solution solution)
{
boolean valueToReturn = true;
for(int idPA = 0; idPA < this.list_personne.size() - 1; idPA++)
{
Personne personne1 = this.list_personne.get(idPA);
for(int idPB = idPA + 1; idPB < this.list_personne.size(); idPB++)
{
Personne personne2 = this.list_personne.get(idPB);
if(solution.stats.get("Met_" + personne1.name() + personne2.name() + this.piece.name()) == null)
valueToReturn = false;
}
}
return(valueToReturn);
// return(solution.stats.get("Met_" + this.list_personne.get(0).name() + this.list_personne.get(1).name() + this.piece.name()) != null);
}
public static List<Indice_P_P_L> all_PPL(Solution solution){
List<Indice_P_P_L> list_a_retourner =new ArrayList<>();
for(Moment moment : ConfigPartie.list_moments_partie){
for(Piece piece : ConfigPartie.list_pieces_partie) {
List<Personne> list_p_temp =new ArrayList<>();
for (Reservation reservation : solution.solution){
if ((moment == reservation.moment) && (piece == reservation.lieu.piece)){
list_p_temp.add(reservation.personne);
}
}
if (list_p_temp.size() > 1){
String desc="A un moment, ";
for(Personne personne : list_p_temp){
desc=desc+personne+" ,";
}
desc=desc+" sont ensemble dans la piece "+piece;
list_a_retourner.add(new Indice_P_P_L(desc, false,list_p_temp,piece));
}
}
}
return list_a_retourner;
}
@Override
public BufferedImage export() {
BufferedImage image_indice = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
DrawTools.drawImageTransformed(image_indice, DrawTools.getImage("image/LieuV.png"), 50, 50, 0, 100);
List<List<Point>> listListPosCharacter = Arrays.asList(
Collections.singletonList(new Point(2, 2)),
Arrays.asList(new Point(1, 2), new Point(3, 2)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(2, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(1, 3), new Point(3, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(2, 2), new Point(1, 3), new Point(3, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(1, 2), new Point(3, 2), new Point(1, 3), new Point(3, 3))
);
for (int index_pers=0;index_pers<list_personne.size();index_pers++){
BufferedImage image_pers = DrawTools.getImage("image\\"+list_personne.get(index_pers)+".png");
DrawTools.drawImageTransformed(image_indice,image_pers,25 * listListPosCharacter.get(list_personne.size() - 1).get(index_pers).x,25 * listListPosCharacter.get(list_personne.size() - 1).get(index_pers).y,0,40);
}
/* int x_img=25;
int y_img=25;
for (int index_pers=0;index_pers<list_personne.size();index_pers++){
BufferedImage image_pers = DrawTools.getImage("image\\"+list_personne.get(index_pers)+".png");
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_pers,x_img,y_img,0,50);
if (index_pers == 0) {x_img=x_img+50;}
if (index_pers == 1) {x_img=25;y_img=75;}
if (index_pers == 2) {x_img=x_img+50;}
////BUG si 5 PERSONNES ///
}
BufferedImage image_lien = DrawTools.getImage("image\\lien.png");
if (list_personne.size()<3){
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_lien,50,75,0,50);
}else{
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_lien,50,50,0,50);
}*/
return image_indice;
}
@Override
public String getEmplacement() {
return ""+piece;
}
@Override
public Coordonnee getCoordonnee() {
int x=50 + (ConfigPartie.list_moments_partie.size()+1)*100;
int y=50 + (piece.ordinal()+1)*100;
return new Coordonnee(x,y);
}
}
| UTF-8 | Java | 4,875 | java | Indice_P_P_L.java | Java | []
| null | []
| import Enum.*;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
//Le personage P est avec le personnage P dans la piece L
public final class Indice_P_P_L extends Indice{
List <Personne> list_personne;
Piece piece;
public Indice_P_P_L(String desc, boolean negation,List<Personne> lp, Piece piece) {
super.typeIndice =TypeIndice.P_P_L;
super.description=desc;
super.negation=negation;
super.localisationIndice=LocalisationIndice.LIGNE;
this.list_personne = lp;
this.piece = piece;
}
@Override
public boolean check(Solution solution)
{
boolean valueToReturn = true;
for(int idPA = 0; idPA < this.list_personne.size() - 1; idPA++)
{
Personne personne1 = this.list_personne.get(idPA);
for(int idPB = idPA + 1; idPB < this.list_personne.size(); idPB++)
{
Personne personne2 = this.list_personne.get(idPB);
if(solution.stats.get("Met_" + personne1.name() + personne2.name() + this.piece.name()) == null)
valueToReturn = false;
}
}
return(valueToReturn);
// return(solution.stats.get("Met_" + this.list_personne.get(0).name() + this.list_personne.get(1).name() + this.piece.name()) != null);
}
public static List<Indice_P_P_L> all_PPL(Solution solution){
List<Indice_P_P_L> list_a_retourner =new ArrayList<>();
for(Moment moment : ConfigPartie.list_moments_partie){
for(Piece piece : ConfigPartie.list_pieces_partie) {
List<Personne> list_p_temp =new ArrayList<>();
for (Reservation reservation : solution.solution){
if ((moment == reservation.moment) && (piece == reservation.lieu.piece)){
list_p_temp.add(reservation.personne);
}
}
if (list_p_temp.size() > 1){
String desc="A un moment, ";
for(Personne personne : list_p_temp){
desc=desc+personne+" ,";
}
desc=desc+" sont ensemble dans la piece "+piece;
list_a_retourner.add(new Indice_P_P_L(desc, false,list_p_temp,piece));
}
}
}
return list_a_retourner;
}
@Override
public BufferedImage export() {
BufferedImage image_indice = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
DrawTools.drawImageTransformed(image_indice, DrawTools.getImage("image/LieuV.png"), 50, 50, 0, 100);
List<List<Point>> listListPosCharacter = Arrays.asList(
Collections.singletonList(new Point(2, 2)),
Arrays.asList(new Point(1, 2), new Point(3, 2)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(2, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(1, 3), new Point(3, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(2, 2), new Point(1, 3), new Point(3, 3)),
Arrays.asList(new Point(1, 1), new Point(3, 1), new Point(1, 2), new Point(3, 2), new Point(1, 3), new Point(3, 3))
);
for (int index_pers=0;index_pers<list_personne.size();index_pers++){
BufferedImage image_pers = DrawTools.getImage("image\\"+list_personne.get(index_pers)+".png");
DrawTools.drawImageTransformed(image_indice,image_pers,25 * listListPosCharacter.get(list_personne.size() - 1).get(index_pers).x,25 * listListPosCharacter.get(list_personne.size() - 1).get(index_pers).y,0,40);
}
/* int x_img=25;
int y_img=25;
for (int index_pers=0;index_pers<list_personne.size();index_pers++){
BufferedImage image_pers = DrawTools.getImage("image\\"+list_personne.get(index_pers)+".png");
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_pers,x_img,y_img,0,50);
if (index_pers == 0) {x_img=x_img+50;}
if (index_pers == 1) {x_img=25;y_img=75;}
if (index_pers == 2) {x_img=x_img+50;}
////BUG si 5 PERSONNES ///
}
BufferedImage image_lien = DrawTools.getImage("image\\lien.png");
if (list_personne.size()<3){
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_lien,50,75,0,50);
}else{
DrawTools.drawImageTransformed(image_indice.getGraphics(),image_lien,50,50,0,50);
}*/
return image_indice;
}
@Override
public String getEmplacement() {
return ""+piece;
}
@Override
public Coordonnee getCoordonnee() {
int x=50 + (ConfigPartie.list_moments_partie.size()+1)*100;
int y=50 + (piece.ordinal()+1)*100;
return new Coordonnee(x,y);
}
}
| 4,875 | 0.593641 | 0.56841 | 126 | 37.690475 | 36.901299 | 221 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.452381 | false | false | 0 |
4991c7d0ffc47bef89d058f1bd8b883ee7a17950 | 25,555,055,441,718 | 35880550e2922030ec68161d55b2519f2fd6b04b | /UE4_SolvePuzzle/src/at/skert/swe/ue4/implementation/Main.java | 632791a56f58b4d2ca854b3718cb96460d500d73 | []
| no_license | StefanKert/Java | https://github.com/StefanKert/Java | 8ef3d2f81c37d71d932a7168f75b43b03a14b024 | 83c075312026ace4f7c7ad5e7c33bc78339826ba | refs/heads/master | 2020-05-16T23:55:20.175000 | 2015-06-22T05:58:11 | 2015-06-22T05:58:19 | 33,009,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package at.skert.swe.ue4.implementation;
import at.skert.swe.ue4.exception.IllegalMoveException;
import at.skert.swe.ue4.exception.NoSolutionException;
public class Main {
public static void main(String[] args){
try {
SlidingPuzzle puzzle = new SlidingPuzzle();
Board board = Board.CreateGoalBoard(3);
board.shuffle();
puzzle.printMoves(board, puzzle.solve(board));
}catch(IllegalMoveException ex){
ex.printStackTrace();
} catch (NoSolutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 581 | java | Main.java | Java | []
| null | []
| package at.skert.swe.ue4.implementation;
import at.skert.swe.ue4.exception.IllegalMoveException;
import at.skert.swe.ue4.exception.NoSolutionException;
public class Main {
public static void main(String[] args){
try {
SlidingPuzzle puzzle = new SlidingPuzzle();
Board board = Board.CreateGoalBoard(3);
board.shuffle();
puzzle.printMoves(board, puzzle.solve(board));
}catch(IllegalMoveException ex){
ex.printStackTrace();
} catch (NoSolutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 581 | 0.695353 | 0.688468 | 20 | 28.049999 | 19.035427 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
78c86a72fa224f8434c7a0f9885b180d42d29de0 | 27,401,891,354,614 | 54af678809fdbcc1ba9c333a17e2aa4103080620 | /web/src/main/java/org/sample/web/components/TextAreaFieldBootstrapFormComponent.java | 80d9d67057ad700fc4da217a508a29c8e618566d | [
"MIT"
]
| permissive | b-cuts/wicket-spring-jpa-bootstrap-boilerplate | https://github.com/b-cuts/wicket-spring-jpa-bootstrap-boilerplate | 5a7bdfa713179727bb5938bb703103d94f0e76fd | c3bb60968fef74b72cda2bfe146c5284c3111ef9 | refs/heads/master | 2020-12-29T00:12:31.846000 | 2014-11-02T11:03:09 | 2014-11-02T11:03:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package org.sample.web.components;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
/**
* @author mpostelnicu
*
*/
public class TextAreaFieldBootstrapFormComponent<TYPE> extends GenericBootstrapFormComponent<TYPE, TextArea<TYPE>> {
/**
*
*/
private static final long serialVersionUID = 1L;
public TextAreaFieldBootstrapFormComponent(String id, IModel<String> labelModel, IModel<TYPE> model) {
super(id, labelModel, model);
}
public TextAreaFieldBootstrapFormComponent(String id, IModel<String> labelModel) {
super(id, labelModel, null);
}
@Override
protected TextArea<TYPE> inputField(String id, IModel<TYPE> model) {
return (TextArea<TYPE>) new TextArea<TYPE>(id,initFieldModel());
}
}
| UTF-8 | Java | 808 | java | TextAreaFieldBootstrapFormComponent.java | Java | [
{
"context": "org.apache.wicket.model.IModel;\r\n\r\n/**\r\n * @author mpostelnicu\r\n * \r\n */\r\npublic class TextAreaFieldBootstrapFor",
"end": 175,
"score": 0.9984043836593628,
"start": 164,
"tag": "USERNAME",
"value": "mpostelnicu"
}
]
| null | []
| /**
*
*/
package org.sample.web.components;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
/**
* @author mpostelnicu
*
*/
public class TextAreaFieldBootstrapFormComponent<TYPE> extends GenericBootstrapFormComponent<TYPE, TextArea<TYPE>> {
/**
*
*/
private static final long serialVersionUID = 1L;
public TextAreaFieldBootstrapFormComponent(String id, IModel<String> labelModel, IModel<TYPE> model) {
super(id, labelModel, model);
}
public TextAreaFieldBootstrapFormComponent(String id, IModel<String> labelModel) {
super(id, labelModel, null);
}
@Override
protected TextArea<TYPE> inputField(String id, IModel<TYPE> model) {
return (TextArea<TYPE>) new TextArea<TYPE>(id,initFieldModel());
}
}
| 808 | 0.710396 | 0.709158 | 34 | 21.764706 | 31.682301 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.029412 | false | false | 0 |
4ac8ed0012a456fe6a8bccc3ad3050bcc5794bde | 7,954,279,463,169 | 0756e9bbc386aa802d8141fb9e7a77e005378399 | /src/ProblemsIn_Java/Uri/Triangulo.java | 84eb8cb10ebcccb9a5236418923c7b5f163edad1 | []
| no_license | dayepesb/OnlineJudges | https://github.com/dayepesb/OnlineJudges | 85eae4de8a5c6c74cd7419bc314410b478dcbb6b | 0069c8aa644e6952348b7bf903ddd50f19b4e8e7 | refs/heads/master | 2021-07-15T06:49:35.228000 | 2020-05-10T07:33:46 | 2020-05-10T07:33:46 | 133,302,544 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ProblemsIn_Java.Uri;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Triangulo {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale("eng","US"));
BufferedReader inAux = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(inAux);
PrintWriter out = new PrintWriter(System.out);
double a = in.nextDouble(), b = in.nextDouble(), c = in.nextDouble(), perm, area;
if (a + b > c && b + c > a && a + c > b) {
perm = a + b + c;
out.printf("Perimetro = %.1f\n", perm);
} else {
area = .5 * (a + b) * c;
out.printf("Area = %.1f\n", area);
}
out.close();
in.close();
}
} | UTF-8 | Java | 775 | java | Triangulo.java | Java | []
| null | []
| package ProblemsIn_Java.Uri;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Triangulo {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale("eng","US"));
BufferedReader inAux = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(inAux);
PrintWriter out = new PrintWriter(System.out);
double a = in.nextDouble(), b = in.nextDouble(), c = in.nextDouble(), perm, area;
if (a + b > c && b + c > a && a + c > b) {
perm = a + b + c;
out.printf("Perimetro = %.1f\n", perm);
} else {
area = .5 * (a + b) * c;
out.printf("Area = %.1f\n", area);
}
out.close();
in.close();
}
} | 775 | 0.652903 | 0.649032 | 27 | 27.74074 | 21.867603 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.148148 | false | false | 0 |
d1b5833a93d364fe1a781d2d1b5ade5f16ec2ad1 | 16,527,034,198,234 | df1817701d95a1aba99d15fa5e8e24861c659ae3 | /src/IfElseStatement2.java | a1b5197e7947c5084c82feacbe7b51aab5358bc6 | []
| no_license | hasanislamqa/JavaBasic | https://github.com/hasanislamqa/JavaBasic | 4e7a2bc2be2b38c2964e4af18b2e9f9078e026db | de21a37db4530282221fabe2ead087118e8e6578 | refs/heads/master | 2020-05-24T16:34:50.124000 | 2020-01-04T15:38:08 | 2020-01-04T15:38:08 | 187,362,384 | 0 | 0 | null | false | 2020-01-04T15:38:09 | 2019-05-18T13:39:31 | 2019-12-29T16:10:24 | 2020-01-04T15:38:08 | 16 | 0 | 0 | 0 | Java | false | false | public class IfElseStatement2 {
static int banana=60;
static int apple=25;
public static void produce(){
if (banana>80){
System.out.println(banana);
}else{
System.out.println(apple);
}
}
}
| UTF-8 | Java | 252 | java | IfElseStatement2.java | Java | []
| null | []
| public class IfElseStatement2 {
static int banana=60;
static int apple=25;
public static void produce(){
if (banana>80){
System.out.println(banana);
}else{
System.out.println(apple);
}
}
}
| 252 | 0.555556 | 0.527778 | 18 | 13 | 14.075195 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 0 |
817340f1ef8f26d53175d86babb73d89c98d4f40 | 32,993,938,817,941 | f5a7d494a453f06a149298a66795c46b513d37cf | /app/src/main/java/com/support/android/designlibdemo/LoginActivity.java | e12cc2ecc7e26000171a930702f6c4ffb04749d2 | []
| no_license | tiaocarreiro99/GerenciadorReunioesApp | https://github.com/tiaocarreiro99/GerenciadorReunioesApp | 86f588c5fe3de97950e2e3f1eab845ef6c0b2c9f | a2decc3105d22bea814bb4cb704459ed30f1a4ee | refs/heads/master | 2020-12-24T06:31:14.828000 | 2016-12-05T21:59:14 | 2016-12-05T21:59:14 | 73,473,814 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.support.android.designlibdemo;
/**
* Created by alunos on 02/12/16.
*/
public class LoginActivity {
}
| UTF-8 | Java | 117 | java | LoginActivity.java | Java | [
{
"context": ".support.android.designlibdemo;\n\n/**\n * Created by alunos on 02/12/16.\n */\npublic class LoginActivity {\n}\n",
"end": 68,
"score": 0.999459445476532,
"start": 62,
"tag": "USERNAME",
"value": "alunos"
}
]
| null | []
| package com.support.android.designlibdemo;
/**
* Created by alunos on 02/12/16.
*/
public class LoginActivity {
}
| 117 | 0.717949 | 0.666667 | 7 | 15.714286 | 16.593582 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 0 |
681bc21c42654401f1c93207f1e69c4be9912626 | 31,585,189,543,236 | 8aeb82626fda5dfea8ea707c7f8bbcd2a97ef086 | /src/qureshi/asim/lab/concurrency/SampleDatabase.java | 3ab7144f3a6c261ebe7365a53bb3e4dfe50b04b8 | []
| no_license | asimqureshi/lab | https://github.com/asimqureshi/lab | 5cc004bee18a87c1f2e87e18c29bb71ca2ade4db | b67f4de075052cc90857bcc5a94de2f9aa89286f | refs/heads/master | 2020-05-16T14:07:49.655000 | 2014-11-09T21:11:20 | 2014-11-09T21:11:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package qureshi.asim.lab.concurrency;
import qureshi.asim.lab.concurrency.bufferqueue.QueueItem;
import java.util.*;
public class SampleDatabase {
private static final int TOT_ITEMS = Main.TOT_ITEMS;
private static final int FETCH_SIZE = Main.FETCH_SIZE;
private static Map<QueueItem, Boolean> database = Collections.synchronizedMap(new HashMap<QueueItem, Boolean>(TOT_ITEMS));
static {
for(int i=0;i<TOT_ITEMS;i++){
database.put(new QueueItem(i), Boolean.FALSE);
}
}
private static int timesDatabaseQueried = 1;
private static boolean isEmpty = false;
public static boolean isEmpty(){
return isEmpty;
}
public static synchronized List<QueueItem> queryItems( int fetchSize){
if(isEmpty) {
//System.out.println("Returning null...");
return null; }
// System.out.println("timesDatabaseQueried = " + timesDatabaseQueried);
List<QueueItem> returnItems = new ArrayList<QueueItem>(fetchSize);
int fetchCount = 0;
for (QueueItem queueItem : database.keySet()) {
if(!database.get(queueItem)) { //pickedFlag is false
returnItems.add(queueItem); //add to return list
database.put(queueItem, Boolean.TRUE); //update in database
fetchCount++;
if(fetchCount == FETCH_SIZE) break;
}
}
if(fetchCount == 0){
isEmpty = true;
System.err.println("Database is Empty now!!!! ::: in " + timesDatabaseQueried);
new RuntimeException("Database is Empty now!!!!" + timesDatabaseQueried);
}
timesDatabaseQueried++;
return returnItems;
}
}
| UTF-8 | Java | 1,775 | java | SampleDatabase.java | Java | []
| null | []
| package qureshi.asim.lab.concurrency;
import qureshi.asim.lab.concurrency.bufferqueue.QueueItem;
import java.util.*;
public class SampleDatabase {
private static final int TOT_ITEMS = Main.TOT_ITEMS;
private static final int FETCH_SIZE = Main.FETCH_SIZE;
private static Map<QueueItem, Boolean> database = Collections.synchronizedMap(new HashMap<QueueItem, Boolean>(TOT_ITEMS));
static {
for(int i=0;i<TOT_ITEMS;i++){
database.put(new QueueItem(i), Boolean.FALSE);
}
}
private static int timesDatabaseQueried = 1;
private static boolean isEmpty = false;
public static boolean isEmpty(){
return isEmpty;
}
public static synchronized List<QueueItem> queryItems( int fetchSize){
if(isEmpty) {
//System.out.println("Returning null...");
return null; }
// System.out.println("timesDatabaseQueried = " + timesDatabaseQueried);
List<QueueItem> returnItems = new ArrayList<QueueItem>(fetchSize);
int fetchCount = 0;
for (QueueItem queueItem : database.keySet()) {
if(!database.get(queueItem)) { //pickedFlag is false
returnItems.add(queueItem); //add to return list
database.put(queueItem, Boolean.TRUE); //update in database
fetchCount++;
if(fetchCount == FETCH_SIZE) break;
}
}
if(fetchCount == 0){
isEmpty = true;
System.err.println("Database is Empty now!!!! ::: in " + timesDatabaseQueried);
new RuntimeException("Database is Empty now!!!!" + timesDatabaseQueried);
}
timesDatabaseQueried++;
return returnItems;
}
}
| 1,775 | 0.60507 | 0.602817 | 74 | 22.986486 | 29.403757 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405405 | false | false | 0 |
cfd11ceab50939187b405d267601e883ef174660 | 19,567,871,062,644 | 6d8ffb3f0579811a2ce96e392505af70db5d66ab | /app/src/main/java/com/akabetech/belaundryondemand/component/AdapterComponent.java | 13edded415bb5049ed8f665744c443401378b642 | []
| no_license | kevinmel2000/belaundry | https://github.com/kevinmel2000/belaundry | 7f6a22fb0f485f0d81d46054ccf04427be5b8fff | 8be72e3904f6e3a6891240e9c939fa0b4031b30f | refs/heads/master | 2020-03-23T23:54:32.617000 | 2017-08-07T22:09:05 | 2017-08-07T22:09:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.akabetech.belaundryondemand.component;
/**
* Created by akbar.pambudi on 8/14/2016.
*/
public class AdapterComponent {
public static<E> E getAdapter(Class<E> clazz){
return RetrofitComponent.getInstance().getRetrofit().create(clazz);
}
public static<E> E getGoogleServiceAdapter(Class<E> clazz) {
return RetrofitComponent.getInstance().getGoogleServiceRetrofit().create(clazz);
}
public static<E> E getGoogleApiAdapter(Class<E> clazz){
return RetrofitComponent.getInstance().getGoogleApiRetrofit().create(clazz);
}
}
| UTF-8 | Java | 584 | java | AdapterComponent.java | Java | [
{
"context": "ch.belaundryondemand.component;\n\n/**\n * Created by akbar.pambudi on 8/14/2016.\n */\npublic class AdapterComponent {",
"end": 83,
"score": 0.9058651328086853,
"start": 70,
"tag": "USERNAME",
"value": "akbar.pambudi"
}
]
| null | []
| package com.akabetech.belaundryondemand.component;
/**
* Created by akbar.pambudi on 8/14/2016.
*/
public class AdapterComponent {
public static<E> E getAdapter(Class<E> clazz){
return RetrofitComponent.getInstance().getRetrofit().create(clazz);
}
public static<E> E getGoogleServiceAdapter(Class<E> clazz) {
return RetrofitComponent.getInstance().getGoogleServiceRetrofit().create(clazz);
}
public static<E> E getGoogleApiAdapter(Class<E> clazz){
return RetrofitComponent.getInstance().getGoogleApiRetrofit().create(clazz);
}
}
| 584 | 0.717466 | 0.705479 | 21 | 26.809525 | 31.240417 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.190476 | false | false | 0 |
45b62292697e55350c3eb4447fac7f51ab860c90 | 19,026,705,155,449 | aca68b4d6193ae132b3d9d0836fc7be62b1ce215 | /springboot_mybatis/src/main/java/top/mengtech/springboot_mybatis/jwt/JwtRequest.java | 833ee961965a1cffc44f71740ed426305d4ef21e | []
| no_license | mengqingmeng/mybatisStudy | https://github.com/mengqingmeng/mybatisStudy | 4c844e60ccf5556cd313047614a2f305a4ab7502 | 49f00977b5e64e22233445a016fb4f0dc0778196 | refs/heads/master | 2022-11-24T10:17:20.484000 | 2020-03-01T14:10:52 | 2020-03-01T14:10:52 | 233,321,544 | 0 | 0 | null | false | 2022-11-16T00:41:59 | 2020-01-12T01:23:43 | 2020-03-01T14:11:04 | 2022-11-16T00:41:56 | 27,497 | 0 | 0 | 6 | Java | false | false | package top.mengtech.springboot_mybatis.jwt;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @ClassName JwtRequest
* @Description
* @Author MQM
* @Date 2020-02-16 18:30
*/
@Getter
@Setter
public class JwtRequest implements Serializable {
private static final long serialVersionUID = -3884131668473413269L;
private String userName;
private String password;
}
| UTF-8 | Java | 410 | java | JwtRequest.java | Java | [
{
"context": "* @ClassName JwtRequest\n * @Description\n * @Author MQM\n * @Date 2020-02-16 18:30\n */\n\n@Getter\n@Setter\npu",
"end": 180,
"score": 0.9996774196624756,
"start": 177,
"tag": "USERNAME",
"value": "MQM"
}
]
| null | []
| package top.mengtech.springboot_mybatis.jwt;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @ClassName JwtRequest
* @Description
* @Author MQM
* @Date 2020-02-16 18:30
*/
@Getter
@Setter
public class JwtRequest implements Serializable {
private static final long serialVersionUID = -3884131668473413269L;
private String userName;
private String password;
}
| 410 | 0.75122 | 0.67561 | 21 | 18.523809 | 18.445852 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
3d7ecf65526003dbf13163111ab0b1648ed5bcee | 33,191,507,269,366 | 997e9a0f7b44a5cf029e3a8cce431e5a0bb6352a | /Ranjana-Java/Map/src/com/ustglobal/maps/TestA.java | ff299da18965b856ffd494a985d8741459def670 | []
| no_license | Ranjanahs/USTGlobal-16Sep19-Ranjana.H.S | https://github.com/Ranjanahs/USTGlobal-16Sep19-Ranjana.H.S | 0d29909550760b2d8fbe8027b17c60c52ac9b952 | 65653f06dd10dcc20e44d8045bbf174199da3342 | refs/heads/master | 2023-01-08T08:42:28.026000 | 2019-12-21T14:07:41 | 2019-12-21T14:07:41 | 215,538,776 | 0 | 0 | null | false | 2023-01-07T13:04:34 | 2019-10-16T12:07:36 | 2019-12-21T14:07:58 | 2023-01-07T13:04:33 | 74,065 | 0 | 0 | 83 | CSS | false | false | package com.ustglobal.maps;
import java.util.HashMap;
public class TestA {
public static void main(String[] args) {
HashMap hm= new HashMap();
hm.put("kullu", 89287);
hm.put("tms", 785644);
hm.put("mts", 745612);
hm.put(null,98989);
hm.put(null, 785210);
System.out.println("data"+hm);
hm.put("tms",7878789);
System.out.println("aftr modify"+hm);//fr keys-duplicates nt allowed
hm.put("kulli",89287);
System.out.println("aftr modify"+hm);//fr value-duplictes are allowed
System.out.println("aftr null"+hm);//fr value-any num null allowd
System.out.println("----------------");
System.out.println("aftr addng duplicate null");
System.out.println(hm);
System.out.println("---------------------");
Object name=hm.get("kullu");
System.out.println("value "+name);
System.out.println("----------------------");
Object value=hm.remove("kullu");
System.out.println("value="+value);
System.out.println("aftr remove="+hm);//does nt presrve insertions ordr
}
}
| UTF-8 | Java | 975 | java | TestA.java | Java | []
| null | []
| package com.ustglobal.maps;
import java.util.HashMap;
public class TestA {
public static void main(String[] args) {
HashMap hm= new HashMap();
hm.put("kullu", 89287);
hm.put("tms", 785644);
hm.put("mts", 745612);
hm.put(null,98989);
hm.put(null, 785210);
System.out.println("data"+hm);
hm.put("tms",7878789);
System.out.println("aftr modify"+hm);//fr keys-duplicates nt allowed
hm.put("kulli",89287);
System.out.println("aftr modify"+hm);//fr value-duplictes are allowed
System.out.println("aftr null"+hm);//fr value-any num null allowd
System.out.println("----------------");
System.out.println("aftr addng duplicate null");
System.out.println(hm);
System.out.println("---------------------");
Object name=hm.get("kullu");
System.out.println("value "+name);
System.out.println("----------------------");
Object value=hm.remove("kullu");
System.out.println("value="+value);
System.out.println("aftr remove="+hm);//does nt presrve insertions ordr
}
}
| 975 | 0.659487 | 0.618462 | 30 | 31.5 | 19.412624 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.766667 | false | false | 0 |
e24da61a30710a4135b2937309c92558f3f823cd | 3,685,081,940,906 | 8bb9566a5a1148481bcdcf90af20b069d1e50b6b | /src/Model/MovieFactory.java | 221b90173b5ea847c61634d3f796e57ed2de13fe | []
| no_license | hihiboss/DesignPattern | https://github.com/hihiboss/DesignPattern | da6e4017f170604d2530c587aacaa8072547044b | df9ae44bc1a3ffbf9b47a17dbacee514a4f36c0b | refs/heads/master | 2020-04-09T18:26:50.817000 | 2018-12-07T12:57:05 | 2018-12-07T12:57:05 | 160,512,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Model;
public class MovieFactory {
private volatile static MovieFactory instance = null;
private MovieFactory(){}
public static MovieFactory getInstance(){
if (instance == null) {
synchronized (Movie.class) {
if (instance == null) {
instance = new MovieFactory();
}
}
}
return instance;
}
public Movie getMovie(MovieAbstractFactory movie) {
return movie.createMovie();
}
}
| UTF-8 | Java | 517 | java | MovieFactory.java | Java | []
| null | []
| package Model;
public class MovieFactory {
private volatile static MovieFactory instance = null;
private MovieFactory(){}
public static MovieFactory getInstance(){
if (instance == null) {
synchronized (Movie.class) {
if (instance == null) {
instance = new MovieFactory();
}
}
}
return instance;
}
public Movie getMovie(MovieAbstractFactory movie) {
return movie.createMovie();
}
}
| 517 | 0.555126 | 0.555126 | 22 | 22.5 | 18.881809 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.227273 | false | false | 0 |
3690c67fdeb68b3a3d029ee555e51fbb7e036290 | 1,005,022,352,272 | f2d89b4010350e036b886bfe46001f22376e6920 | /easy-smart-house-scripting/src/main/java/net/easysmarthouse/scripting/util/DeviceScriptUtil.java | 24b657416a814369f3097b4d250ed3ae495f5b3b | []
| no_license | EasySmartHouse/esh-embedded-backend | https://github.com/EasySmartHouse/esh-embedded-backend | 9a777bdc3917f639056d392571c123ba56cba861 | d8ba0ac940da59cd997717f1fc4c7a04e716ce69 | refs/heads/master | 2021-09-17T15:46:40.303000 | 2018-07-03T12:13:41 | 2018-07-03T12:13:41 | 122,620,972 | 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 net.easysmarthouse.scripting.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author rusakovich
*/
public class DeviceScriptUtil {
private static final String ADDRESS_PATTERN = "address:\\s*'(.*)'";
private DeviceScriptUtil() {
}
public static String getDeviceAddress(String scriptContent) {
Pattern pattern = Pattern.compile(ADDRESS_PATTERN);
Matcher matcher = pattern.matcher(scriptContent);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
| UTF-8 | Java | 764 | java | DeviceScriptUtil.java | Java | [
{
"context": "import java.util.regex.Pattern;\n\n/**\n *\n * @author rusakovich\n */\npublic class DeviceScriptUtil {\n\n private ",
"end": 322,
"score": 0.991085410118103,
"start": 312,
"tag": "USERNAME",
"value": "rusakovich"
}
]
| 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 net.easysmarthouse.scripting.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author rusakovich
*/
public class DeviceScriptUtil {
private static final String ADDRESS_PATTERN = "address:\\s*'(.*)'";
private DeviceScriptUtil() {
}
public static String getDeviceAddress(String scriptContent) {
Pattern pattern = Pattern.compile(ADDRESS_PATTERN);
Matcher matcher = pattern.matcher(scriptContent);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
| 764 | 0.675393 | 0.674084 | 31 | 23.645161 | 24.423082 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354839 | false | false | 0 |
5e7aaab00dc8b0e15d6982334e30094949639263 | 9,861,244,977,214 | 74093a6c0edc71b8b14676e2756ff87d132cf348 | /appfoundry-robo-tests/src/test/java/be/appfoundry/android/ui/MyActivityTest.java | 2cf63ede85f1f6c91d613de68583bdccb871b7cf | []
| no_license | iluxa-c0m/android-project-template | https://github.com/iluxa-c0m/android-project-template | 01a3d2168aca88d2986efed1816d00ecfee70fbc | 44a232280b40e026035c41a380fd45eec3bc31f9 | refs/heads/master | 2020-06-15T13:06:10.530000 | 2016-12-01T16:55:42 | 2016-12-01T16:55:42 | 75,290,723 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.appfoundry.android.ui;
import android.annotation.TargetApi;
import android.os.Build;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
import be.appfoundry.android.RobolectricGradleTestRunner;
import be.appfoundry.android.androidarchitecture.ui.MyActivity;
import be.appfoundry.android.androidarchitecture.R;
import static org.fest.assertions.api.Assertions.assertThat;
//import static org.assertj.android.api.Assertions.assertThat;
/**
* @author Filip Maelbrancke
*/
@Config(emulateSdk = 18)
@RunWith(RobolectricGradleTestRunner.class)
public class MyActivityTest {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Test
public void shouldHaveLoadedFragmentWhenActivityCreated() throws Exception {
MyActivity activity = new MyActivity();
ActivityController.of(activity).attach().create();
MyActivity.PlaceholderFragment fragment = (MyActivity.PlaceholderFragment) activity.getFragmentManager().findFragmentById(R.id.container);
assertThat(fragment).isNotNull();
}
}
| UTF-8 | Java | 1,126 | java | MyActivityTest.java | Java | [
{
"context": "ndroid.api.Assertions.assertThat;\n\n\n/**\n * @author Filip Maelbrancke\n */\n@Config(emulateSdk = 18)\n@RunWith(Robolectric",
"end": 578,
"score": 0.9998871088027954,
"start": 561,
"tag": "NAME",
"value": "Filip Maelbrancke"
}
]
| null | []
| package be.appfoundry.android.ui;
import android.annotation.TargetApi;
import android.os.Build;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;
import be.appfoundry.android.RobolectricGradleTestRunner;
import be.appfoundry.android.androidarchitecture.ui.MyActivity;
import be.appfoundry.android.androidarchitecture.R;
import static org.fest.assertions.api.Assertions.assertThat;
//import static org.assertj.android.api.Assertions.assertThat;
/**
* @author <NAME>
*/
@Config(emulateSdk = 18)
@RunWith(RobolectricGradleTestRunner.class)
public class MyActivityTest {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Test
public void shouldHaveLoadedFragmentWhenActivityCreated() throws Exception {
MyActivity activity = new MyActivity();
ActivityController.of(activity).attach().create();
MyActivity.PlaceholderFragment fragment = (MyActivity.PlaceholderFragment) activity.getFragmentManager().findFragmentById(R.id.container);
assertThat(fragment).isNotNull();
}
}
| 1,115 | 0.78952 | 0.787744 | 36 | 30.277779 | 30.636408 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 0 |
b97d87d70be707d8dd385379dada56491fcbc62e | 6,502,580,500,796 | 47b949ec2c540eb5c19b8a0934160951b86cef0a | /src/test/VNode.java | c63d10eb43f16257d6b7a43fbe1810f051b621fe | []
| no_license | imnotnerd/MyUI | https://github.com/imnotnerd/MyUI | a2e6ece51a8e69f6487bacc4e2fc39d65b824e76 | 9254000b5c52a1517aaeb20446854a653243631f | refs/heads/master | 2016-03-05T08:08:17.920000 | 2015-05-11T01:36:33 | 2015-05-11T01:36:33 | 35,395,831 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
/*
* 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.
*/
/**
*
* @author Administrator
*/
public class VNode {
String name;
int outdegree;
int deep;
int servicenum;
Service[] service = new Service[10];
public void init(){
int i;
for(i=0;i<10;i++)
service[i]=new Service();
}
}
| UTF-8 | Java | 491 | java | VNode.java | Java | [
{
"context": "the template in the editor.\n */\n\n/**\n *\n * @author Administrator\n */\npublic class VNode {\n String name;\n int",
"end": 231,
"score": 0.6842235326766968,
"start": 218,
"tag": "USERNAME",
"value": "Administrator"
}
]
| null | []
| package test;
/*
* 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.
*/
/**
*
* @author Administrator
*/
public class VNode {
String name;
int outdegree;
int deep;
int servicenum;
Service[] service = new Service[10];
public void init(){
int i;
for(i=0;i<10;i++)
service[i]=new Service();
}
}
| 491 | 0.602851 | 0.592668 | 25 | 18.639999 | 19.002905 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 0 |
1e6df7325fd1b11fcc71e850fa971bb41447eab1 | 28,638,841,996,854 | c1e1c6cddbb378f95592f0957e2863dae51a7be4 | /app/src/main/java/com/example/cs2063project/UserInfo.java | 2713089b4e0eaee057b84eabe2856ea1c384bc14 | []
| no_license | jmajcan/noveltrail | https://github.com/jmajcan/noveltrail | ca99a0a88401e0c88d3758b1b66148d97866b026 | e312887620388e49822f1f4fd61b07b94f3d4501 | refs/heads/master | 2020-04-22T12:41:53.038000 | 2019-04-09T11:25:49 | 2019-04-09T11:25:49 | 170,381,338 | 0 | 1 | null | false | 2019-04-09T11:25:50 | 2019-02-12T19:52:26 | 2019-04-02T03:31:13 | 2019-04-09T11:25:49 | 367 | 0 | 0 | 4 | Java | false | false | package com.example.cs2063project;
import java.io.Serializable;
public class UserInfo implements Serializable {
String email;
String password;
String user_fname;
String user_lname;
UserInfo(String email, String password, String user_fname, String user_lname){
this.email = email;
this.password = password;
this.user_fname = user_fname;
this.user_lname = user_lname;
}
}
| UTF-8 | Java | 429 | java | UserInfo.java | Java | [
{
"context": " this.email = email;\n this.password = password;\n this.user_fname = user_fname;\n th",
"end": 343,
"score": 0.9987040758132935,
"start": 335,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.example.cs2063project;
import java.io.Serializable;
public class UserInfo implements Serializable {
String email;
String password;
String user_fname;
String user_lname;
UserInfo(String email, String password, String user_fname, String user_lname){
this.email = email;
this.password = <PASSWORD>;
this.user_fname = user_fname;
this.user_lname = user_lname;
}
}
| 431 | 0.678322 | 0.668998 | 17 | 24.235294 | 20.475321 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 0 |
b0a00b11979be5ba292db7faa62d7f4c99c7918d | 2,156,073,619,433 | 139989dde78e72f7f6d6e59b4647beaa6068a4ea | /src/uTorrentSorter/ConfigManager.java | 170a7151276be2eedc7dc4e94e18138e34f09898 | []
| no_license | IGitSylvia/utorrent-sorter | https://github.com/IGitSylvia/utorrent-sorter | eec7d4834f3d67dbb8e9e370843faf529deafb10 | 224c214d16bac586e075d85e88abc00d2d0c4c4c | refs/heads/master | 2021-01-10T17:52:56.606000 | 2012-05-11T03:44:43 | 2012-05-11T03:44:43 | 55,619,237 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uTorrentSorter;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/******************************************************************************
*Written By: Taylor M. Hicks *
*Purpose: Config Manager Panel *
*Date:5/9/2012 *
*******************************************************************************/
public class ConfigManager extends JPanel {
static JLabel rootLabel = new JLabel("Root Directory:");
static JLabel tvLabel = new JLabel("TV Directory:");
static JLabel moviesLabel = new JLabel("Movie Directory:");
static JLabel gamesLabel = new JLabel("Game Directory:");
static JLabel musicLabel = new JLabel("Music Directory:");
static JLabel documentLabel = new JLabel("Document Directory:");
static JLabel videoLabel = new JLabel("Video Directory:");
static JLabel unlabeledLabel = new JLabel("Unlabeld Directory");
static JButton saveButton = new JButton("Save");
static JButton cancelButton = new JButton("Cancel");
Config config;
JTextField rootTextField;
JTextField tvTextField;
JTextField moviesTextField;
JTextField gamesTextField;
JTextField musicTextField;
JTextField documentTextField;
JTextField videoTextField;
JTextField unlabeledTextField;
public ConfigManager()
{
config = new Config();
config.setConfigFile(new File("conf.txt"));
initializeJTextFields(config);
constructPanel();
}
public ConfigManager(Config c)
{
initializeJTextFields(c);
constructPanel();
}
private void initializeJTextFields(Config c)
{
config = c;
rootTextField = new JTextField(config.getRootDirectory());
tvTextField = new JTextField(config.getTvDirectory());
moviesTextField = new JTextField(config.getMoviesDirectory());
gamesTextField = new JTextField(config.getGamesDirectory());
musicTextField = new JTextField(config.getMusicDirectory());
documentTextField = new JTextField(config.getDocumentDirectory());
videoTextField = new JTextField(config.getVideoDirectory());
unlabeledTextField = new JTextField(config.getUnlabeledDirectory());
}
private void constructPanel()
{
setLayout(new GridLayout(9,2));
Listener listener = new Listener();
rootTextField.addActionListener(listener);
tvTextField.addActionListener(listener);
moviesTextField.addActionListener(listener);
gamesTextField.addActionListener(listener);
musicTextField.addActionListener(listener);
documentTextField.addActionListener(listener);
videoTextField.addActionListener(listener);
unlabeledTextField.addActionListener(listener);
saveButton.addActionListener(listener);
cancelButton.addActionListener(listener);
add(rootLabel); add(rootTextField);
add(tvLabel); add(tvTextField);
add(moviesLabel); add(moviesTextField);
add(gamesLabel); add(gamesTextField);
add(musicLabel); add(musicTextField);
add(documentLabel); add(documentTextField);
add(videoLabel); add(videoTextField);
add(unlabeledLabel); add(unlabeledTextField);
add(saveButton); add(cancelButton);
}
private class Listener implements ActionListener
{
@Override public void actionPerformed(ActionEvent event)
{
if (event.getSource().equals(cancelButton)) System.exit(0);
config.setTvDirectory(tvTextField.getText());
config.setDocumentDirectory(documentTextField.getText());
config.setUnlabeledDirectory(unlabeledTextField.getText());
config.setGamesDirectory(gamesTextField.getText());
config.setMoviesDirectory(moviesTextField.getText());
config.setMusicDirectory(musicTextField.getText());
config.setVideoDirectory(videoTextField.getText());
config.setRootDirectory(rootTextField.getText());
if (event.getSource().equals(saveButton))
{
try
{
config.writeToFile();
System.exit(0);
}
catch(Exception exception)
{
if(exception instanceof IOException) JOptionPane.showMessageDialog(saveButton.getTopLevelAncestor(),String.format("Error writing to file check your input and try agin.%n%s",exception.getMessage()),"Error", JOptionPane.ERROR_MESSAGE);
else
{
JOptionPane.showMessageDialog(saveButton.getTopLevelAncestor(),String.format("Error: %S%nForced To Close.",exception.getMessage(),"Error",JOptionPane.ERROR_MESSAGE));
}
}
}
}
}
}
| UTF-8 | Java | 5,335 | java | ConfigManager.java | Java | [
{
"context": "************************************\n *Written By: Taylor M. Hicks *",
"end": 432,
"score": 0.9998814463615417,
"start": 417,
"tag": "NAME",
"value": "Taylor M. Hicks"
}
]
| null | []
| package uTorrentSorter;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/******************************************************************************
*Written By: <NAME> *
*Purpose: Config Manager Panel *
*Date:5/9/2012 *
*******************************************************************************/
public class ConfigManager extends JPanel {
static JLabel rootLabel = new JLabel("Root Directory:");
static JLabel tvLabel = new JLabel("TV Directory:");
static JLabel moviesLabel = new JLabel("Movie Directory:");
static JLabel gamesLabel = new JLabel("Game Directory:");
static JLabel musicLabel = new JLabel("Music Directory:");
static JLabel documentLabel = new JLabel("Document Directory:");
static JLabel videoLabel = new JLabel("Video Directory:");
static JLabel unlabeledLabel = new JLabel("Unlabeld Directory");
static JButton saveButton = new JButton("Save");
static JButton cancelButton = new JButton("Cancel");
Config config;
JTextField rootTextField;
JTextField tvTextField;
JTextField moviesTextField;
JTextField gamesTextField;
JTextField musicTextField;
JTextField documentTextField;
JTextField videoTextField;
JTextField unlabeledTextField;
public ConfigManager()
{
config = new Config();
config.setConfigFile(new File("conf.txt"));
initializeJTextFields(config);
constructPanel();
}
public ConfigManager(Config c)
{
initializeJTextFields(c);
constructPanel();
}
private void initializeJTextFields(Config c)
{
config = c;
rootTextField = new JTextField(config.getRootDirectory());
tvTextField = new JTextField(config.getTvDirectory());
moviesTextField = new JTextField(config.getMoviesDirectory());
gamesTextField = new JTextField(config.getGamesDirectory());
musicTextField = new JTextField(config.getMusicDirectory());
documentTextField = new JTextField(config.getDocumentDirectory());
videoTextField = new JTextField(config.getVideoDirectory());
unlabeledTextField = new JTextField(config.getUnlabeledDirectory());
}
private void constructPanel()
{
setLayout(new GridLayout(9,2));
Listener listener = new Listener();
rootTextField.addActionListener(listener);
tvTextField.addActionListener(listener);
moviesTextField.addActionListener(listener);
gamesTextField.addActionListener(listener);
musicTextField.addActionListener(listener);
documentTextField.addActionListener(listener);
videoTextField.addActionListener(listener);
unlabeledTextField.addActionListener(listener);
saveButton.addActionListener(listener);
cancelButton.addActionListener(listener);
add(rootLabel); add(rootTextField);
add(tvLabel); add(tvTextField);
add(moviesLabel); add(moviesTextField);
add(gamesLabel); add(gamesTextField);
add(musicLabel); add(musicTextField);
add(documentLabel); add(documentTextField);
add(videoLabel); add(videoTextField);
add(unlabeledLabel); add(unlabeledTextField);
add(saveButton); add(cancelButton);
}
private class Listener implements ActionListener
{
@Override public void actionPerformed(ActionEvent event)
{
if (event.getSource().equals(cancelButton)) System.exit(0);
config.setTvDirectory(tvTextField.getText());
config.setDocumentDirectory(documentTextField.getText());
config.setUnlabeledDirectory(unlabeledTextField.getText());
config.setGamesDirectory(gamesTextField.getText());
config.setMoviesDirectory(moviesTextField.getText());
config.setMusicDirectory(musicTextField.getText());
config.setVideoDirectory(videoTextField.getText());
config.setRootDirectory(rootTextField.getText());
if (event.getSource().equals(saveButton))
{
try
{
config.writeToFile();
System.exit(0);
}
catch(Exception exception)
{
if(exception instanceof IOException) JOptionPane.showMessageDialog(saveButton.getTopLevelAncestor(),String.format("Error writing to file check your input and try agin.%n%s",exception.getMessage()),"Error", JOptionPane.ERROR_MESSAGE);
else
{
JOptionPane.showMessageDialog(saveButton.getTopLevelAncestor(),String.format("Error: %S%nForced To Close.",exception.getMessage(),"Error",JOptionPane.ERROR_MESSAGE));
}
}
}
}
}
}
| 5,326 | 0.616307 | 0.614433 | 131 | 39.725189 | 32.468906 | 253 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.740458 | false | false | 0 |
5d5ddd6731ecbcf3df8cf9516eabfca1e66aac5b | 1,546,188,289,452 | 1d120b1c204b826fa61e608f5c5924f9b8e52240 | /src/main/java/com/ipvision/analyzer/hbase/LogBean.java | 34b010347fddd7ce6bbe530a441bbfe92f0b63cf | []
| no_license | rakib07cse/HBaseLogAnalyzer | https://github.com/rakib07cse/HBaseLogAnalyzer | a72d5b462d240eb50646ac009851c21e91f87ba0 | 7db5bb57849740b8a8a08aee965901c94b2e0247 | refs/heads/master | 2021-07-23T01:33:38.904000 | 2017-11-01T11:08:46 | 2017-11-01T11:08:46 | 106,411,994 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ipvision.analyzer.hbase;
import java.io.Serializable;
/**
*
* @author rakib
*/
public class LogBean implements Serializable {
private String timestamp;
private String logLevel;
private String eventType;
private String requestId;
private String liveStreamHistroy;
private String liveStreamParams;
private String methodName;
private String params;
public LogBean() {
}
public LogBean(String timestamp, String logLevel, String eventType, String requestId, String liveStreamHistory, String liveStreamParams, String methodName, String params) {
this.timestamp = timestamp;
this.logLevel = logLevel;
this.eventType = eventType;
this.requestId = requestId;
this.liveStreamHistroy = liveStreamHistory;
this.liveStreamParams = liveStreamParams;
this.methodName = methodName;
this.params = params;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getTimestamp() {
return timestamp;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public String getLogLevel() {
return logLevel;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getEventType() {
return eventType;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getRequestId() {
return requestId;
}
public void setLiveStreamHistory(String liveStreamHistory) {
this.liveStreamHistroy = liveStreamHistory;
}
public String getLiveStreamHistory() {
return liveStreamHistroy;
}
public void setLiveStreamParams(String liveStreamParams) {
this.liveStreamParams = liveStreamParams;
}
public String getLiveStreamParams() {
return liveStreamParams;
}
public void setMethodName(String methodName) {
if (methodName != null && !methodName.isEmpty()) {
this.methodName = methodName;
}
// else {
// this.methodName = "noMethod";
// }
}
public String getMethodName() {
return methodName;
}
public void setParams(String params) {
if (params != null && !params.isEmpty()) {
// this.params = "{" + params + "}";
this.params = params;
}
// } else {
// this.params = "{" + "" + "}";
// }
}
public String getParams() {
return params;
}
}
| UTF-8 | Java | 2,797 | java | LogBean.java | Java | [
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n *\n * @author rakib\n */\npublic class LogBean implements Serializable ",
"end": 276,
"score": 0.9990055561065674,
"start": 271,
"tag": "USERNAME",
"value": "rakib"
}
]
| null | []
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ipvision.analyzer.hbase;
import java.io.Serializable;
/**
*
* @author rakib
*/
public class LogBean implements Serializable {
private String timestamp;
private String logLevel;
private String eventType;
private String requestId;
private String liveStreamHistroy;
private String liveStreamParams;
private String methodName;
private String params;
public LogBean() {
}
public LogBean(String timestamp, String logLevel, String eventType, String requestId, String liveStreamHistory, String liveStreamParams, String methodName, String params) {
this.timestamp = timestamp;
this.logLevel = logLevel;
this.eventType = eventType;
this.requestId = requestId;
this.liveStreamHistroy = liveStreamHistory;
this.liveStreamParams = liveStreamParams;
this.methodName = methodName;
this.params = params;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getTimestamp() {
return timestamp;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public String getLogLevel() {
return logLevel;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getEventType() {
return eventType;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getRequestId() {
return requestId;
}
public void setLiveStreamHistory(String liveStreamHistory) {
this.liveStreamHistroy = liveStreamHistory;
}
public String getLiveStreamHistory() {
return liveStreamHistroy;
}
public void setLiveStreamParams(String liveStreamParams) {
this.liveStreamParams = liveStreamParams;
}
public String getLiveStreamParams() {
return liveStreamParams;
}
public void setMethodName(String methodName) {
if (methodName != null && !methodName.isEmpty()) {
this.methodName = methodName;
}
// else {
// this.methodName = "noMethod";
// }
}
public String getMethodName() {
return methodName;
}
public void setParams(String params) {
if (params != null && !params.isEmpty()) {
// this.params = "{" + params + "}";
this.params = params;
}
// } else {
// this.params = "{" + "" + "}";
// }
}
public String getParams() {
return params;
}
}
| 2,797 | 0.628888 | 0.628888 | 116 | 23.112068 | 24.08597 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405172 | false | false | 0 |
257d0d585405ac0ac70ae701e6f0141d24cb8e16 | 32,323,923,926,876 | e826528e0b81debf7af0842bc1200ae6540fe7e2 | /src/main/java/com/example/meetingroom/entity/Meeting.java | 8307001abde3a1d2b082d0074274869b23807a58 | []
| no_license | stripathy210/meetingRoom | https://github.com/stripathy210/meetingRoom | 69b6232ecfd0df4b4d0e2b37684f4bab02070276 | e92fc44b34f5e69a8553a4e2069037cc015cb693 | refs/heads/master | 2022-11-30T00:47:36.315000 | 2020-08-10T08:47:44 | 2020-08-10T08:47:44 | 286,422,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.meetingroom.entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Meeting {
private Long meetingId;
private Room room;
private int noOfParticipants;
private RoomTime time;
public Meeting(Long meetingId, Room room, int noOfParticipants, RoomTime time) {
this.meetingId = meetingId;
this.room = room;
this.noOfParticipants = noOfParticipants;
this.time = time;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Meeting{");
sb.append("meetingId=").append(meetingId);
sb.append(", room=").append(room);
sb.append(", noOfParticipants=").append(noOfParticipants);
sb.append(", time=").append(time);
sb.append('}');
return sb.toString();
}
}
| UTF-8 | Java | 844 | java | Meeting.java | Java | []
| null | []
| package com.example.meetingroom.entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Meeting {
private Long meetingId;
private Room room;
private int noOfParticipants;
private RoomTime time;
public Meeting(Long meetingId, Room room, int noOfParticipants, RoomTime time) {
this.meetingId = meetingId;
this.room = room;
this.noOfParticipants = noOfParticipants;
this.time = time;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Meeting{");
sb.append("meetingId=").append(meetingId);
sb.append(", room=").append(room);
sb.append(", noOfParticipants=").append(noOfParticipants);
sb.append(", time=").append(time);
sb.append('}');
return sb.toString();
}
}
| 844 | 0.64455 | 0.64455 | 32 | 25.375 | 21.015991 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
88cffe82b23f812f984f45a064503de1eb7cc709 | 1,288,490,257,637 | 54007248794774853b2a96790cb05875480b7b6a | /src/main/java/org/tcf/sql/util/FunUtil.java | 14397b1e0831db3703cd7c5cc9b3aa2fb04b01b0 | []
| no_license | yunwei1237/dao | https://github.com/yunwei1237/dao | f7abf6e7881245ea204c560125340ef2ed9e6698 | a3f3121172330a9dd4293a96369ada664f6efe57 | refs/heads/master | 2021-09-03T05:53:28.868000 | 2018-01-06T02:51:24 | 2018-01-06T02:51:24 | 115,481,849 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.tcf.sql.util;
import org.tcf.sql.entity.fun.Function;
public class FunUtil {
/**
* 获得avg函数
* @param columnName
* @return
*/
public static Function avg(){
return new Function("avg");
}
public static Function max(){
return new Function("max");
}
public static Function min(){
return new Function("min");
}
public static Function count(){
return new Function("count");
}
public static Function sum(){
return new Function("sum");
}
}
| UTF-8 | Java | 507 | java | FunUtil.java | Java | []
| null | []
| package org.tcf.sql.util;
import org.tcf.sql.entity.fun.Function;
public class FunUtil {
/**
* 获得avg函数
* @param columnName
* @return
*/
public static Function avg(){
return new Function("avg");
}
public static Function max(){
return new Function("max");
}
public static Function min(){
return new Function("min");
}
public static Function count(){
return new Function("count");
}
public static Function sum(){
return new Function("sum");
}
}
| 507 | 0.635271 | 0.635271 | 26 | 17.192308 | 13.344602 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false | 0 |
29f12fc59b844da2c932e318b8ac682a40a13607 | 2,138,893,765,902 | 212621f6cef7da2f569bdb9a9f08aa6476113d3b | /emr-dynamodb-hadoop/src/test/java/org/apache/hadoop/dynamodb/read/DynamoDBRecordReaderTest.java | a5c306fd96cb1802053beeb5963757e964cf1a71 | [
"Apache-2.0"
]
| permissive | awslabs/emr-dynamodb-connector | https://github.com/awslabs/emr-dynamodb-connector | 73d46ec03cbd0aa7f037eab72d3118a276ed55e7 | 40f605acc03926cca4b086db3873d488e316a547 | refs/heads/master | 2023-08-22T11:36:25.581000 | 2023-04-17T21:54:18 | 2023-04-17T21:54:18 | 65,947,212 | 234 | 150 | Apache-2.0 | false | 2023-06-14T22:31:09 | 2016-08-17T22:43:06 | 2023-06-09T07:36:27 | 2023-06-14T22:31:09 | 541 | 206 | 134 | 60 | Java | false | false | /**
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
* except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "LICENSE.TXT" file accompanying this file. This file is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under the License.
*/
package org.apache.hadoop.dynamodb.read;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.apache.hadoop.dynamodb.DynamoDBClient;
import org.apache.hadoop.dynamodb.DynamoDBConstants;
import org.apache.hadoop.dynamodb.DynamoDBFibonacciRetryer.RetryResult;
import org.apache.hadoop.dynamodb.DynamoDBItemWritable;
import org.apache.hadoop.dynamodb.filter.DynamoDBQueryFilter;
import org.apache.hadoop.dynamodb.preader.DynamoDBRecordReaderContext;
import org.apache.hadoop.dynamodb.split.DynamoDBSegmentsSplit;
import org.apache.hadoop.dynamodb.split.DynamoDBSplit;
import org.apache.hadoop.mapred.Counters.Counter;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
public class DynamoDBRecordReaderTest {
private static final String HASH_KEY = "hashKey";
private static final String RANGE_KEY = "rangeKey";
private static final int NUM_RANGE_KEYS_PER_HASH_KEY = 3;
private static final String[] HASH_KEYS = {"6d9KhslLlNWKoPUpOrYX",
"gi0aeHusUZPjgpNJtXNDLzkipmeft", "9w3ZDZyiFheGE", "cfk9gcCgFA6M5g"};
@Test
public void testPaginatedReads() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
int i = 0;
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
List<Map<String, AttributeValue>> items = getItems();
if (i == 0) {
Map<String, AttributeValue> lastEvaluatedKey = new HashMap<>();
lastEvaluatedKey.put("test", AttributeValue.fromS("test"));
i++;
return new RetryResult<>(ScanResponse.builder()
.scannedCount(items.size())
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.items(items)
.lastEvaluatedKey(lastEvaluatedKey)
.build(), 0);
} else {
assertEquals("test", exclusiveStartKey.get("test").s());
return new RetryResult<>(ScanResponse.builder()
.scannedCount(items.size())
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.items(items)
.build(), 0);
}
}
private List<Map<String, AttributeValue>> getItems() {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : HASH_KEYS) {
Map<String, AttributeValue> item = new HashMap<>();
item.put("hashKey", AttributeValue.fromS(key));
items.add(item);
}
return items;
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (int i = 0; i < 8; i++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(HASH_KEYS[(i / 2) % 4], getHashKeyValue(value, "S"));
}
boolean ret = reader.next(reader.createKey(), null);
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testConsumingRemainingElementsIfEndKeyIsNull() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", "N");
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
return new RetryResult<>(getHashNumberRangeKeyItems(HASH_KEYS, "S"), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
for (int j = 0; j < NUM_RANGE_KEYS_PER_HASH_KEY; j++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
assertEquals(j, Integer.parseInt(getRangeKeyValue(value, "N")));
}
}
boolean ret = reader.next(reader.createKey(), reader.createValue());
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testConsumingAllBeginningElementsIfStartKeyIsNull() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", "N");
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
assertNull(exclusiveStartKey);
return new RetryResult<>(getHashNumberRangeKeyItems(HASH_KEYS, "S"), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
for (int j = 0; j < NUM_RANGE_KEYS_PER_HASH_KEY; j++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
assertEquals(j, Integer.parseInt(getRangeKeyValue(value, "N")));
}
}
boolean ret = reader.next(reader.createKey(), reader.createValue());
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testScanFirstSegment() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
assertEquals(0, (int) segment);
assertEquals(4, (int) totalSegments);
return new RetryResult<>(getHashKeyItems(HASH_KEYS), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
}
boolean ret = reader.next(reader.createKey(), null);
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test(expected = IOException.class, timeout = 10000)
public void testExceptionInDbClient() throws IOException {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
throw new RuntimeException("Unrecoverable Exception");
}
});
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
}
private DynamoDBRecordReaderContext buildContext() {
DynamoDBRecordReaderContext context = new DynamoDBRecordReaderContext();
context.setAttributes(null);
context.setConf(getTestConf());
context.setReporter(new Reporter() {
@Override
public void progress() {
}
@Override
public void setStatus(String arg0) {
}
@Override
public void incrCounter(String arg0, String arg1, long arg2) {
}
@Override
public void incrCounter(Enum<?> arg0, long arg1) {
}
@Override
public InputSplit getInputSplit() throws UnsupportedOperationException {
return null;
}
@Override
public Counter getCounter(String arg0, String arg1) {
return null;
}
@Override
public Counter getCounter(Enum<?> arg0) {
return null;
}
@Override
public float getProgress() {
return 0;
}
});
return context;
}
private String getHashKeyValue(DynamoDBItemWritable value, String type) {
return getKeyValue(value, HASH_KEY, type);
}
private String getRangeKeyValue(DynamoDBItemWritable value, String type) {
return getKeyValue(value, RANGE_KEY, type);
}
private String getKeyValue(DynamoDBItemWritable value, String keyName, String type) {
if (type.equals("S")) {
return value.getItem().get(keyName).s();
} else {
return value.getItem().get(keyName).n();
}
}
private ScanResponse getHashKeyItems(String[] hashKeys) {
return getHashKeyItems(hashKeys, "S");
}
private ScanResponse getHashKeyItems(String[] hashKeys, String type) {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : hashKeys) {
Map<String, AttributeValue> item = new HashMap<>();
if (type.equals("S")) {
item.put("hashKey", AttributeValue.fromS(key));
} else {
item.put("hashKey", AttributeValue.fromN(key));
}
items.add(item);
}
return ScanResponse.builder()
.scannedCount(items.size())
.items(items)
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.build();
}
private ScanResponse getHashNumberRangeKeyItems(String[] hashKeys, String hashType) {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : hashKeys) {
for (Integer i = 0; i < NUM_RANGE_KEYS_PER_HASH_KEY; i++) {
Map<String, AttributeValue> item = new HashMap<>();
if (hashType.equals("S")) {
item.put("hashKey", AttributeValue.fromS(key));
} else {
item.put("hashKey", AttributeValue.fromN(key));
}
item.put("rangeKey", AttributeValue.fromN("0" + i.toString()));
items.add(item);
}
}
return ScanResponse.builder()
.scannedCount(items.size())
.items(items)
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.build();
}
private TableDescription getTableDescription(String hashType, String rangeType) {
List<KeySchemaElement> keySchema = new ArrayList<>();
List<AttributeDefinition> definitions = new ArrayList<>();
keySchema.add(KeySchemaElement.builder()
.attributeName("hashKey")
.keyType(KeyType.HASH)
.build());
definitions.add(AttributeDefinition.builder()
.attributeName("hashKey")
.attributeType(hashType)
.build());
if (rangeType != null) {
keySchema.add(KeySchemaElement.builder()
.attributeName("rangeKey")
.keyType(KeyType.RANGE)
.build());
definitions.add(AttributeDefinition.builder()
.attributeName("rangeKey")
.attributeType(rangeType)
.build());
}
TableDescription description = TableDescription.builder()
.keySchema(keySchema)
.attributeDefinitions(definitions)
.provisionedThroughput(ProvisionedThroughputDescription.builder()
.readCapacityUnits(1000L)
.writeCapacityUnits(1000L)
.build())
.build();
return description;
}
private JobConf getTestConf() {
JobConf conf = new JobConf();
conf.set(DynamoDBConstants.DEFAULT_ACCESS_KEY_CONF, "abc");
conf.set(DynamoDBConstants.DEFAULT_SECRET_KEY_CONF, "abcd");
return conf;
}
}
| UTF-8 | Java | 15,005 | java | DynamoDBRecordReaderTest.java | Java | [
{
"context": " 3;\n private static final String[] HASH_KEYS = {\"6d9KhslLlNWKoPUpOrYX\",\n \"gi0aeHusUZPjgpNJtXNDLzkipmeft\", \"9w3ZDZy",
"end": 2409,
"score": 0.9789657592773438,
"start": 2389,
"tag": "KEY",
"value": "6d9KhslLlNWKoPUpOrYX"
},
{
"context": "ing[] HASH_KEYS = {\"6d9KhslLlNWKoPUpOrYX\",\n \"gi0aeHusUZPjgpNJtXNDLzkipmeft\", \"9w3ZDZyiFheGE\", \"cfk9gcCgFA6M5g\"};\n\n @Test\n ",
"end": 2448,
"score": 0.9988983273506165,
"start": 2419,
"tag": "KEY",
"value": "gi0aeHusUZPjgpNJtXNDLzkipmeft"
},
{
"context": "PUpOrYX\",\n \"gi0aeHusUZPjgpNJtXNDLzkipmeft\", \"9w3ZDZyiFheGE\", \"cfk9gcCgFA6M5g\"};\n\n @Test\n public void testP",
"end": 2465,
"score": 0.999028742313385,
"start": 2452,
"tag": "KEY",
"value": "9w3ZDZyiFheGE"
},
{
"context": "gi0aeHusUZPjgpNJtXNDLzkipmeft\", \"9w3ZDZyiFheGE\", \"cfk9gcCgFA6M5g\"};\n\n @Test\n public void testPaginatedReads() {\n",
"end": 2483,
"score": 0.9988323450088501,
"start": 2469,
"tag": "KEY",
"value": "cfk9gcCgFA6M5g"
},
{
"context": "f.set(DynamoDBConstants.DEFAULT_ACCESS_KEY_CONF, \"abc\");\n conf.set(DynamoDBConstants.DEFAULT_SECRET_",
"end": 14910,
"score": 0.8328260183334351,
"start": 14907,
"tag": "KEY",
"value": "abc"
},
{
"context": "f.set(DynamoDBConstants.DEFAULT_SECRET_KEY_CONF, \"abcd\");\n return conf;\n }\n}\n",
"end": 14975,
"score": 0.8623294830322266,
"start": 14971,
"tag": "KEY",
"value": "abcd"
}
]
| null | []
| /**
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
* except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "LICENSE.TXT" file accompanying this file. This file is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under the License.
*/
package org.apache.hadoop.dynamodb.read;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.apache.hadoop.dynamodb.DynamoDBClient;
import org.apache.hadoop.dynamodb.DynamoDBConstants;
import org.apache.hadoop.dynamodb.DynamoDBFibonacciRetryer.RetryResult;
import org.apache.hadoop.dynamodb.DynamoDBItemWritable;
import org.apache.hadoop.dynamodb.filter.DynamoDBQueryFilter;
import org.apache.hadoop.dynamodb.preader.DynamoDBRecordReaderContext;
import org.apache.hadoop.dynamodb.split.DynamoDBSegmentsSplit;
import org.apache.hadoop.dynamodb.split.DynamoDBSplit;
import org.apache.hadoop.mapred.Counters.Counter;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
public class DynamoDBRecordReaderTest {
private static final String HASH_KEY = "hashKey";
private static final String RANGE_KEY = "rangeKey";
private static final int NUM_RANGE_KEYS_PER_HASH_KEY = 3;
private static final String[] HASH_KEYS = {"6d9KhslLlNWKoPUpOrYX",
"<KEY>", "<KEY>", "<KEY>"};
@Test
public void testPaginatedReads() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
int i = 0;
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
List<Map<String, AttributeValue>> items = getItems();
if (i == 0) {
Map<String, AttributeValue> lastEvaluatedKey = new HashMap<>();
lastEvaluatedKey.put("test", AttributeValue.fromS("test"));
i++;
return new RetryResult<>(ScanResponse.builder()
.scannedCount(items.size())
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.items(items)
.lastEvaluatedKey(lastEvaluatedKey)
.build(), 0);
} else {
assertEquals("test", exclusiveStartKey.get("test").s());
return new RetryResult<>(ScanResponse.builder()
.scannedCount(items.size())
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.items(items)
.build(), 0);
}
}
private List<Map<String, AttributeValue>> getItems() {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : HASH_KEYS) {
Map<String, AttributeValue> item = new HashMap<>();
item.put("hashKey", AttributeValue.fromS(key));
items.add(item);
}
return items;
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (int i = 0; i < 8; i++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(HASH_KEYS[(i / 2) % 4], getHashKeyValue(value, "S"));
}
boolean ret = reader.next(reader.createKey(), null);
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testConsumingRemainingElementsIfEndKeyIsNull() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", "N");
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
return new RetryResult<>(getHashNumberRangeKeyItems(HASH_KEYS, "S"), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
for (int j = 0; j < NUM_RANGE_KEYS_PER_HASH_KEY; j++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
assertEquals(j, Integer.parseInt(getRangeKeyValue(value, "N")));
}
}
boolean ret = reader.next(reader.createKey(), reader.createValue());
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testConsumingAllBeginningElementsIfStartKeyIsNull() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", "N");
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
assertNull(exclusiveStartKey);
return new RetryResult<>(getHashNumberRangeKeyItems(HASH_KEYS, "S"), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
for (int j = 0; j < NUM_RANGE_KEYS_PER_HASH_KEY; j++) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
assertEquals(j, Integer.parseInt(getRangeKeyValue(value, "N")));
}
}
boolean ret = reader.next(reader.createKey(), reader.createValue());
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void testScanFirstSegment() {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
assertEquals(0, (int) segment);
assertEquals(4, (int) totalSegments);
return new RetryResult<>(getHashKeyItems(HASH_KEYS), 0);
}
});
// Setup mock client
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
// Check result
try {
for (String hashKey : HASH_KEYS) {
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
assertEquals(hashKey, getHashKeyValue(value, "S"));
}
boolean ret = reader.next(reader.createKey(), null);
assertEquals(false, ret);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test(expected = IOException.class, timeout = 10000)
public void testExceptionInDbClient() throws IOException {
DynamoDBSplit split = new DynamoDBSegmentsSplit(null, 0, 0, Arrays.asList(0), 4, 0, new
DynamoDBQueryFilter());
DynamoDBRecordReaderContext context = buildContext();
context.setSplit(split);
context.setClient(new DynamoDBClient() {
@Override
public TableDescription describeTable(String tableName) {
return getTableDescription("S", null);
}
@Override
public RetryResult<ScanResponse> scanTable(String tableName, DynamoDBQueryFilter
dynamoDBQueryFilter, Integer segment, Integer totalSegments, Map<String,
AttributeValue> exclusiveStartKey, long limit, Reporter reporter) {
throw new RuntimeException("Unrecoverable Exception");
}
});
DefaultDynamoDBRecordReader reader = new DefaultDynamoDBRecordReader(context);
DynamoDBItemWritable value = reader.createValue();
reader.next(reader.createKey(), value);
}
private DynamoDBRecordReaderContext buildContext() {
DynamoDBRecordReaderContext context = new DynamoDBRecordReaderContext();
context.setAttributes(null);
context.setConf(getTestConf());
context.setReporter(new Reporter() {
@Override
public void progress() {
}
@Override
public void setStatus(String arg0) {
}
@Override
public void incrCounter(String arg0, String arg1, long arg2) {
}
@Override
public void incrCounter(Enum<?> arg0, long arg1) {
}
@Override
public InputSplit getInputSplit() throws UnsupportedOperationException {
return null;
}
@Override
public Counter getCounter(String arg0, String arg1) {
return null;
}
@Override
public Counter getCounter(Enum<?> arg0) {
return null;
}
@Override
public float getProgress() {
return 0;
}
});
return context;
}
private String getHashKeyValue(DynamoDBItemWritable value, String type) {
return getKeyValue(value, HASH_KEY, type);
}
private String getRangeKeyValue(DynamoDBItemWritable value, String type) {
return getKeyValue(value, RANGE_KEY, type);
}
private String getKeyValue(DynamoDBItemWritable value, String keyName, String type) {
if (type.equals("S")) {
return value.getItem().get(keyName).s();
} else {
return value.getItem().get(keyName).n();
}
}
private ScanResponse getHashKeyItems(String[] hashKeys) {
return getHashKeyItems(hashKeys, "S");
}
private ScanResponse getHashKeyItems(String[] hashKeys, String type) {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : hashKeys) {
Map<String, AttributeValue> item = new HashMap<>();
if (type.equals("S")) {
item.put("hashKey", AttributeValue.fromS(key));
} else {
item.put("hashKey", AttributeValue.fromN(key));
}
items.add(item);
}
return ScanResponse.builder()
.scannedCount(items.size())
.items(items)
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.build();
}
private ScanResponse getHashNumberRangeKeyItems(String[] hashKeys, String hashType) {
List<Map<String, AttributeValue>> items = new ArrayList<>();
for (String key : hashKeys) {
for (Integer i = 0; i < NUM_RANGE_KEYS_PER_HASH_KEY; i++) {
Map<String, AttributeValue> item = new HashMap<>();
if (hashType.equals("S")) {
item.put("hashKey", AttributeValue.fromS(key));
} else {
item.put("hashKey", AttributeValue.fromN(key));
}
item.put("rangeKey", AttributeValue.fromN("0" + i.toString()));
items.add(item);
}
}
return ScanResponse.builder()
.scannedCount(items.size())
.items(items)
.consumedCapacity(ConsumedCapacity.builder()
.capacityUnits(1d)
.build())
.build();
}
private TableDescription getTableDescription(String hashType, String rangeType) {
List<KeySchemaElement> keySchema = new ArrayList<>();
List<AttributeDefinition> definitions = new ArrayList<>();
keySchema.add(KeySchemaElement.builder()
.attributeName("hashKey")
.keyType(KeyType.HASH)
.build());
definitions.add(AttributeDefinition.builder()
.attributeName("hashKey")
.attributeType(hashType)
.build());
if (rangeType != null) {
keySchema.add(KeySchemaElement.builder()
.attributeName("rangeKey")
.keyType(KeyType.RANGE)
.build());
definitions.add(AttributeDefinition.builder()
.attributeName("rangeKey")
.attributeType(rangeType)
.build());
}
TableDescription description = TableDescription.builder()
.keySchema(keySchema)
.attributeDefinitions(definitions)
.provisionedThroughput(ProvisionedThroughputDescription.builder()
.readCapacityUnits(1000L)
.writeCapacityUnits(1000L)
.build())
.build();
return description;
}
private JobConf getTestConf() {
JobConf conf = new JobConf();
conf.set(DynamoDBConstants.DEFAULT_ACCESS_KEY_CONF, "abc");
conf.set(DynamoDBConstants.DEFAULT_SECRET_KEY_CONF, "abcd");
return conf;
}
}
| 14,964 | 0.669577 | 0.663578 | 430 | 33.888371 | 27.231337 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711628 | false | false | 0 |
ddbd7ddd2553179980d2d4fea14bc5eca13b8322 | 11,991,548,760,148 | 8db35ebbbb64d34a6773c16659b65edc4af10a70 | /weinxin/src/main/java/com/tencent/mm/compatible/util/n.java | b86444f566ea5d9a5823347b17e9a60498a4187e | []
| no_license | cj3479/demo | https://github.com/cj3479/demo | 5ba417538281ad2015bd8f4fe0c6985560acea05 | 0e254aac3fac68d12f3b65791ca21d109be504b7 | refs/heads/master | 2020-03-02T17:42:17.773000 | 2019-09-11T07:37:35 | 2019-09-11T07:37:35 | 102,733,897 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.compatible.util;
import android.os.Build;
import android.os.Build.VERSION;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.compatible.d.j;
import com.tencent.mm.compatible.d.p;
import com.tencent.mm.sdk.platformtools.bf;
public final class n
{
public static String dz(String paramString)
{
GMTrace.i(13779731480576L, 102667);
if (paramString == null)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gPP == 2)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gQa == 1)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gPP == 1)
{
if (paramString.toString().contains("\n"))
{
paramString = paramString.toString().replace("\n", " ");
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (Build.VERSION.SDK_INT == 16)
{
if (paramString.toString().contains("\n"))
{
if (bf.ap(Build.MANUFACTURER, "").toLowerCase().indexOf("meizu".toLowerCase()) >= 0)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
paramString = paramString.toString().replace("\n", " ");
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
}
/* Location: /home/chengjian/weinxin/weinxin_1100/classes.jar!/com/tencent/mm/compatible/util/n.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,757 | java | n.java | Java | []
| null | []
| package com.tencent.mm.compatible.util;
import android.os.Build;
import android.os.Build.VERSION;
import com.tencent.gmtrace.GMTrace;
import com.tencent.mm.compatible.d.j;
import com.tencent.mm.compatible.d.p;
import com.tencent.mm.sdk.platformtools.bf;
public final class n
{
public static String dz(String paramString)
{
GMTrace.i(13779731480576L, 102667);
if (paramString == null)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gPP == 2)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gQa == 1)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (p.gRb.gPP == 1)
{
if (paramString.toString().contains("\n"))
{
paramString = paramString.toString().replace("\n", " ");
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
if (Build.VERSION.SDK_INT == 16)
{
if (paramString.toString().contains("\n"))
{
if (bf.ap(Build.MANUFACTURER, "").toLowerCase().indexOf("meizu".toLowerCase()) >= 0)
{
GMTrace.o(13779731480576L, 102667);
return paramString;
}
paramString = paramString.toString().replace("\n", " ");
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
GMTrace.o(13779731480576L, 102667);
return paramString;
}
}
/* Location: /home/chengjian/weinxin/weinxin_1100/classes.jar!/com/tencent/mm/compatible/util/n.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 1,757 | 0.618099 | 0.494593 | 66 | 25.636364 | 21.945274 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621212 | false | false | 0 |
490a0cb69c46cd3f175d389b4e120df3f50cc60b | 4,320,737,116,959 | 37c47de25136190e084d521cec595e70299f9dac | /AbstractFactory/src/AbstractFactory/QueijoMinas.java | d253cd245cc55650e3095e9681571f4141c138fe | []
| no_license | felipeddallilo/padroesdeprojetos | https://github.com/felipeddallilo/padroesdeprojetos | 51a0319990d2472fbcec17cab9d3e1949e99476c | 2ff5e46b89423e65f61505c1cb990e06f4807ade | refs/heads/master | 2020-06-20T20:33:36.045000 | 2019-07-26T07:09:01 | 2019-07-26T07:09:01 | 197,239,677 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package AbstractFactory;
public class QueijoMinas extends Queijo {
}
| UTF-8 | Java | 71 | java | QueijoMinas.java | Java | []
| null | []
| package AbstractFactory;
public class QueijoMinas extends Queijo {
}
| 71 | 0.802817 | 0.802817 | 5 | 13.2 | 16.654129 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 0 |
68fd7f0a12a509e15101762460dba2ef01be67f9 | 4,647,154,672,575 | 0b9390394a51a7f7fe1b2ad976327cfda2cfa026 | /src/PS/HackerRank/PS/The_Hurdle_Race.java | fdb5b8224fc173fdc5e3a8f93e5949a40204e873 | []
| no_license | Vishnu05/DS | https://github.com/Vishnu05/DS | 277d3005316fdb8c3c4a14a72129fe5c3219f9e8 | b30850ebd7c18d3931b50e2f2bb98ccd878a7f84 | refs/heads/master | 2021-06-27T22:50:31.121000 | 2020-10-07T09:16:31 | 2020-10-07T09:16:31 | 164,674,177 | 0 | 0 | null | false | 2020-04-01T01:24:19 | 2019-01-08T15:09:28 | 2020-04-01T01:07:53 | 2020-04-01T01:24:19 | 2,660 | 0 | 0 | 0 | Java | false | false | package PS.HackerRank.PS;
import java.util.Scanner;
public class The_Hurdle_Race {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = scan.nextInt();
int j = scan.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
int k = 0;
for (int i = 0; i < n; i++) {
if (arr[k] < arr[i]) {
k = i;
}
}
int l = arr[k];
if (j < l) {
System.out.println(arr[k] - j);
} else {
System.out.println("0");
}
}
}
| UTF-8 | Java | 668 | java | The_Hurdle_Race.java | Java | []
| null | []
| package PS.HackerRank.PS;
import java.util.Scanner;
public class The_Hurdle_Race {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = scan.nextInt();
int j = scan.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
int k = 0;
for (int i = 0; i < n; i++) {
if (arr[k] < arr[i]) {
k = i;
}
}
int l = arr[k];
if (j < l) {
System.out.println(arr[k] - j);
} else {
System.out.println("0");
}
}
}
| 668 | 0.422156 | 0.416168 | 34 | 18.647058 | 15.637215 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 0 |
d5956d14d1ea64d8a1ed67da4905a10b451b097e | 14,199,161,936,731 | 83b05f04b6c72b91f18add601ee769c189cecd40 | /Tema 2/src/exercicis/Exercici30.java | b32e55b9f0e37419152859201f873f073c7d2b44 | []
| no_license | Soteck/Java | https://github.com/Soteck/Java | afa1ad004b5af33a214cc67a447471bb6ccfda1f | 88f759349609567f21c98e268a9a8722f1f8ebf1 | refs/heads/master | 2020-06-03T09:03:11.400000 | 2014-03-28T19:41:07 | 2014-03-28T19:41:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /** Exercici 30
*Utilitzant els mètodes de la classe String, per la cadena Això era i no era, fes un programa que
Mostri la longitud de la cadena.
Els dos primers caràcters.
La compari amb una altre sense tenir en compte les diferències majúscules / minúscules.
Trobi la posició de la primera lletra e.
Escrigui la lletra que ocupa la posició 6.
* @author Cristian
*/
package exercicis;
public class Exercici30 {
public static void main(String[] args) {
String frase = "Això era i no era";
String oracio = "Hola";
System.out.println("La longitud és: " + frase.length());
System.out.println("Primer caracter: " + frase.charAt(0) + " i segon caracter: " + frase.charAt(1));
int comparacio=frase.compareToIgnoreCase(oracio);
if (comparacio<0){
System.out.println("No es pareixen");
}
else if (comparacio==0) {
System.out.println("Són iguals");
} else {
System.out.println("Són parescudes");
}
System.out.println("La primera e está a la posicio: " + frase.indexOf("e"));
System.out.println("Posició 6: " + frase.charAt(6));
}
}
| ISO-8859-1 | Java | 1,146 | java | Exercici30.java | Java | [
{
"context": "ui la lletra que ocupa la posició 6.\r\n\r\n * @author Cristian\r\n\r\n */\r\n\r\npackage exercicis;\r\n\r\npublic class Exer",
"end": 386,
"score": 0.9998520016670227,
"start": 378,
"tag": "NAME",
"value": "Cristian"
}
]
| null | []
| /** Exercici 30
*Utilitzant els mètodes de la classe String, per la cadena Això era i no era, fes un programa que
Mostri la longitud de la cadena.
Els dos primers caràcters.
La compari amb una altre sense tenir en compte les diferències majúscules / minúscules.
Trobi la posició de la primera lletra e.
Escrigui la lletra que ocupa la posició 6.
* @author Cristian
*/
package exercicis;
public class Exercici30 {
public static void main(String[] args) {
String frase = "Això era i no era";
String oracio = "Hola";
System.out.println("La longitud és: " + frase.length());
System.out.println("Primer caracter: " + frase.charAt(0) + " i segon caracter: " + frase.charAt(1));
int comparacio=frase.compareToIgnoreCase(oracio);
if (comparacio<0){
System.out.println("No es pareixen");
}
else if (comparacio==0) {
System.out.println("Són iguals");
} else {
System.out.println("Són parescudes");
}
System.out.println("La primera e está a la posicio: " + frase.indexOf("e"));
System.out.println("Posició 6: " + frase.charAt(6));
}
}
| 1,146 | 0.660777 | 0.65106 | 46 | 22.52174 | 27.604929 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.130435 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.