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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eca6495269b3c61c9b6edcd8fd25c5884390bd70 | 28,089,086,147,535 | 2dd2fefc14c2a9c160546817f72f28ded0e5ae9a | /src/main/java/com/houseofcards/repositories/LoginInfoRepository.java | 52e32976b203a456a2df92a8cef79bb8f1d2d327 | [] | no_license | mupetmower/HouseOfCards | https://github.com/mupetmower/HouseOfCards | 1e55450af820a2740b43bb93179e9a603a619099 | 3c725df3d78664e33fbc7031d9914b4a1eebe67b | refs/heads/updates | 2022-11-24T05:19:32.757000 | 2018-05-06T15:41:46 | 2018-05-06T15:41:46 | 127,170,809 | 0 | 0 | null | false | 2018-05-06T15:42:24 | 2018-03-28T16:49:33 | 2018-05-06T15:41:50 | 2018-05-06T15:42:24 | 38,688 | 0 | 0 | 0 | Java | false | null | package com.houseofcards.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.houseofcards.entities.generated.Logininfo;
import com.houseofcards.entities.generated.User;
public interface LoginInfoRepository extends JpaRepository<Logininfo, String> {
public Logininfo findByUsername(String username);
}
| UTF-8 | Java | 344 | java | LoginInfoRepository.java | Java | [] | null | [] | package com.houseofcards.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.houseofcards.entities.generated.Logininfo;
import com.houseofcards.entities.generated.User;
public interface LoginInfoRepository extends JpaRepository<Logininfo, String> {
public Logininfo findByUsername(String username);
}
| 344 | 0.840116 | 0.840116 | 12 | 27.666666 | 28.630791 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 1 |
76830cf8e9507f9095f6d5d5ce14bbb72c72b2b1 | 21,397,527,076,711 | af4289a0dda48fad043c63b0f3446f169e25cc57 | /src/edu/stanford/nlp/sempre/tables/ConvertCsvToTtl.java | f69c39b558c026af97944cd82e38e37a834bbda2 | [] | no_license | Santos-Luis/MasterThesis | https://github.com/Santos-Luis/MasterThesis | eb85a9ced48e4a4bc1a8658aa9f3c65bd486520d | e705ddd085e2ed9dd9fb81e57118e189a63a4535 | refs/heads/master | 2020-04-03T07:05:25.430000 | 2018-11-02T09:48:22 | 2018-11-02T09:48:22 | 155,093,052 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.stanford.nlp.sempre.tables;
import java.io.*;
import java.util.*;
import java.text.*;
import au.com.bytecode.opencsv.CSVReader;
import edu.stanford.nlp.sempre.*;
import fig.basic.*;
import fig.exec.*;
import static fig.basic.LogInfo.*;
/**
Converts a CSV file into a TTL file to be loaded into Virtuoso.
Also dumps a lexicon file that maps strings to Freebase constants.
This allows us to quickly deploy semantic parsers on random CSV data that's not
already in Freebase.
Domain (e.g., paleo): everything will live under fb:<domain>.*
The input is a set of tables. Each table has:
- A set of column names (each column corresponds to a property)
- A set of row names (each row corresponds to an event).
- A name (this determines the type of the event).
Columns that contain strings are considered entities, and we define a new type
for that based on the column name. Important: note that different tables
interact by virtue of having the same column name (think of joining two tables
by string matching their column names). Of course, this is restrictive, but
it's good enough for now.
Example (domain: foo)
table name: info
columns: person, age, marital_status, social_security, place_of_birth
...
table name: education
columns: person, elementary_school, high_school, college
...
Event types: fb:foo.info, fb:foo.education
Properties: fb:foo.info.person, fb:foo.info.age, ...
Entity types: fb:foo.person, ...
Events: fb:foo.info0, fb:foo.info1, ...
Entities: fb:foo.barack_obama, ...
Each column is a property that could take on several values. A column could
have many different types (e.g., int, text, entity) depending on how the
values are parsed, but we can't do this with one pass over the data, so we're
punting on this for now.
@author Percy Liang
*/
public class ConvertCsvToTtl implements Runnable {
@Option(required = true, gloss = "Domain (used to specify all the entities)") public String domain;
@Option(required = true, gloss = "Input CSV <table name>:<table path> (assume each file has a header)") public List<String> tables;
@Option(required = true, gloss = "Output schema ttl to this path") public String outSchemaPath;
@Option(required = true, gloss = "Output ttl to this path") public String outTtlPath;
@Option(required = true, gloss = "Output lexicon to this path") public String outLexiconPath;
@Option(gloss = "Only use these columns") public List<String> keepProperties;
@Option(gloss = "Maximum number of rows to read per file") public int maxRowsPerFile = Integer.MAX_VALUE;
public static final String ttlPrefix = "@prefix fb: <http://rdf.freebase.com/ns/>.";
// Names and types of entities
Map<String, String> id2name = new HashMap<String, String>();
Map<String, Set<String>> id2types = new HashMap<String, Set<String>>();
// Used to parse values into dates
List<SimpleDateFormat> dateFormats = Arrays.asList(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH), // One used by Freebase
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH),
new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH));
String prependDomain(String s) { return "fb:" + domain + "." + s; }
String makeString(String s) {
if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\""))
s = s.substring(1, s.length() - 1);
s = s.replaceAll("\"", "\\\\\""); // Quote
return "\"" + s + "\"@en";
}
String lexEntry(String s, String id, Set<String> types) {
SemType type = types == null ? SemType.anyType : SemType.newUnionSemType(types);
Map<String, Object> result = new HashMap<String, Object>();
result.put("lexeme", s); // Note: this is not actually a lexeme, but the full rawPhrase.
result.put("formula", id);
result.put("source", "STRING_MATCH");
result.put("type", type);
return Json.writeValueAsStringHard(result);
}
String canonicalize(String value) {
if (Character.isDigit(value.charAt(value.length() - 1))) {
// Try to convert to integer
try {
Integer.parseInt(value);
return "\"" + value + "\"^^xsd:int";
} catch (NumberFormatException e) {
}
// Try to convert to double
try {
Double.parseDouble(value);
return "\"" + value + "\"^^xsd:double";
} catch (NumberFormatException e) {
}
// Try to convert to date
for (DateFormat format : dateFormats) {
try {
Date date = format.parse(value);
return "\"" + dateFormats.get(0).format(date) + "\"^^xsd:datetime";
} catch (ParseException e) {
}
}
}
// Try to interpret as entity if it is short enough
if (value.split(" ").length <= 5) {
String id = value;
id = id.replaceAll("[^\\w]", "_"); // Replace abnormal characters with _
id = id.replaceAll("_+", "_"); // Merge consecutive _'s
id = id.replaceAll("_$", "");
id = id.toLowerCase();
if (id.length() == 0) id = "null";
id = prependDomain(id);
id2name.put(id, value);
return id;
}
// Just interpret as string
return makeString(value);
}
public static void writeTriple(PrintWriter out, String arg1, String property, String arg2) {
out.println(arg1 + "\t" + property + "\t" + arg2 + ".");
}
static class Column {
String description;
String header;
String property;
int numInt, numDouble, numDate, numText, numEntity;
// Return whether we have an entity.
boolean add(String value) {
if (value.endsWith("xsd:int"))
numInt++;
else if (value.endsWith("xsd:double"))
numDouble++;
else if (value.endsWith("xsd:datetime"))
numDate++;
else if (value.endsWith("@en"))
numText++;
else {
numEntity++;
return true;
}
return false;
}
String getEntityType() { return header; }
String getType() {
int[] counts = new int[] {numInt, numDouble, numDate, numText, numEntity};
int max = ListUtils.max(counts);
// if (numInt == max) return FreebaseInfo.INT;
// if (numDouble == max) return FreebaseInfo.FLOAT;
if (numInt == max) return CanonicalNames.NUMBER;
if (numDouble == max) return CanonicalNames.NUMBER;
if (numDate == max) return CanonicalNames.DATE;
if (numText == max) return CanonicalNames.TEXT;
return getEntityType();
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append(header);
if (numInt > 0) b.append(", int=" + numInt);
if (numDouble > 0) b.append(", double=" + numDouble);
if (numDate > 0) b.append(", date=" + numDate);
if (numText > 0) b.append(", text=" + numText);
if (numEntity > 0) b.append(", entity=" + numEntity);
return b.toString();
}
}
public void run() {
PrintWriter schemaOut = IOUtils.openOutHard(outSchemaPath);
PrintWriter ttlOut = IOUtils.openOutHard(outTtlPath);
PrintWriter lexiconOut = IOUtils.openOutHard(outLexiconPath);
ttlOut.println(ttlPrefix);
int total = 0;
for (String pairStr : tables) {
int num = 0; // The row number (standards for an event / CSV)
String[] pair = pairStr.split(":", 2);
if (pair.length != 2) throw new RuntimeException("Expected <table name>:<file name> pair, but got: " + pair);
String tableName = pair[0];
String inPath = pair[1];
String eventType = prependDomain(tableName); // e.g., fb:paleo.taxon
LogInfo.begin_track("Reading %s for events of type %s", inPath, eventType);
Column[] columns = null;
try (CSVReader csv = new CSVReader(new FileReader(inPath))) {
for (String[] row : csv) {
if (num >= maxRowsPerFile) break;
// Initialize the columns
if (columns == null) {
columns = new Column[row.length];
for (int i = 0; i < columns.length; i++) {
Column c = columns[i] = new Column();
row[i] = row[i].trim();
c.description = row[i];
c.header = canonicalize(row[i]);
if (keepProperties != null && !keepProperties.contains(c.header)) {
c.header = null;
continue;
}
if (!c.header.startsWith("fb:" + domain))
throw new RuntimeException("Invalid (internal problem): " + c.header);
c.property = c.header.replace("fb:" + domain, "fb:" + domain + "." + tableName); // Property
}
continue;
}
// Read a row (corresponds to an event/CVT)
String event = prependDomain(tableName + (num++));
writeTriple(ttlOut, event, "fb:type.object.type", tableName);
for (int i = 0; i < Math.min(row.length, columns.length); i++) { // For each column...
Column c = columns[i];
if (c.header == null || row[i].equals("")) continue;
row[i] = canonicalize(row[i]);
writeTriple(ttlOut, event, c.property, row[i]); // Write out the assertion
if (c.add(row[i])) { // Write out type for entities
MapUtils.addToSet(id2types, row[i], c.getEntityType());
writeTriple(ttlOut, row[i], "fb:type.object.type", c.getEntityType());
writeTriple(ttlOut, row[i], "fb:type.object.type", CanonicalNames.ENTITY);
}
}
if (num % 10000 == 0)
logs("Read %d rows (events)", num);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// Write out schema
writeTriple(schemaOut, eventType, "fb:freebase.type_hints.mediator", "\"true\"^^xsd:boolean"); // event type is a CVT
for (Column c : columns) {
if (c.header == null) continue;
writeTriple(schemaOut, c.property, "fb:type.object.type", "fb:type.property");
writeTriple(schemaOut, c.property, "fb:type.property.schema", eventType);
writeTriple(schemaOut, c.property, "fb:type.property.expected_type", c.getType());
writeTriple(schemaOut, c.property, "fb:type.object.name", makeString(c.description));
if (c.getType().equals(c.getEntityType())) {
writeTriple(schemaOut, c.getEntityType(), "fb:type.object.name", makeString(c.description));
writeTriple(schemaOut, c.getEntityType(), "fb:freebase.type_hints.included_types", CanonicalNames.ENTITY);
}
LogInfo.logs("%s", c);
}
LogInfo.end_track();
total += num;
}
logs("%d events, %d entities (ones with names)", total, id2name.size());
for (Map.Entry<String, String> e : id2name.entrySet()) {
writeTriple(ttlOut, e.getKey(), "fb:type.object.name", makeString(e.getValue()));
String k = e.getKey();
String s = e.getValue();
Set<String> types = id2types.get(k);
lexiconOut.println(lexEntry(s, k, types));
}
schemaOut.close();
ttlOut.close();
lexiconOut.close();
}
public static void main(String[] args) {
Execution.run(args, new ConvertCsvToTtl());
}
}
| UTF-8 | Java | 11,103 | java | ConvertCsvToTtl.java | Java | [
{
"context": "e data, so we're\npunting on this for now.\n\n@author Percy Liang\n*/\npublic class ConvertCsvToTtl implements Runnab",
"end": 1805,
"score": 0.9997720122337341,
"start": 1794,
"tag": "NAME",
"value": "Percy Liang"
}
] | null | [] | package edu.stanford.nlp.sempre.tables;
import java.io.*;
import java.util.*;
import java.text.*;
import au.com.bytecode.opencsv.CSVReader;
import edu.stanford.nlp.sempre.*;
import fig.basic.*;
import fig.exec.*;
import static fig.basic.LogInfo.*;
/**
Converts a CSV file into a TTL file to be loaded into Virtuoso.
Also dumps a lexicon file that maps strings to Freebase constants.
This allows us to quickly deploy semantic parsers on random CSV data that's not
already in Freebase.
Domain (e.g., paleo): everything will live under fb:<domain>.*
The input is a set of tables. Each table has:
- A set of column names (each column corresponds to a property)
- A set of row names (each row corresponds to an event).
- A name (this determines the type of the event).
Columns that contain strings are considered entities, and we define a new type
for that based on the column name. Important: note that different tables
interact by virtue of having the same column name (think of joining two tables
by string matching their column names). Of course, this is restrictive, but
it's good enough for now.
Example (domain: foo)
table name: info
columns: person, age, marital_status, social_security, place_of_birth
...
table name: education
columns: person, elementary_school, high_school, college
...
Event types: fb:foo.info, fb:foo.education
Properties: fb:foo.info.person, fb:foo.info.age, ...
Entity types: fb:foo.person, ...
Events: fb:foo.info0, fb:foo.info1, ...
Entities: fb:foo.barack_obama, ...
Each column is a property that could take on several values. A column could
have many different types (e.g., int, text, entity) depending on how the
values are parsed, but we can't do this with one pass over the data, so we're
punting on this for now.
@author <NAME>
*/
public class ConvertCsvToTtl implements Runnable {
@Option(required = true, gloss = "Domain (used to specify all the entities)") public String domain;
@Option(required = true, gloss = "Input CSV <table name>:<table path> (assume each file has a header)") public List<String> tables;
@Option(required = true, gloss = "Output schema ttl to this path") public String outSchemaPath;
@Option(required = true, gloss = "Output ttl to this path") public String outTtlPath;
@Option(required = true, gloss = "Output lexicon to this path") public String outLexiconPath;
@Option(gloss = "Only use these columns") public List<String> keepProperties;
@Option(gloss = "Maximum number of rows to read per file") public int maxRowsPerFile = Integer.MAX_VALUE;
public static final String ttlPrefix = "@prefix fb: <http://rdf.freebase.com/ns/>.";
// Names and types of entities
Map<String, String> id2name = new HashMap<String, String>();
Map<String, Set<String>> id2types = new HashMap<String, Set<String>>();
// Used to parse values into dates
List<SimpleDateFormat> dateFormats = Arrays.asList(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH), // One used by Freebase
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH),
new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH));
String prependDomain(String s) { return "fb:" + domain + "." + s; }
String makeString(String s) {
if (s.length() >= 2 && s.startsWith("\"") && s.endsWith("\""))
s = s.substring(1, s.length() - 1);
s = s.replaceAll("\"", "\\\\\""); // Quote
return "\"" + s + "\"@en";
}
String lexEntry(String s, String id, Set<String> types) {
SemType type = types == null ? SemType.anyType : SemType.newUnionSemType(types);
Map<String, Object> result = new HashMap<String, Object>();
result.put("lexeme", s); // Note: this is not actually a lexeme, but the full rawPhrase.
result.put("formula", id);
result.put("source", "STRING_MATCH");
result.put("type", type);
return Json.writeValueAsStringHard(result);
}
String canonicalize(String value) {
if (Character.isDigit(value.charAt(value.length() - 1))) {
// Try to convert to integer
try {
Integer.parseInt(value);
return "\"" + value + "\"^^xsd:int";
} catch (NumberFormatException e) {
}
// Try to convert to double
try {
Double.parseDouble(value);
return "\"" + value + "\"^^xsd:double";
} catch (NumberFormatException e) {
}
// Try to convert to date
for (DateFormat format : dateFormats) {
try {
Date date = format.parse(value);
return "\"" + dateFormats.get(0).format(date) + "\"^^xsd:datetime";
} catch (ParseException e) {
}
}
}
// Try to interpret as entity if it is short enough
if (value.split(" ").length <= 5) {
String id = value;
id = id.replaceAll("[^\\w]", "_"); // Replace abnormal characters with _
id = id.replaceAll("_+", "_"); // Merge consecutive _'s
id = id.replaceAll("_$", "");
id = id.toLowerCase();
if (id.length() == 0) id = "null";
id = prependDomain(id);
id2name.put(id, value);
return id;
}
// Just interpret as string
return makeString(value);
}
public static void writeTriple(PrintWriter out, String arg1, String property, String arg2) {
out.println(arg1 + "\t" + property + "\t" + arg2 + ".");
}
static class Column {
String description;
String header;
String property;
int numInt, numDouble, numDate, numText, numEntity;
// Return whether we have an entity.
boolean add(String value) {
if (value.endsWith("xsd:int"))
numInt++;
else if (value.endsWith("xsd:double"))
numDouble++;
else if (value.endsWith("xsd:datetime"))
numDate++;
else if (value.endsWith("@en"))
numText++;
else {
numEntity++;
return true;
}
return false;
}
String getEntityType() { return header; }
String getType() {
int[] counts = new int[] {numInt, numDouble, numDate, numText, numEntity};
int max = ListUtils.max(counts);
// if (numInt == max) return FreebaseInfo.INT;
// if (numDouble == max) return FreebaseInfo.FLOAT;
if (numInt == max) return CanonicalNames.NUMBER;
if (numDouble == max) return CanonicalNames.NUMBER;
if (numDate == max) return CanonicalNames.DATE;
if (numText == max) return CanonicalNames.TEXT;
return getEntityType();
}
@Override public String toString() {
StringBuilder b = new StringBuilder();
b.append(header);
if (numInt > 0) b.append(", int=" + numInt);
if (numDouble > 0) b.append(", double=" + numDouble);
if (numDate > 0) b.append(", date=" + numDate);
if (numText > 0) b.append(", text=" + numText);
if (numEntity > 0) b.append(", entity=" + numEntity);
return b.toString();
}
}
public void run() {
PrintWriter schemaOut = IOUtils.openOutHard(outSchemaPath);
PrintWriter ttlOut = IOUtils.openOutHard(outTtlPath);
PrintWriter lexiconOut = IOUtils.openOutHard(outLexiconPath);
ttlOut.println(ttlPrefix);
int total = 0;
for (String pairStr : tables) {
int num = 0; // The row number (standards for an event / CSV)
String[] pair = pairStr.split(":", 2);
if (pair.length != 2) throw new RuntimeException("Expected <table name>:<file name> pair, but got: " + pair);
String tableName = pair[0];
String inPath = pair[1];
String eventType = prependDomain(tableName); // e.g., fb:paleo.taxon
LogInfo.begin_track("Reading %s for events of type %s", inPath, eventType);
Column[] columns = null;
try (CSVReader csv = new CSVReader(new FileReader(inPath))) {
for (String[] row : csv) {
if (num >= maxRowsPerFile) break;
// Initialize the columns
if (columns == null) {
columns = new Column[row.length];
for (int i = 0; i < columns.length; i++) {
Column c = columns[i] = new Column();
row[i] = row[i].trim();
c.description = row[i];
c.header = canonicalize(row[i]);
if (keepProperties != null && !keepProperties.contains(c.header)) {
c.header = null;
continue;
}
if (!c.header.startsWith("fb:" + domain))
throw new RuntimeException("Invalid (internal problem): " + c.header);
c.property = c.header.replace("fb:" + domain, "fb:" + domain + "." + tableName); // Property
}
continue;
}
// Read a row (corresponds to an event/CVT)
String event = prependDomain(tableName + (num++));
writeTriple(ttlOut, event, "fb:type.object.type", tableName);
for (int i = 0; i < Math.min(row.length, columns.length); i++) { // For each column...
Column c = columns[i];
if (c.header == null || row[i].equals("")) continue;
row[i] = canonicalize(row[i]);
writeTriple(ttlOut, event, c.property, row[i]); // Write out the assertion
if (c.add(row[i])) { // Write out type for entities
MapUtils.addToSet(id2types, row[i], c.getEntityType());
writeTriple(ttlOut, row[i], "fb:type.object.type", c.getEntityType());
writeTriple(ttlOut, row[i], "fb:type.object.type", CanonicalNames.ENTITY);
}
}
if (num % 10000 == 0)
logs("Read %d rows (events)", num);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// Write out schema
writeTriple(schemaOut, eventType, "fb:freebase.type_hints.mediator", "\"true\"^^xsd:boolean"); // event type is a CVT
for (Column c : columns) {
if (c.header == null) continue;
writeTriple(schemaOut, c.property, "fb:type.object.type", "fb:type.property");
writeTriple(schemaOut, c.property, "fb:type.property.schema", eventType);
writeTriple(schemaOut, c.property, "fb:type.property.expected_type", c.getType());
writeTriple(schemaOut, c.property, "fb:type.object.name", makeString(c.description));
if (c.getType().equals(c.getEntityType())) {
writeTriple(schemaOut, c.getEntityType(), "fb:type.object.name", makeString(c.description));
writeTriple(schemaOut, c.getEntityType(), "fb:freebase.type_hints.included_types", CanonicalNames.ENTITY);
}
LogInfo.logs("%s", c);
}
LogInfo.end_track();
total += num;
}
logs("%d events, %d entities (ones with names)", total, id2name.size());
for (Map.Entry<String, String> e : id2name.entrySet()) {
writeTriple(ttlOut, e.getKey(), "fb:type.object.name", makeString(e.getValue()));
String k = e.getKey();
String s = e.getValue();
Set<String> types = id2types.get(k);
lexiconOut.println(lexEntry(s, k, types));
}
schemaOut.close();
ttlOut.close();
lexiconOut.close();
}
public static void main(String[] args) {
Execution.run(args, new ConvertCsvToTtl());
}
}
| 11,098 | 0.620463 | 0.61695 | 285 | 37.957893 | 29.41807 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.915789 | false | false | 1 |
5813d6ec0158072c1c9cca3196ec60406cda69b4 | 11,811,160,099,027 | 0a80c461842b83db4a44c3d34052bda29ceea8af | /WebServiceProject/src/com/ws/test/EmployeeService.java | 445b2d58a3ebd418243e3689255125f86dc4a15d | [] | no_license | khinendra/CICD_POC_Repo | https://github.com/khinendra/CICD_POC_Repo | 1a5807a13d52e057f704db712a472e3bd4dc3686 | 0da5a2c7fc3711886e77b8a7c8e25855df0b22ee | refs/heads/master | 2021-01-11T19:25:47.828000 | 2017-03-14T17:18:55 | 2017-03-14T17:18:55 | 79,363,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ws.test;
public interface EmployeeService {
public String getEmplyeeName(String loginname);
public String getEmployeeAddress(String loginname);
}
| UTF-8 | Java | 165 | java | EmployeeService.java | Java | [] | null | [] | package com.ws.test;
public interface EmployeeService {
public String getEmplyeeName(String loginname);
public String getEmployeeAddress(String loginname);
}
| 165 | 0.8 | 0.8 | 6 | 25.5 | 20.27108 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
dce4e6d2b633057f130cc9fa7b529879b4c59a03 | 32,899,449,491,808 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /java/java-tests/testData/inspection/explicitArrayFilling/afterByteArray.java | c0aaac94be341fec2b962df8ba291d50c0655109 | [
"Apache-2.0"
] | permissive | JetBrains/intellij-community | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | // "Replace loop with 'Arrays.fill()' method call" "true"
import java.util.Arrays;
class Test {
void fillByteArray() {
byte[] plaintext = {1,2,3,4,5};
Arrays.fill(plaintext, (byte) 0);
}
} | UTF-8 | Java | 205 | java | afterByteArray.java | Java | [] | null | [] | // "Replace loop with 'Arrays.fill()' method call" "true"
import java.util.Arrays;
class Test {
void fillByteArray() {
byte[] plaintext = {1,2,3,4,5};
Arrays.fill(plaintext, (byte) 0);
}
} | 205 | 0.619512 | 0.590244 | 11 | 17.727272 | 18.694145 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 1 |
8419618a62432a64befd585b47e1be064721040f | 11,132,555,290,960 | 2c1654115a16dd9d54d46c13c5fd698eca796c99 | /MESTRA JAVA TOOL/src/mestra/Trace_SRS_MF.java | 4c33f87fb9fa01437bfa290dd6eb972ba641b6aa | [] | no_license | RobertPastor/MestraJavaXML | https://github.com/RobertPastor/MestraJavaXML | fe641167bc23fab1036e10b0229d95c3426ebd1c | 3282f93ae36b2ebc4edba4ad5f1a5edf545a68df | refs/heads/master | 2021-07-18T15:54:58.782000 | 2020-05-22T13:52:16 | 2020-05-22T13:52:16 | 166,102,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mestra;
import configuration.ConfigurationFileBaseReader;
public class Trace_SRS_MF extends MestraSRS {
private MestraMF mestraMF = null;
public Trace_SRS_MF(MestraSRS mestraSRS, MestraMF aMestraMF, ConfigurationFileBaseReader configuration) {
super(mestraSRS, configuration);
if (aMestraMF == null) {
this.mestraMF = null;
}
else {
this.mestraMF = (MestraMF)aMestraMF.clone();
}
}
public Trace_SRS_MF getThis() {
return this;
}
/**
* @return the mestraSDD
*/
public MestraMF getMestraMF() {
return this.mestraMF;
}
public void setMestraMF(MestraMF aMestraMF) {
this.mestraMF = aMestraMF;
}
public String getMFIdentifier() {
if (this.mestraMF == null) {
return "";
}
else {
return this.mestraMF.getIdentifier();
}
}
}
| UTF-8 | Java | 856 | java | Trace_SRS_MF.java | Java | [] | null | [] | package mestra;
import configuration.ConfigurationFileBaseReader;
public class Trace_SRS_MF extends MestraSRS {
private MestraMF mestraMF = null;
public Trace_SRS_MF(MestraSRS mestraSRS, MestraMF aMestraMF, ConfigurationFileBaseReader configuration) {
super(mestraSRS, configuration);
if (aMestraMF == null) {
this.mestraMF = null;
}
else {
this.mestraMF = (MestraMF)aMestraMF.clone();
}
}
public Trace_SRS_MF getThis() {
return this;
}
/**
* @return the mestraSDD
*/
public MestraMF getMestraMF() {
return this.mestraMF;
}
public void setMestraMF(MestraMF aMestraMF) {
this.mestraMF = aMestraMF;
}
public String getMFIdentifier() {
if (this.mestraMF == null) {
return "";
}
else {
return this.mestraMF.getIdentifier();
}
}
}
| 856 | 0.641355 | 0.641355 | 45 | 18.022223 | 21.594742 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.955556 | false | false | 1 |
c048edf01b83ba844d7687915ae619396f0cb5c1 | 19,241,453,528,108 | d7d58b0331ba4adf0ca32530c5a1ee0ad78e0b79 | /app/src/main/java/com/example/firstprogram/generic/GenericTest.java | 735210a66b8f338b770121b44313e408767d5066 | [] | no_license | elliottacquaire/FirstProgram | https://github.com/elliottacquaire/FirstProgram | 9bc11487456b86d8d681cf04f4373dbd262e3673 | b92599c2654f6996ba7713abd0b418b37c607221 | refs/heads/master | 2021-06-12T00:14:59.831000 | 2021-02-23T03:18:03 | 2021-02-23T03:18:03 | 101,954,062 | 2 | 0 | null | false | 2017-08-31T03:40:58 | 2017-08-31T03:16:02 | 2017-08-31T03:37:10 | 2017-08-31T03:40:57 | 0 | 1 | 0 | 0 | null | null | null | package com.example.firstprogram.generic;
import java.util.ArrayList;
import java.util.List;
/**
* 泛型接口、泛型类和泛型方法
*
* 类型通配符上限通过形如Box<? extends Number>形式定义,相对应的,
* 类型通配符下限为Box<? super Number>形式,其含义与类型通配符上限正好相反
*
*
* 无论何时,如果你能做到,你就该尽量使用泛型方法。也就是说,如果使用泛型方法将整个类泛型化,
* 那么就应该使用泛型方法。另外对于一个static的方法而已,无法访问泛型类型的参数。
* 所以如果static方法要使用泛型能力,就必须使其成为泛型方法。
*
*/
public class GenericTest {
public static void main(String[] args) {
Box<String> name = new Box<String>("corn");
try {
Object obj = genericMethod(Class.forName("com.test.test"));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//不能创建一个确切的泛型类型的数组
// List<String>[] ls = new ArrayList<String>[10];
//使用通配符创建泛型数组是可以的
List<?>[] ls1 = new ArrayList<?>[10];
List<String>[] ls11 = new ArrayList[10];
}
/**
* 泛型方法的基本介绍
* @param tClass 传入的泛型实参
* @return T 返回值为T类型
* 说明:
* 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
* 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。
* 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。
* 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。
*/
public static <T> T genericMethod(Class<T> tClass)throws InstantiationException ,
IllegalAccessException{
T instance = tClass.newInstance();
return instance;
}
//静态方法有一种情况需要注意一下,那就是在类中的静态方法使用泛型:
// 静态方法无法访问类上定义的泛型;如果静态方法操作的引用数据类型不确定的时候,必须要将泛型定义在方法上。
//即:如果静态方法要使用泛型的话,必须将静态方法也定义成泛型方法 。
/**
* 如果在类中定义使用泛型的静态方法,需要添加额外的泛型声明(将这个方法定义成泛型方法)
* 即使静态方法要使用泛型类中已经声明过的泛型也不可以。
* 如:public static void show(T t){..},此时编译器会提示错误信息:
"StaticGenerator cannot be refrenced from static context"
*/
public static <T> void show(T t){
}
//在泛型方法中添加上下边界限制的时候,必须在权限声明与返回值之间的<T>上添加上下边界,即在泛型声明的时候添加
//public <T> T showKeyName(Generic<T extends Number> container),编译器会报错:"Unexpected bound"
public <T extends Number> T showKeyName(Box<T> container){
System.out.println("container key :" + container.getData());
T test = container.getData();
return test;
}
}
//泛型类
class Box<T> {
private T data;
public Box() {
}
public Box(T data) {
this.data = data;
}
//我想说的其实是这个,虽然在方法中使用了泛型,但是这并不是一个泛型方法。
//这只是类中一个普通的成员方法,只不过他的返回值是在声明泛型类已经声明过的泛型。
//所以在这个方法中才可以继续使用 T 这个泛型。
public T getData() {
return data;
}
} | UTF-8 | Java | 4,035 | java | GenericTest.java | Java | [] | null | [] | package com.example.firstprogram.generic;
import java.util.ArrayList;
import java.util.List;
/**
* 泛型接口、泛型类和泛型方法
*
* 类型通配符上限通过形如Box<? extends Number>形式定义,相对应的,
* 类型通配符下限为Box<? super Number>形式,其含义与类型通配符上限正好相反
*
*
* 无论何时,如果你能做到,你就该尽量使用泛型方法。也就是说,如果使用泛型方法将整个类泛型化,
* 那么就应该使用泛型方法。另外对于一个static的方法而已,无法访问泛型类型的参数。
* 所以如果static方法要使用泛型能力,就必须使其成为泛型方法。
*
*/
public class GenericTest {
public static void main(String[] args) {
Box<String> name = new Box<String>("corn");
try {
Object obj = genericMethod(Class.forName("com.test.test"));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//不能创建一个确切的泛型类型的数组
// List<String>[] ls = new ArrayList<String>[10];
//使用通配符创建泛型数组是可以的
List<?>[] ls1 = new ArrayList<?>[10];
List<String>[] ls11 = new ArrayList[10];
}
/**
* 泛型方法的基本介绍
* @param tClass 传入的泛型实参
* @return T 返回值为T类型
* 说明:
* 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
* 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。
* 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。
* 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。
*/
public static <T> T genericMethod(Class<T> tClass)throws InstantiationException ,
IllegalAccessException{
T instance = tClass.newInstance();
return instance;
}
//静态方法有一种情况需要注意一下,那就是在类中的静态方法使用泛型:
// 静态方法无法访问类上定义的泛型;如果静态方法操作的引用数据类型不确定的时候,必须要将泛型定义在方法上。
//即:如果静态方法要使用泛型的话,必须将静态方法也定义成泛型方法 。
/**
* 如果在类中定义使用泛型的静态方法,需要添加额外的泛型声明(将这个方法定义成泛型方法)
* 即使静态方法要使用泛型类中已经声明过的泛型也不可以。
* 如:public static void show(T t){..},此时编译器会提示错误信息:
"StaticGenerator cannot be refrenced from static context"
*/
public static <T> void show(T t){
}
//在泛型方法中添加上下边界限制的时候,必须在权限声明与返回值之间的<T>上添加上下边界,即在泛型声明的时候添加
//public <T> T showKeyName(Generic<T extends Number> container),编译器会报错:"Unexpected bound"
public <T extends Number> T showKeyName(Box<T> container){
System.out.println("container key :" + container.getData());
T test = container.getData();
return test;
}
}
//泛型类
class Box<T> {
private T data;
public Box() {
}
public Box(T data) {
this.data = data;
}
//我想说的其实是这个,虽然在方法中使用了泛型,但是这并不是一个泛型方法。
//这只是类中一个普通的成员方法,只不过他的返回值是在声明泛型类已经声明过的泛型。
//所以在这个方法中才可以继续使用 T 这个泛型。
public T getData() {
return data;
}
} | 4,035 | 0.636504 | 0.631498 | 97 | 25.783504 | 22.556791 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.216495 | false | false | 1 |
52a90b9253c34b9a64fa8d7faa5c6eb2894883d5 | 3,779,571,222,326 | 3a6bfa6784136e187bc6bfc12c08a012553e4882 | /app/src/main/java/com/yessumtorah/boilerapp/User.java | 6ba8104ff3c0885af3503bbb7b73aa18da69178a | [] | no_license | GuyG-Saha/Boile21 | https://github.com/GuyG-Saha/Boile21 | ec4969713dfd4d130d442d813bed15c578e4a76c | 6c8a5f18481877106730f847f9a0584fb866029d | refs/heads/master | 2022-03-27T02:13:47.369000 | 2020-01-10T18:24:11 | 2020-01-10T18:24:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yessumtorah.boilerapp;
public class User {
}
| UTF-8 | Java | 58 | java | User.java | Java | [] | null | [] | package com.yessumtorah.boilerapp;
public class User {
}
| 58 | 0.775862 | 0.775862 | 4 | 13.5 | 14.044572 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
355b1b4ef62bdecaee5c5ec153f3c8fd79b1050a | 3,779,571,221,806 | c946ba32da44ea56470c0b70c9b4265eb12741d4 | /app/src/main/java/com/successpoint/wingo/view/LiveData/tests/PublishABRTest/PublishABRTest.java | 0f59f15d11b2bc91016027b498f9968ccdb9a23c | [] | no_license | khaledeltarabily/WingoAppAndroid | https://github.com/khaledeltarabily/WingoAppAndroid | 55796ba7e07c6590154604517a31418b0e2f29e3 | 51618b8dcdef397726e3771d50f7b07ec920c1f3 | refs/heads/master | 2020-08-12T17:47:59.708000 | 2019-10-13T12:04:03 | 2019-10-13T12:04:03 | 214,812,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// Copyright © 2015 Infrared5, Inc. All rights reserved.
//
// The accompanying code comprising examples for use solely in conjunction with Red5 Pro (the "Example Code")
// is licensed to you by Infrared5 Inc. in consideration of your agreement to the following
// license terms and conditions. Access, use, modification, or redistribution of the accompanying
// code constitutes your acceptance of the following license terms and conditions.
//
// Permission is hereby granted, free of charge, to you to use the Example Code and associated documentation
// files (collectively, the "Software") without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The Software shall be used solely in conjunction with Red5 Pro. Red5 Pro is licensed under a separate end
// user license agreement (the "EULA"), which must be executed with Infrared5, Inc.
// An example of the EULA can be found on our website at: https://account.red5pro.com/assets/LICENSE.txt.
//
// The above copyright notice and this license shall be included in all copies or portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL INFRARED5, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
package com.successpoint.wingo.view.LiveData.tests.PublishABRTest;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.event.R5ConnectionEvent;
import com.red5pro.streaming.source.R5AdaptiveBitrateController;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
import com.red5pro.streaming.view.R5VideoView;
import com.successpoint.wingo.R;
import com.successpoint.wingo.view.LiveData.tests.PublishTest.PublishTest;
import com.successpoint.wingo.view.showLiveView.TestContent;
/**
* Created by davidHeimann on 2/10/16.
*/
public class PublishABRTest extends PublishTest {
protected R5AdaptiveBitrateController adaptor;
@Override
public void onConnectionEvent(R5ConnectionEvent event) {
super.onConnectionEvent(event);
if (event.name() == R5ConnectionEvent.ABR_LEVEL_CHANGED.name()) {
int level = adaptor.getBitRateLevel();
if (level >= 0) {
int bitrate = adaptor.getBitrateLevelValues()[level];
Log.d("Publisher", "ABR Level Change: level(" + level + "), bitrate(" + bitrate + ")");
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.publish_test, container, false);
//Create the configuration from the values.xml
R5Configuration config = new R5Configuration(R5StreamProtocol.RTSP,
TestContent.GetPropertyString("host"),
TestContent.GetPropertyInt("port"),
TestContent.GetPropertyString("context"),
TestContent.GetPropertyFloat("publish_buffer_time"));
config.setLicenseKey(TestContent.GetPropertyString("license_key"));
config.setBundleID(getActivity().getPackageName());
R5Connection connection = new R5Connection(config);
//setup a new stream using the connection
publish = new R5Stream(connection);
publish.audioController.sampleRate = TestContent.GetPropertyInt("sample_rate");
publish.setListener(this);
//show all logging
publish.setLogLevel(R5Stream.LOG_LEVEL_DEBUG);
R5Camera camera = null;
if(TestContent.GetPropertyBool("video_on")) {
//attach a camera video source
cam = openFrontFacingCameraGingerbread();
cam.setDisplayOrientation((camOrientation + 180) % 360);
camera = new R5Camera(cam, TestContent.GetPropertyInt("camera_width"), TestContent.GetPropertyInt("camera_height"));
camera.setBitrate(TestContent.GetPropertyInt("bitrate"));
camera.setOrientation(camOrientation);
}
if(TestContent.GetPropertyBool("audio_on")) {
//attach a microphone
R5Microphone mic = new R5Microphone();
publish.attachMic(mic);
}
preview = (R5VideoView)rootView.findViewById(R.id.videoPreview);
preview.attachStream(publish);
if(TestContent.GetPropertyBool("video_on"))
publish.attachCamera(camera);
preview.showDebugView(TestContent.GetPropertyBool("debug_view"));
adaptor = new R5AdaptiveBitrateController();
adaptor.AttachStream(publish);
adaptor.requiresVideo = false;
publish.publish(TestContent.GetPropertyString("stream1"), getPublishRecordType());
if(TestContent.GetPropertyBool("video_on"))
cam.startPreview();
return rootView;
}
}
| UTF-8 | Java | 5,664 | java | PublishABRTest.java | Java | [
{
"context": ".view.showLiveView.TestContent;\n\n/**\n * Created by davidHeimann on 2/10/16.\n */\npublic class PublishABRTest exten",
"end": 2672,
"score": 0.995522677898407,
"start": 2660,
"tag": "USERNAME",
"value": "davidHeimann"
}
] | null | [] | //
// Copyright © 2015 Infrared5, Inc. All rights reserved.
//
// The accompanying code comprising examples for use solely in conjunction with Red5 Pro (the "Example Code")
// is licensed to you by Infrared5 Inc. in consideration of your agreement to the following
// license terms and conditions. Access, use, modification, or redistribution of the accompanying
// code constitutes your acceptance of the following license terms and conditions.
//
// Permission is hereby granted, free of charge, to you to use the Example Code and associated documentation
// files (collectively, the "Software") without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The Software shall be used solely in conjunction with Red5 Pro. Red5 Pro is licensed under a separate end
// user license agreement (the "EULA"), which must be executed with Infrared5, Inc.
// An example of the EULA can be found on our website at: https://account.red5pro.com/assets/LICENSE.txt.
//
// The above copyright notice and this license shall be included in all copies or portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL INFRARED5, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
package com.successpoint.wingo.view.LiveData.tests.PublishABRTest;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.event.R5ConnectionEvent;
import com.red5pro.streaming.source.R5AdaptiveBitrateController;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
import com.red5pro.streaming.view.R5VideoView;
import com.successpoint.wingo.R;
import com.successpoint.wingo.view.LiveData.tests.PublishTest.PublishTest;
import com.successpoint.wingo.view.showLiveView.TestContent;
/**
* Created by davidHeimann on 2/10/16.
*/
public class PublishABRTest extends PublishTest {
protected R5AdaptiveBitrateController adaptor;
@Override
public void onConnectionEvent(R5ConnectionEvent event) {
super.onConnectionEvent(event);
if (event.name() == R5ConnectionEvent.ABR_LEVEL_CHANGED.name()) {
int level = adaptor.getBitRateLevel();
if (level >= 0) {
int bitrate = adaptor.getBitrateLevelValues()[level];
Log.d("Publisher", "ABR Level Change: level(" + level + "), bitrate(" + bitrate + ")");
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.publish_test, container, false);
//Create the configuration from the values.xml
R5Configuration config = new R5Configuration(R5StreamProtocol.RTSP,
TestContent.GetPropertyString("host"),
TestContent.GetPropertyInt("port"),
TestContent.GetPropertyString("context"),
TestContent.GetPropertyFloat("publish_buffer_time"));
config.setLicenseKey(TestContent.GetPropertyString("license_key"));
config.setBundleID(getActivity().getPackageName());
R5Connection connection = new R5Connection(config);
//setup a new stream using the connection
publish = new R5Stream(connection);
publish.audioController.sampleRate = TestContent.GetPropertyInt("sample_rate");
publish.setListener(this);
//show all logging
publish.setLogLevel(R5Stream.LOG_LEVEL_DEBUG);
R5Camera camera = null;
if(TestContent.GetPropertyBool("video_on")) {
//attach a camera video source
cam = openFrontFacingCameraGingerbread();
cam.setDisplayOrientation((camOrientation + 180) % 360);
camera = new R5Camera(cam, TestContent.GetPropertyInt("camera_width"), TestContent.GetPropertyInt("camera_height"));
camera.setBitrate(TestContent.GetPropertyInt("bitrate"));
camera.setOrientation(camOrientation);
}
if(TestContent.GetPropertyBool("audio_on")) {
//attach a microphone
R5Microphone mic = new R5Microphone();
publish.attachMic(mic);
}
preview = (R5VideoView)rootView.findViewById(R.id.videoPreview);
preview.attachStream(publish);
if(TestContent.GetPropertyBool("video_on"))
publish.attachCamera(camera);
preview.showDebugView(TestContent.GetPropertyBool("debug_view"));
adaptor = new R5AdaptiveBitrateController();
adaptor.AttachStream(publish);
adaptor.requiresVideo = false;
publish.publish(TestContent.GetPropertyString("stream1"), getPublishRecordType());
if(TestContent.GetPropertyBool("video_on"))
cam.startPreview();
return rootView;
}
}
| 5,664 | 0.708105 | 0.697687 | 129 | 42.899223 | 35.76622 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.713178 | false | false | 1 |
a85cddec7ecffdb2ff59a8d41880e9b20ae848c5 | 2,456,721,343,044 | d0d266c3ca36432818d82453c09d03625f96fc1f | /src/cn/com/ite/hnjtamis/query/employeeQuery/EmployeeThemeBankForm.java | 1f1873ddd48c380e423cced5454299021e60b758 | [] | no_license | Williamwuyi/hnjtamis | https://github.com/Williamwuyi/hnjtamis | acd51158fe43d1109721124c8340e032dd99a51f | f35de9bf1289d6193cf5a29a5ec9b6d000b84040 | refs/heads/master | 2020-08-08T09:27:36.667000 | 2019-10-09T03:19:27 | 2019-10-09T03:19:27 | 213,804,269 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.com.ite.hnjtamis.query.employeeQuery;
public class EmployeeThemeBankForm {
private String deptId;
private String deptName;
private String employeeId;
private String employeeName;
private String employeeCode;
private String themeBankId;
private String themeBankName;
private Integer themeNum;
private Integer themeFinNum;
private Integer themebanknum;
private Integer xxthemebanknum;
private Integer wxxthemebanknum;//未学习
private Integer yxxthemebanknum;//已学习
private Integer yxwthemebanknum;//已学完
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
public String getThemeBankId() {
return themeBankId;
}
public void setThemeBankId(String themeBankId) {
this.themeBankId = themeBankId;
}
public String getThemeBankName() {
return themeBankName;
}
public void setThemeBankName(String themeBankName) {
this.themeBankName = themeBankName;
}
public Integer getThemeNum() {
return themeNum;
}
public void setThemeNum(Integer themeNum) {
this.themeNum = themeNum;
}
public Integer getThemeFinNum() {
return themeFinNum;
}
public void setThemeFinNum(Integer themeFinNum) {
this.themeFinNum = themeFinNum;
}
public Integer getThemebanknum() {
return themebanknum;
}
public void setThemebanknum(Integer themebanknum) {
this.themebanknum = themebanknum;
}
public Integer getXxthemebanknum() {
return xxthemebanknum;
}
public void setXxthemebanknum(Integer xxthemebanknum) {
this.xxthemebanknum = xxthemebanknum;
}
public Integer getWxxthemebanknum() {
return wxxthemebanknum;
}
public void setWxxthemebanknum(Integer wxxthemebanknum) {
this.wxxthemebanknum = wxxthemebanknum;
}
public Integer getYxxthemebanknum() {
return yxxthemebanknum;
}
public void setYxxthemebanknum(Integer yxxthemebanknum) {
this.yxxthemebanknum = yxxthemebanknum;
}
public Integer getYxwthemebanknum() {
return yxwthemebanknum;
}
public void setYxwthemebanknum(Integer yxwthemebanknum) {
this.yxwthemebanknum = yxwthemebanknum;
}
}
| UTF-8 | Java | 2,667 | java | EmployeeThemeBankForm.java | Java | [] | null | [] | package cn.com.ite.hnjtamis.query.employeeQuery;
public class EmployeeThemeBankForm {
private String deptId;
private String deptName;
private String employeeId;
private String employeeName;
private String employeeCode;
private String themeBankId;
private String themeBankName;
private Integer themeNum;
private Integer themeFinNum;
private Integer themebanknum;
private Integer xxthemebanknum;
private Integer wxxthemebanknum;//未学习
private Integer yxxthemebanknum;//已学习
private Integer yxwthemebanknum;//已学完
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
public String getThemeBankId() {
return themeBankId;
}
public void setThemeBankId(String themeBankId) {
this.themeBankId = themeBankId;
}
public String getThemeBankName() {
return themeBankName;
}
public void setThemeBankName(String themeBankName) {
this.themeBankName = themeBankName;
}
public Integer getThemeNum() {
return themeNum;
}
public void setThemeNum(Integer themeNum) {
this.themeNum = themeNum;
}
public Integer getThemeFinNum() {
return themeFinNum;
}
public void setThemeFinNum(Integer themeFinNum) {
this.themeFinNum = themeFinNum;
}
public Integer getThemebanknum() {
return themebanknum;
}
public void setThemebanknum(Integer themebanknum) {
this.themebanknum = themebanknum;
}
public Integer getXxthemebanknum() {
return xxthemebanknum;
}
public void setXxthemebanknum(Integer xxthemebanknum) {
this.xxthemebanknum = xxthemebanknum;
}
public Integer getWxxthemebanknum() {
return wxxthemebanknum;
}
public void setWxxthemebanknum(Integer wxxthemebanknum) {
this.wxxthemebanknum = wxxthemebanknum;
}
public Integer getYxxthemebanknum() {
return yxxthemebanknum;
}
public void setYxxthemebanknum(Integer yxxthemebanknum) {
this.yxxthemebanknum = yxxthemebanknum;
}
public Integer getYxwthemebanknum() {
return yxwthemebanknum;
}
public void setYxwthemebanknum(Integer yxwthemebanknum) {
this.yxwthemebanknum = yxwthemebanknum;
}
}
| 2,667 | 0.768214 | 0.768214 | 110 | 23.081818 | 17.64299 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.590909 | false | false | 1 |
d806ff6c81b5a09bbd0ce63f4fdace45d1d51c14 | 14,611,478,789,133 | 104ad105ce283563103a8ac098a148999d28cfdc | /health_interface/src/main/java/com/itheima/interfaces/PerService.java | e4e7d2117437f74651b8df79b0eb4f22c153eb46 | [] | no_license | a18574392661/health_parent | https://github.com/a18574392661/health_parent | c1b14dc565178386f473b12d4f32cd4ef90e05aa | 4e760a8c2f9c214b14619a77f22410bc5b1ae265 | refs/heads/master | 2022-07-10T06:48:54.942000 | 2020-03-13T13:41:28 | 2020-03-13T13:42:47 | 247,068,636 | 0 | 0 | null | false | 2021-01-14T20:37:16 | 2020-03-13T12:41:22 | 2020-03-13T13:44:21 | 2021-01-14T20:37:14 | 14,583 | 0 | 0 | 2 | JavaScript | false | false | package com.itheima.interfaces;
import java.util.List;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
public interface PerService {
List<Permission> queryRolePers(List<Role> listRoles);
PageResult perAll(QueryPageBean queryPageBean);
void perDel(String id);
void perAdd(Permission permission);
void perEdit(Permission permission);
Permission perByid(String id);
}
| UTF-8 | Java | 478 | java | PerService.java | Java | [] | null | [] | package com.itheima.interfaces;
import java.util.List;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
public interface PerService {
List<Permission> queryRolePers(List<Role> listRoles);
PageResult perAll(QueryPageBean queryPageBean);
void perDel(String id);
void perAdd(Permission permission);
void perEdit(Permission permission);
Permission perByid(String id);
}
| 478 | 0.797071 | 0.797071 | 24 | 18.916666 | 18.434381 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 1 |
ac46c4a9159c74bd551b8b0215986a65e1d1c0b9 | 35,794,257,462,152 | 5dea5ca1e725a09c46f3f128a54e97b4353f7c9e | /src/test/com/rhb/sas/interfaces/downloadreport/sina/DownloadYjygFromEastmoneyTest.java | 3dc9b6e120f49c95a8bd7918c8caec657ee71a0b | [] | no_license | dofoyo/sas | https://github.com/dofoyo/sas | 9c20f3df50ceec5e310aca700cf7f94f1ff46fac | e20683c7af6f6fe7df808d84a520f166b99275e9 | refs/heads/master | 2021-06-18T10:41:55.819000 | 2017-06-22T06:17:06 | 2017-06-22T06:17:06 | 13,361,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test.com.rhb.sas.interfaces.downloadreport.sina;
import org.junit.BeforeClass;
import org.junit.Test;
import com.rhb.af.business.FindBusiness;
import com.rhb.af.util.AppContext;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadReportDateFromEastmoney;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadReportDateFromEastmoneyOneByOne;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadYjygFromEastmoney;
import com.rhb.sas.report.business.ReportBusiness;
public class DownloadYjygFromEastmoneyTest {
static String appContextPath = "com/rhb/sas/AppContext.xml";
static ReportBusiness rb;
static FindBusiness fb;
@BeforeClass
public static void initial() {
rb = (ReportBusiness) AppContext.getInstance().getAppContext(appContextPath).getBean("reportService");
fb = (FindBusiness) AppContext.getInstance().getAppContext(appContextPath).getBean("findService");
}
@Test
public void test1(){
DownloadYjygFromEastmoney d = new DownloadYjygFromEastmoney();
d.setFb(fb);
d.setRb(rb);
d.doIt();
}
}
| UTF-8 | Java | 1,057 | java | DownloadYjygFromEastmoneyTest.java | Java | [] | null | [] | package test.com.rhb.sas.interfaces.downloadreport.sina;
import org.junit.BeforeClass;
import org.junit.Test;
import com.rhb.af.business.FindBusiness;
import com.rhb.af.util.AppContext;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadReportDateFromEastmoney;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadReportDateFromEastmoneyOneByOne;
import com.rhb.sas.interfaces.downloadreport.sina.DownloadYjygFromEastmoney;
import com.rhb.sas.report.business.ReportBusiness;
public class DownloadYjygFromEastmoneyTest {
static String appContextPath = "com/rhb/sas/AppContext.xml";
static ReportBusiness rb;
static FindBusiness fb;
@BeforeClass
public static void initial() {
rb = (ReportBusiness) AppContext.getInstance().getAppContext(appContextPath).getBean("reportService");
fb = (FindBusiness) AppContext.getInstance().getAppContext(appContextPath).getBean("findService");
}
@Test
public void test1(){
DownloadYjygFromEastmoney d = new DownloadYjygFromEastmoney();
d.setFb(fb);
d.setRb(rb);
d.doIt();
}
}
| 1,057 | 0.796594 | 0.795648 | 35 | 29.200001 | 31.364948 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.257143 | false | false | 1 |
bc37738f83e8a22cb06af3f3d547544799eb6ac7 | 32,804,960,268,088 | 55d9237e860e2a5d61eae4764319007d3488b4f3 | /src/main/java/fi/riista/feature/harvestpermit/report/HarvestReportFeature.java | 76d316c0e5974c381d68d94b9196682322956a73 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nghib/oma-riista-web | https://github.com/nghib/oma-riista-web | 2c61ecd365a3323791e31de1c204600cd7be8c03 | 18c8da542f1a0846339a0d93864dfbe5524e10ca | refs/heads/master | 2018-02-07T15:22:47.474000 | 2017-03-03T12:44:54 | 2017-03-03T13:04:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fi.riista.feature.harvestpermit.report;
import fi.riista.feature.account.user.ActiveUserService;
import fi.riista.feature.gamediary.GameSpecies_;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFields;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFieldsDTO;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFieldsRepository;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFields_;
import fi.riista.feature.harvestpermit.season.HarvestAreaDTO;
import fi.riista.feature.harvestpermit.season.HarvestQuota;
import fi.riista.feature.harvestpermit.season.HarvestQuotaRepository;
import fi.riista.feature.harvestpermit.season.HarvestSeason;
import fi.riista.feature.harvestpermit.season.HarvestSeasonDTO;
import fi.riista.feature.harvestpermit.season.HarvestSeasonRepository;
import fi.riista.feature.harvestpermit.season.HarvestSeason_;
import fi.riista.util.F;
import fi.riista.util.jpa.JpaSpecs;
import org.joda.time.LocalDate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.List;
import static fi.riista.util.jpa.JpaSpecs.and;
import static fi.riista.util.jpa.JpaSpecs.isNotNull;
import static fi.riista.util.jpa.JpaSpecs.or;
import static org.springframework.data.jpa.domain.Specifications.where;
@Component
public class HarvestReportFeature {
@Resource
private HarvestSeasonRepository harvestSeasonRepository;
@Resource
private HarvestReportFieldsRepository harvestReportFieldsRepository;
@Resource
private ActiveUserService activeUserService;
@Resource
private HarvestQuotaRepository harvestQuotaRepository;
@Transactional(readOnly = true)
public List<HarvestSeasonDTO> listReportableHuntingSeasons(
@Nullable LocalDate date, @Nullable Integer gameSpeciesCode) {
return F.mapNonNullsToList(getHarvestSeasons(date, gameSpeciesCode), HarvestSeasonDTO::create);
}
private List<HarvestSeason> getHarvestSeasons(
@Nullable final LocalDate date, @Nullable final Integer speciesCode) {
final Specification<HarvestSeason> withSpeciesCode = speciesCode == null
? JpaSpecs.conjunction()
: JpaSpecs.equal(
HarvestSeason_.fields, HarvestReportFields_.species, GameSpecies_.officialCode, speciesCode);
if (date == null) {
return harvestSeasonRepository.findAll(withSpeciesCode);
}
final Specification<HarvestSeason> interval1 =
JpaSpecs.withinInterval(HarvestSeason_.beginDate, HarvestSeason_.endOfReportingDate, date);
final Specification<HarvestSeason> interval2 =
JpaSpecs.withinInterval(HarvestSeason_.beginDate2, HarvestSeason_.endOfReportingDate2, date);
return harvestSeasonRepository.findAll(where(withSpeciesCode).and(or(
interval1, and(isNotNull(HarvestSeason_.beginDate2), interval2))));
}
@Transactional(readOnly = true)
public List<HarvestReportFieldsDTO> listReportableWithPermits(
@Nullable LocalDate date, @Nullable Integer gameSpeciesCode) {
return F.mapNonNullsToList(getHarvestReportFieldses(date, gameSpeciesCode), HarvestReportFieldsDTO::create);
}
private List<HarvestReportFields> getHarvestReportFieldses(
@Nullable final LocalDate date, @Nullable final Integer gameSpeciesCode) {
final Specification<HarvestReportFields> withSpeciesCode = gameSpeciesCode == null
? JpaSpecs.conjunction()
: JpaSpecs.equal(HarvestReportFields_.species, GameSpecies_.officialCode, gameSpeciesCode);
Specifications<HarvestReportFields> spec =
where(JpaSpecs.equal(HarvestReportFields_.usedWithPermit, true))
.and(withSpeciesCode);
if (date != null) {
spec = spec.and(
JpaSpecs.withinInterval(HarvestReportFields_.beginDate, HarvestReportFields_.endDate, date));
}
return harvestReportFieldsRepository.findAll(spec);
}
@Transactional(readOnly = true)
public HarvestAreaDTO findHarvestArea(long rhyId, long harvestSeasonId) {
final HarvestQuota quota = harvestQuotaRepository.findByHarvestSeasonAndRhy(harvestSeasonId, rhyId);
return quota == null ? null : HarvestAreaDTO.create(quota.getHarvestArea());
}
}
| UTF-8 | Java | 4,637 | java | HarvestReportFeature.java | Java | [] | null | [] | package fi.riista.feature.harvestpermit.report;
import fi.riista.feature.account.user.ActiveUserService;
import fi.riista.feature.gamediary.GameSpecies_;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFields;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFieldsDTO;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFieldsRepository;
import fi.riista.feature.harvestpermit.report.fields.HarvestReportFields_;
import fi.riista.feature.harvestpermit.season.HarvestAreaDTO;
import fi.riista.feature.harvestpermit.season.HarvestQuota;
import fi.riista.feature.harvestpermit.season.HarvestQuotaRepository;
import fi.riista.feature.harvestpermit.season.HarvestSeason;
import fi.riista.feature.harvestpermit.season.HarvestSeasonDTO;
import fi.riista.feature.harvestpermit.season.HarvestSeasonRepository;
import fi.riista.feature.harvestpermit.season.HarvestSeason_;
import fi.riista.util.F;
import fi.riista.util.jpa.JpaSpecs;
import org.joda.time.LocalDate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.List;
import static fi.riista.util.jpa.JpaSpecs.and;
import static fi.riista.util.jpa.JpaSpecs.isNotNull;
import static fi.riista.util.jpa.JpaSpecs.or;
import static org.springframework.data.jpa.domain.Specifications.where;
@Component
public class HarvestReportFeature {
@Resource
private HarvestSeasonRepository harvestSeasonRepository;
@Resource
private HarvestReportFieldsRepository harvestReportFieldsRepository;
@Resource
private ActiveUserService activeUserService;
@Resource
private HarvestQuotaRepository harvestQuotaRepository;
@Transactional(readOnly = true)
public List<HarvestSeasonDTO> listReportableHuntingSeasons(
@Nullable LocalDate date, @Nullable Integer gameSpeciesCode) {
return F.mapNonNullsToList(getHarvestSeasons(date, gameSpeciesCode), HarvestSeasonDTO::create);
}
private List<HarvestSeason> getHarvestSeasons(
@Nullable final LocalDate date, @Nullable final Integer speciesCode) {
final Specification<HarvestSeason> withSpeciesCode = speciesCode == null
? JpaSpecs.conjunction()
: JpaSpecs.equal(
HarvestSeason_.fields, HarvestReportFields_.species, GameSpecies_.officialCode, speciesCode);
if (date == null) {
return harvestSeasonRepository.findAll(withSpeciesCode);
}
final Specification<HarvestSeason> interval1 =
JpaSpecs.withinInterval(HarvestSeason_.beginDate, HarvestSeason_.endOfReportingDate, date);
final Specification<HarvestSeason> interval2 =
JpaSpecs.withinInterval(HarvestSeason_.beginDate2, HarvestSeason_.endOfReportingDate2, date);
return harvestSeasonRepository.findAll(where(withSpeciesCode).and(or(
interval1, and(isNotNull(HarvestSeason_.beginDate2), interval2))));
}
@Transactional(readOnly = true)
public List<HarvestReportFieldsDTO> listReportableWithPermits(
@Nullable LocalDate date, @Nullable Integer gameSpeciesCode) {
return F.mapNonNullsToList(getHarvestReportFieldses(date, gameSpeciesCode), HarvestReportFieldsDTO::create);
}
private List<HarvestReportFields> getHarvestReportFieldses(
@Nullable final LocalDate date, @Nullable final Integer gameSpeciesCode) {
final Specification<HarvestReportFields> withSpeciesCode = gameSpeciesCode == null
? JpaSpecs.conjunction()
: JpaSpecs.equal(HarvestReportFields_.species, GameSpecies_.officialCode, gameSpeciesCode);
Specifications<HarvestReportFields> spec =
where(JpaSpecs.equal(HarvestReportFields_.usedWithPermit, true))
.and(withSpeciesCode);
if (date != null) {
spec = spec.and(
JpaSpecs.withinInterval(HarvestReportFields_.beginDate, HarvestReportFields_.endDate, date));
}
return harvestReportFieldsRepository.findAll(spec);
}
@Transactional(readOnly = true)
public HarvestAreaDTO findHarvestArea(long rhyId, long harvestSeasonId) {
final HarvestQuota quota = harvestQuotaRepository.findByHarvestSeasonAndRhy(harvestSeasonId, rhyId);
return quota == null ? null : HarvestAreaDTO.create(quota.getHarvestArea());
}
}
| 4,637 | 0.757171 | 0.755661 | 107 | 42.336449 | 34.184475 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64486 | false | false | 1 |
f0f2f0ffe97a9247fd4fae9e5fd51a438fe36f86 | 34,608,846,486,248 | b0e34c0aac358800a229b1a95c50e9bccf35c528 | /20190808/U1M1L3Katas/src/main/java/com/company/AgeAgain.java | 46bc60b7b03b0f3b96106799cca4125eeabc678a | [] | no_license | dominickdechristofaro/Dominick_DeChristofaro_JavaS1 | https://github.com/dominickdechristofaro/Dominick_DeChristofaro_JavaS1 | 2277d0dda9a2dcb8f0a9a73c9b6184788fc9c75b | 513bc69255942e1990b841176ab85f949b7b9b65 | refs/heads/master | 2020-06-30T03:10:25.411000 | 2019-10-16T16:30:44 | 2019-10-16T16:30:44 | 200,704,157 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**********************************************************************************************************************
* Name: Dominick DeChristofaro
* Date: 08/08/2019
* Description: Asks for the user's age and displays a series of questions based on the value.
*********************************************************************************************************************/
package com.company;
import java.util.Scanner;
public class AgeAgain {
public static void main(String[] args) {
// Variables
int age = 0;
String grade = " ";
String goingToCollege = " ";
String college = " ";
String afterHighSchool = " ";
String job = " ";
// Create a Scanner object for user input
Scanner scan = new Scanner(System.in);
// Prompt the user for their age
System.out.println("Please enter your age as an integer value.");
age = Integer.parseInt(scan.nextLine());
// If age is less than 14
if(age < 14) {
// Prompt the user for the grade they are in
System.out.println("Please enter your grade as an integer value.");
grade = scan.nextLine();
System.out.println("Wow! " + grade + " grade - that sounds exciting!");
}
// If age is between 14 and 18 inclusive
else if(age >= 14 && age <= 18) {
// Ask the user if they are going to college
System.out.println("Are you planning to go to college? (yes/no)");
goingToCollege = scan.nextLine();
// If the user is going to college, ask what college.
if(goingToCollege.equals("yes")) {
System.out.println("What college are you planning to attend?");
college = scan.nextLine();
System.out.println(college + " is a great school!");
}
// If the user is not going to college, as what they would like to do after high school
else if(goingToCollege.equals("no")) {
System.out.println("What would you like to do after High School?");
afterHighSchool = scan.nextLine();
System.out.println("Wow, " + afterHighSchool + " sounds like a plan!");
}
// If input is incorrect
else {
System.out.println("Invalid Input");
}
}
// If age is greater than 18
else if(age > 18) {
// Ask the user what their job is
System.out.println("What is your job?");
job = scan.nextLine();
System.out.println(job + " sounds like a great job!");
}
}
}
| UTF-8 | Java | 2,721 | java | AgeAgain.java | Java | [
{
"context": "******************************\n * Name: Dominick DeChristofaro\n * Date: 08/08/2019\n * Description: ",
"end": 162,
"score": 0.9998477101325989,
"start": 140,
"tag": "NAME",
"value": "Dominick DeChristofaro"
}
] | null | [] | /**********************************************************************************************************************
* Name: <NAME>
* Date: 08/08/2019
* Description: Asks for the user's age and displays a series of questions based on the value.
*********************************************************************************************************************/
package com.company;
import java.util.Scanner;
public class AgeAgain {
public static void main(String[] args) {
// Variables
int age = 0;
String grade = " ";
String goingToCollege = " ";
String college = " ";
String afterHighSchool = " ";
String job = " ";
// Create a Scanner object for user input
Scanner scan = new Scanner(System.in);
// Prompt the user for their age
System.out.println("Please enter your age as an integer value.");
age = Integer.parseInt(scan.nextLine());
// If age is less than 14
if(age < 14) {
// Prompt the user for the grade they are in
System.out.println("Please enter your grade as an integer value.");
grade = scan.nextLine();
System.out.println("Wow! " + grade + " grade - that sounds exciting!");
}
// If age is between 14 and 18 inclusive
else if(age >= 14 && age <= 18) {
// Ask the user if they are going to college
System.out.println("Are you planning to go to college? (yes/no)");
goingToCollege = scan.nextLine();
// If the user is going to college, ask what college.
if(goingToCollege.equals("yes")) {
System.out.println("What college are you planning to attend?");
college = scan.nextLine();
System.out.println(college + " is a great school!");
}
// If the user is not going to college, as what they would like to do after high school
else if(goingToCollege.equals("no")) {
System.out.println("What would you like to do after High School?");
afterHighSchool = scan.nextLine();
System.out.println("Wow, " + afterHighSchool + " sounds like a plan!");
}
// If input is incorrect
else {
System.out.println("Invalid Input");
}
}
// If age is greater than 18
else if(age > 18) {
// Ask the user what their job is
System.out.println("What is your job?");
job = scan.nextLine();
System.out.println(job + " sounds like a great job!");
}
}
}
| 2,705 | 0.497979 | 0.488791 | 67 | 39.611938 | 29.503328 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.432836 | false | false | 1 |
d55a1a7c9f0410f99ecfb6a9c2dda662d34352e8 | 33,655,363,781,949 | 73b5d880fa06943c20ff0a9aee9d0c1d1eeebe10 | /tinyos-1.x/beta/SystemCore/java/net/tinyos/multihop/MultihopTreeBuilder.java | 12a056750e25e8dc565c1d8e437653b16f7aa03d | [
"Intel"
] | permissive | x3ro/tinyos-legacy | https://github.com/x3ro/tinyos-legacy | 101d19f9e639f5a9d59d3edd4ed04b1f53221e63 | cdc0e7ba1cac505fcace33b974b2e0aca1ccc56a | refs/heads/master | 2021-01-16T19:20:21.744000 | 2015-06-30T20:23:05 | 2015-06-30T20:23:05 | 38,358,728 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.tinyos.multihop;
import net.tinyos.message.*;
import net.tinyos.util.*;
import java.io.*;
import java.text.*;
import java.util.*;
public class MultihopTreeBuilder implements Runnable {
private MoteIF moteIF;
private static final int BEACON_PERIOD = 8*1024;
private int beaconPeriod;
private int spAddr;
private int beaconSeqno = 1;
MultihopBeaconMsg beaconMsg = new MultihopBeaconMsg();
MultihopTreeBuilder(int period) {
beaconPeriod = period;
String moteid = Env.getenv("MOTEID");
if (moteid == null) {
this.spAddr = MultihopConnector.DEFAULT_MOTE_ID;
} else {
this.spAddr = Integer.parseInt(moteid);
}
beaconSeqno = 0;
beaconMsg.set_beaconPeriod(beaconPeriod);
beaconMsg.set_parent(0xffff);
beaconMsg.set_sourceAddr(spAddr);
beaconMsg.set_treeID(spAddr);
beaconMsg.set_cost(0);
beaconMsg.set_timestamp(System.currentTimeMillis());
try {
moteIF = new MoteIF((Messenger)null);
} catch (Exception e) {
System.out.println("ERROR: Couldn't contact serial forwarder.");
System.exit(1);
}
System.out.println(beaconMsg);
send(beaconMsg);
moteIF.start();
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void run() {
while(true) {
try {
// beaconMsg.set_beaconSeqno((short)beaconSeqno++);
beaconMsg.set_timestamp(System.currentTimeMillis());
// System.out.println(beaconMsg);
send(beaconMsg);
Thread.sleep(beaconPeriod);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void send(Message m) {
try {
moteIF.send(MoteIF.TOS_BCAST_ADDR, m);
} catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR: Can't send message");
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
int period = BEACON_PERIOD;
if (args.length < 0) {
System.err.println("usage: java net.tinyos.multihop.MultihopTreeBuilder [beacon period (ms)]");
System.exit(1);
}
if (args.length == 1) {
period = Integer.parseInt(args[0]);
}
MultihopTreeBuilder mtb = new MultihopTreeBuilder(period);
}
}
| UTF-8 | Java | 2,380 | java | MultihopTreeBuilder.java | Java | [] | null | [] | package net.tinyos.multihop;
import net.tinyos.message.*;
import net.tinyos.util.*;
import java.io.*;
import java.text.*;
import java.util.*;
public class MultihopTreeBuilder implements Runnable {
private MoteIF moteIF;
private static final int BEACON_PERIOD = 8*1024;
private int beaconPeriod;
private int spAddr;
private int beaconSeqno = 1;
MultihopBeaconMsg beaconMsg = new MultihopBeaconMsg();
MultihopTreeBuilder(int period) {
beaconPeriod = period;
String moteid = Env.getenv("MOTEID");
if (moteid == null) {
this.spAddr = MultihopConnector.DEFAULT_MOTE_ID;
} else {
this.spAddr = Integer.parseInt(moteid);
}
beaconSeqno = 0;
beaconMsg.set_beaconPeriod(beaconPeriod);
beaconMsg.set_parent(0xffff);
beaconMsg.set_sourceAddr(spAddr);
beaconMsg.set_treeID(spAddr);
beaconMsg.set_cost(0);
beaconMsg.set_timestamp(System.currentTimeMillis());
try {
moteIF = new MoteIF((Messenger)null);
} catch (Exception e) {
System.out.println("ERROR: Couldn't contact serial forwarder.");
System.exit(1);
}
System.out.println(beaconMsg);
send(beaconMsg);
moteIF.start();
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void run() {
while(true) {
try {
// beaconMsg.set_beaconSeqno((short)beaconSeqno++);
beaconMsg.set_timestamp(System.currentTimeMillis());
// System.out.println(beaconMsg);
send(beaconMsg);
Thread.sleep(beaconPeriod);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public synchronized void send(Message m) {
try {
moteIF.send(MoteIF.TOS_BCAST_ADDR, m);
} catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR: Can't send message");
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
int period = BEACON_PERIOD;
if (args.length < 0) {
System.err.println("usage: java net.tinyos.multihop.MultihopTreeBuilder [beacon period (ms)]");
System.exit(1);
}
if (args.length == 1) {
period = Integer.parseInt(args[0]);
}
MultihopTreeBuilder mtb = new MultihopTreeBuilder(period);
}
}
| 2,380 | 0.62521 | 0.618908 | 97 | 22.536083 | 19.701412 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.57732 | false | false | 1 |
daa1e785be5ea76d15fc25da99f6d2600ed88f8e | 35,201,551,986,189 | 831fbac6652f4f2e8cf5cd2ce6d742e6f914d975 | /dropwizard-template/src/main/java/DropwizardConfiguration.java | c39923ce8c3de428b4e6288cc26678f4731760ac | [
"MIT"
] | permissive | abatilo/dropwizard-template | https://github.com/abatilo/dropwizard-template | 8539ba6b019ef29f34a19edd00ad868f15485f0a | 2ef9e14103bc8720da801aa92f4ad6df31b294c8 | refs/heads/master | 2021-04-29T19:50:26.080000 | 2020-10-16T05:53:13 | 2020-10-16T05:53:13 | 121,586,042 | 0 | 1 | MIT | false | 2020-10-16T05:53:15 | 2018-02-15T03:00:13 | 2020-10-12T06:22:57 | 2020-10-16T05:53:15 | 109 | 0 | 1 | 0 | Java | false | false | import io.dropwizard.Configuration;
import javax.validation.Valid;
import lombok.Getter;
@Getter
public class DropwizardConfiguration extends Configuration {
@Valid private String version;
}
| UTF-8 | Java | 196 | java | DropwizardConfiguration.java | Java | [] | null | [] | import io.dropwizard.Configuration;
import javax.validation.Valid;
import lombok.Getter;
@Getter
public class DropwizardConfiguration extends Configuration {
@Valid private String version;
}
| 196 | 0.816327 | 0.816327 | 10 | 18.6 | 19.443251 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 1 |
8994a666145df1da837225e3ac702c3627f3d1c3 | 21,466,246,601,726 | 7a49cf97df151143f26455c132d716d3ab59ec18 | /ProjetS2/src/iut/info1/projetS2/tableur/Container.java | 0c847bff09fd6f5422b980c383b33623031d040d | [] | no_license | Mickap/Calculatrice | https://github.com/Mickap/Calculatrice | 5706cb8fc908c04ecbd236835b368755bf5d80b8 | c719e2ddd144207937c71221088cb5b9632a2a3c | refs/heads/master | 2021-01-18T22:59:14.613000 | 2015-05-31T22:41:49 | 2015-05-31T22:41:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Container.java 5 mai 2015
* IUT Info 1 2014/2015 groupe 3
*/
package iut.info1.projetS2.tableur;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
/**
* Paramétrage des panels de la calculatrice
* @author Mickael
*
*/
@SuppressWarnings("serial")
public class Container extends JPanel {
/**
* Créé un JPanel avec les propriétés voulues
* @param longueur du panel
* @param largeur du panel
*/
public Container(int largeur, int longueur) {
super();
// On définit la couleur de fond du panel
setBackground(new Color(255,228,196));
// dimensions du panel
Dimension dimContainer = new Dimension(largeur, longueur);
setPreferredSize(dimContainer);
}
}
| ISO-8859-1 | Java | 796 | java | Container.java | Java | [
{
"context": "ramétrage des panels de la calculatrice\n * @author Mickael\n *\n */\n@SuppressWarnings(\"serial\")\npublic class C",
"end": 271,
"score": 0.999786376953125,
"start": 264,
"tag": "NAME",
"value": "Mickael"
}
] | null | [] | /*
* Container.java 5 mai 2015
* IUT Info 1 2014/2015 groupe 3
*/
package iut.info1.projetS2.tableur;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
/**
* Paramétrage des panels de la calculatrice
* @author Mickael
*
*/
@SuppressWarnings("serial")
public class Container extends JPanel {
/**
* Créé un JPanel avec les propriétés voulues
* @param longueur du panel
* @param largeur du panel
*/
public Container(int largeur, int longueur) {
super();
// On définit la couleur de fond du panel
setBackground(new Color(255,228,196));
// dimensions du panel
Dimension dimContainer = new Dimension(largeur, longueur);
setPreferredSize(dimContainer);
}
}
| 796 | 0.64557 | 0.612658 | 37 | 20.351351 | 19.2834 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.324324 | false | false | 1 |
7cf058c13910b2f277add1f6e1022b0229d11d48 | 37,641,093,394,703 | 8be33fc6f74bc9a8338da00ce826ec47974fd62d | /springcloud/kdxcloud-iot-moni/src/main/java/com/kdx/cloud/iot/moni/message/backgroundctrl/BackGroundMessageCtrl.java | ec82ad8b325ead0cace033fccc17cd98d98cf8b3 | [] | no_license | lpwang/practise-project | https://github.com/lpwang/practise-project | d877b4f29a744c68fe03013852f53d30528dc32d | 8fd07a2aba2c6a626730e7869c1ccae2d0c628ee | refs/heads/master | 2018-12-19T19:39:45.690000 | 2018-12-18T15:48:16 | 2018-12-18T15:48:16 | 137,304,530 | 0 | 0 | null | false | 2019-11-02T08:53:23 | 2018-06-14T04:05:23 | 2019-07-08T03:52:32 | 2019-11-02T08:53:22 | 3,309 | 0 | 0 | 1 | Java | false | false | package com.kdx.cloud.iot.moni.message.backgroundctrl;
import com.kdx.cloud.iot.moni.globle.entry.RespEntry;
import com.kdx.cloud.iot.moni.globle.factory.RespEntryFactory;
import com.kdx.cloud.iot.moni.message.service.intf.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class BackGroundMessageCtrl {
@Autowired
private IMessageService messageService;
@RequestMapping(method = RequestMethod.GET , path = "/api/background/iot-moni/message/conf/numbers")
public RespEntry<Map<String, Integer>> getMessageNum(@RequestParam(name = "product_id") String product_id) {
int confNumbers = messageService.countMessage(product_id);
HashMap<String, Integer> dataMap = new HashMap<String, Integer>();
dataMap.put("count", confNumbers);
RespEntryFactory<Map<String, Integer>> respEntryFactory = new RespEntryFactory<Map<String, Integer>>();
return respEntryFactory.getSuccessRespEntry(dataMap);
}
}
| UTF-8 | Java | 1,304 | java | BackGroundMessageCtrl.java | Java | [] | null | [] | package com.kdx.cloud.iot.moni.message.backgroundctrl;
import com.kdx.cloud.iot.moni.globle.entry.RespEntry;
import com.kdx.cloud.iot.moni.globle.factory.RespEntryFactory;
import com.kdx.cloud.iot.moni.message.service.intf.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class BackGroundMessageCtrl {
@Autowired
private IMessageService messageService;
@RequestMapping(method = RequestMethod.GET , path = "/api/background/iot-moni/message/conf/numbers")
public RespEntry<Map<String, Integer>> getMessageNum(@RequestParam(name = "product_id") String product_id) {
int confNumbers = messageService.countMessage(product_id);
HashMap<String, Integer> dataMap = new HashMap<String, Integer>();
dataMap.put("count", confNumbers);
RespEntryFactory<Map<String, Integer>> respEntryFactory = new RespEntryFactory<Map<String, Integer>>();
return respEntryFactory.getSuccessRespEntry(dataMap);
}
}
| 1,304 | 0.781442 | 0.781442 | 31 | 41.064518 | 34.215572 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.774194 | false | false | 1 |
645b7f64589f6ff619c2adb7be7149f9c42e2afa | 35,880,156,805,460 | 7b33fe5bf146406baefbe04861c9d2e4f052f1be | /src/main/java/com/lbt/icon/demanddraft/domain/demanddraft/dto/UpdateDemandDraftProductDTO.java | c1d6353dc5a12d00d96788c16c71c41ba895daf5 | [] | no_license | Devbimpe/ddproduct | https://github.com/Devbimpe/ddproduct | 6b62b57e904318068d8d5767ca8e9d94e2ad8a86 | 9eacab6eb99d79bcec243b8e5de37411f2724d4f | refs/heads/master | 2023-03-01T17:49:47.259000 | 2020-08-03T12:27:04 | 2020-08-03T12:27:04 | 299,304,217 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lbt.icon.demanddraft.domain.demanddraft.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.lbt.icon.bankproduct.domain.master.dto.BankProductMasterDTO;
import com.lbt.icon.bankproduct.domain.master.dto.UpdateBankProductMasterDTO;
import com.lbt.icon.core.domain.BaseDTO;
import com.lbt.icon.demanddraft.domain.demanddraftproductcharges.dto.QueryDemandDraftProductChargesDTO;
import com.lbt.icon.demanddraft.type.DDTransferFrequency;
import com.lbt.icon.demanddraft.type.DemandDraftType;
import com.lbt.icon.demanddraft.type.InstrumentSeries;
import lombok.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* @author devbimpe
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Setter
@Getter
@NoArgsConstructor
public class UpdateDemandDraftProductDTO extends BaseDTO {
private String productCode;
private DemandDraftType demandDraftType;
private String inventoryType;
private String issueBank;
private String issueBranch;
private Boolean duplicateIssueReport;
private Boolean consolidatePartTrans;
private Boolean micrInventory;
private DDTransferFrequency ddTransferFrequency;
private String ddTransferSpacer;
private BankProductMasterDTO bankProductMasterDTO;
@Pattern(regexp = "^P[0-9]+[Y][0-9]+[M][0-9]+[D]$", message = "{dd.revalidatePeriod.Pattern}")
private String cautionStatePeriod;
// @JsonIgnore
// @Pattern(regexp = "^P[0-9]+[Y][0-9]+[M][0-9]+[D]$", message = "{dd.revalidatePeriod.Pattern}")
// private String revalidatePeriod;
@NotNull(message = "{demandDraft[NotNull.allowRevalidate]}")
private Boolean allowRevalidate;
// @NotNull(message = "{demandDraft[NotNull.buyExchangeRateCode]}")
// private String buyExchangeRateCode;
@NotNull(message = "{demandDraft[NotNull.exchangeRateCode]}")
private String exchangeRateCode;
private Boolean cashTransferAllowed;
private Boolean transferTransAllowed;
private Boolean custodianPrintAllow;
// private String ddSequenceCode;
private String commonDDAccountId;
private String defaultCustodian;
// private InstrumentSeries instrumentSeries;
private String instrumentSeries;
}
| UTF-8 | Java | 2,304 | java | UpdateDemandDraftProductDTO.java | Java | [
{
"context": "ax.validation.constraints.Pattern;\n\n/**\n * @author devbimpe\n */\n\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@",
"end": 757,
"score": 0.9995009303092957,
"start": 749,
"tag": "USERNAME",
"value": "devbimpe"
}
] | null | [] | package com.lbt.icon.demanddraft.domain.demanddraft.dto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.lbt.icon.bankproduct.domain.master.dto.BankProductMasterDTO;
import com.lbt.icon.bankproduct.domain.master.dto.UpdateBankProductMasterDTO;
import com.lbt.icon.core.domain.BaseDTO;
import com.lbt.icon.demanddraft.domain.demanddraftproductcharges.dto.QueryDemandDraftProductChargesDTO;
import com.lbt.icon.demanddraft.type.DDTransferFrequency;
import com.lbt.icon.demanddraft.type.DemandDraftType;
import com.lbt.icon.demanddraft.type.InstrumentSeries;
import lombok.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* @author devbimpe
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Setter
@Getter
@NoArgsConstructor
public class UpdateDemandDraftProductDTO extends BaseDTO {
private String productCode;
private DemandDraftType demandDraftType;
private String inventoryType;
private String issueBank;
private String issueBranch;
private Boolean duplicateIssueReport;
private Boolean consolidatePartTrans;
private Boolean micrInventory;
private DDTransferFrequency ddTransferFrequency;
private String ddTransferSpacer;
private BankProductMasterDTO bankProductMasterDTO;
@Pattern(regexp = "^P[0-9]+[Y][0-9]+[M][0-9]+[D]$", message = "{dd.revalidatePeriod.Pattern}")
private String cautionStatePeriod;
// @JsonIgnore
// @Pattern(regexp = "^P[0-9]+[Y][0-9]+[M][0-9]+[D]$", message = "{dd.revalidatePeriod.Pattern}")
// private String revalidatePeriod;
@NotNull(message = "{demandDraft[NotNull.allowRevalidate]}")
private Boolean allowRevalidate;
// @NotNull(message = "{demandDraft[NotNull.buyExchangeRateCode]}")
// private String buyExchangeRateCode;
@NotNull(message = "{demandDraft[NotNull.exchangeRateCode]}")
private String exchangeRateCode;
private Boolean cashTransferAllowed;
private Boolean transferTransAllowed;
private Boolean custodianPrintAllow;
// private String ddSequenceCode;
private String commonDDAccountId;
private String defaultCustodian;
// private InstrumentSeries instrumentSeries;
private String instrumentSeries;
}
| 2,304 | 0.772135 | 0.766927 | 85 | 26.105883 | 27.151438 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.458824 | false | false | 1 |
721407508aa435d6037facdd1053b19a6a8a3e42 | 33,878,702,070,489 | d5d5d214a895bb61666b80de82c512200ae32eb8 | /src/test/java/com/kart/pageobjects/HomePage.java | d3411fa9f30bbdc753f01e378c9fec4e0e06dbdf | [] | no_license | Reddy117/Vijaya | https://github.com/Reddy117/Vijaya | 7963c90fc49fc659ec92b8770a0b7e11b2674b9c | 8ecb5dbc90ad314eed351a2241ddf678d282b479 | refs/heads/master | 2022-12-25T05:09:58.064000 | 2020-05-12T13:02:26 | 2020-05-12T13:02:26 | 263,338,128 | 0 | 0 | null | false | 2020-10-13T21:56:14 | 2020-05-12T13:02:48 | 2020-05-12T13:04:05 | 2020-10-13T21:56:13 | 4,272 | 0 | 0 | 1 | Java | false | false | package com.kart.pageobjects;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.kart.util.BaseClass;
public class HomePage extends BaseClass{
@FindBy(xpath="//*[@id=\"block_top_menu\"]/ul/li[1]/a")
public WebElement womenTab;
@FindBy(xpath="//*[@id=\"block_top_menu\"]/ul/li[1]/ul/li[1]/ul/li[1]/a")
public WebElement tshirtLink;
@FindBy(xpath="//*[@id=\"center_column\"]/ul/li/div/div[1]/div/a[1]/img")
public WebElement tshirtImg;
@FindBy(xpath="//*[@id=\"quantity_wanted\"]")
public WebElement qtyTxt;
@FindBy(xpath="//*[@id=\"group_1\"]")
public WebElement sizedrop;
@FindBy(xpath="//*[@id=\"layer_cart\"]/div[1]/div[1]/h2")
public WebElement addKartbtn;
public HomePage(){
PageFactory.initElements(driver, this);
}
public void addProductToKart(String size,String qty,String expMsg){
try{
mouseHover(womenTab);
tshirtLink.click();
tshirtImg.click();
driver.switchTo().frame(0);
qtyTxt.clear();
qtyTxt.sendKeys(qty);
new Select(sizedrop).selectByVisibleText(size);
Thread.sleep(2000);
//addKartbtn.click();
}catch(Exception e){
}
}
}
| UTF-8 | Java | 1,299 | java | HomePage.java | Java | [] | null | [] | package com.kart.pageobjects;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.kart.util.BaseClass;
public class HomePage extends BaseClass{
@FindBy(xpath="//*[@id=\"block_top_menu\"]/ul/li[1]/a")
public WebElement womenTab;
@FindBy(xpath="//*[@id=\"block_top_menu\"]/ul/li[1]/ul/li[1]/ul/li[1]/a")
public WebElement tshirtLink;
@FindBy(xpath="//*[@id=\"center_column\"]/ul/li/div/div[1]/div/a[1]/img")
public WebElement tshirtImg;
@FindBy(xpath="//*[@id=\"quantity_wanted\"]")
public WebElement qtyTxt;
@FindBy(xpath="//*[@id=\"group_1\"]")
public WebElement sizedrop;
@FindBy(xpath="//*[@id=\"layer_cart\"]/div[1]/div[1]/h2")
public WebElement addKartbtn;
public HomePage(){
PageFactory.initElements(driver, this);
}
public void addProductToKart(String size,String qty,String expMsg){
try{
mouseHover(womenTab);
tshirtLink.click();
tshirtImg.click();
driver.switchTo().frame(0);
qtyTxt.clear();
qtyTxt.sendKeys(qty);
new Select(sizedrop).selectByVisibleText(size);
Thread.sleep(2000);
//addKartbtn.click();
}catch(Exception e){
}
}
}
| 1,299 | 0.663587 | 0.65204 | 50 | 23.98 | 21.009989 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.74 | false | false | 1 |
82773d96a607eee04163f9c834014d60264c2a4a | 30,219,389,942,734 | 95ed7fdcab9b2d6154ec6ced005fa8fb13a10adb | /src/schedulers/components/Quantum.java | 08c1fc0d1578d7ea3917a76481062e029b794927 | [] | no_license | MazenAmria/CPU-Scheduler | https://github.com/MazenAmria/CPU-Scheduler | cbe543c3be73c4cc4086ee91ac66b60ea2707d01 | 1a7c6d9383735b24ab52bffbe2ae973c6e68f81f | refs/heads/master | 2023-02-19T08:02:04.017000 | 2021-01-18T19:50:25 | 2021-01-18T19:50:25 | 307,693,196 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package schedulers.components;
public class Quantum implements Visualisable {
private long processID;
private double startTime;
private double finishTime;
public Quantum(long processID, double startTime, double finishTime) {
this.processID = processID;
this.startTime = startTime;
this.finishTime = finishTime;
}
public long getProcessID() {
return processID;
}
public void setProcessID(long processID) {
this.processID = processID;
}
public double getStartTime() {
return startTime;
}
public void setStartTime(double startTime) {
this.startTime = startTime;
}
public double getFinishTime() {
return finishTime;
}
public void setFinishTime(double finishTime) {
this.finishTime = finishTime;
}
@Override
public String toString() {
return "Schedulers.Components.Quantum{" +
"processID=" + processID +
", startTime=" + startTime +
", finishTime=" + finishTime +
'}';
}
}
| UTF-8 | Java | 1,101 | java | Quantum.java | Java | [] | null | [] | package schedulers.components;
public class Quantum implements Visualisable {
private long processID;
private double startTime;
private double finishTime;
public Quantum(long processID, double startTime, double finishTime) {
this.processID = processID;
this.startTime = startTime;
this.finishTime = finishTime;
}
public long getProcessID() {
return processID;
}
public void setProcessID(long processID) {
this.processID = processID;
}
public double getStartTime() {
return startTime;
}
public void setStartTime(double startTime) {
this.startTime = startTime;
}
public double getFinishTime() {
return finishTime;
}
public void setFinishTime(double finishTime) {
this.finishTime = finishTime;
}
@Override
public String toString() {
return "Schedulers.Components.Quantum{" +
"processID=" + processID +
", startTime=" + startTime +
", finishTime=" + finishTime +
'}';
}
}
| 1,101 | 0.608538 | 0.608538 | 46 | 22.934782 | 18.878792 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 1 |
2573f1f4df42a46dc678f497e235bfd90034deb2 | 27,376,121,583,210 | 9164b8146c7cae0deb05d6f353b1a30b68c9d791 | /src/main/java/skhu/sof14/hotthink/config/CommonInterceptor.java | 97a164b3ce104ba9b8f9f2b3a13aa8e546f6f1be | [] | no_license | 14SOF/HotThink | https://github.com/14SOF/HotThink | 5f0b8dcd4100357fa40e61cd9e509d92bfccc3cb | f92b7850236de147b08017b9f3c012a3585e926f | refs/heads/dev | 2021-04-01T14:47:38.996000 | 2020-07-23T11:39:51 | 2020-07-23T11:39:51 | 248,194,541 | 6 | 2 | null | false | 2020-06-05T04:45:14 | 2020-03-18T09:59:04 | 2020-05-21T19:32:12 | 2020-06-05T04:33:59 | 8,032 | 1 | 0 | 77 | HTML | false | false | package skhu.sof14.hotthink.config;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import skhu.sof14.hotthink.config.security.SecurityConfig;
import skhu.sof14.hotthink.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
@Autowired
UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info(" Request URI \t: " + request.getRequestURI());
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null ) {
String nick = userService.getNickFromAuth();
if(!nick.equals("anonymousUser")){
modelAndView.addObject("userNick", nick);
}
}
// logger.info("=================== END ===================\n");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
}
| UTF-8 | Java | 1,803 | java | CommonInterceptor.java | Java | [] | null | [] | package skhu.sof14.hotthink.config;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import skhu.sof14.hotthink.config.security.SecurityConfig;
import skhu.sof14.hotthink.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);
@Autowired
UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info(" Request URI \t: " + request.getRequestURI());
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null ) {
String nick = userService.getNickFromAuth();
if(!nick.equals("anonymousUser")){
modelAndView.addObject("userNick", nick);
}
}
// logger.info("=================== END ===================\n");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
}
| 1,803 | 0.713256 | 0.707155 | 47 | 37.361702 | 32.956081 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.723404 | false | false | 1 |
c5f6ff217e3bbb1750f2988d16dae33906990756 | 34,900,904,282,912 | e9e110cf08972d26c31a00c85f9264c9a22d37c8 | /src/org/radf/apps/commons/entity/FinanceReport.java | bebea52837af54ee0e5cb78d68c72b4e51508ec2 | [] | no_license | xoo1996/huiermis | https://github.com/xoo1996/huiermis | ea96b46944ad3d29524d3fccaf155de282bce4e9 | 8c160010a83767610245cbbbf4eb922b073b1554 | refs/heads/master | 2020-04-16T03:45:43.896000 | 2019-01-11T12:54:29 | 2019-01-11T12:54:29 | 165,240,962 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.radf.apps.commons.entity;
import org.radf.plat.util.entity.EntitySupport;
public class FinanceReport extends EntitySupport {
private Long bindno;
private String gctsname;
private String taxno;
private String fpdtnm;
private String taxrate;
private String fpdtmodel;
private String pdtut;
private String pdtnum;
private String finprc;
private String tmksid;
private String sellprc;
private String gctemail;
private String finnt;
private String pdtprc;
private String finrate;
//private String fintel;
private String gctmobilephone;
private String gctaddr;
private String gctdepositbank;
private String gctdepositid;
private String gcttel;
private String comaddr;
private String depositbank;
private String depositid;
private String specialtel;
private String gctnm;
private String retailname;
private String retailtaxno;
public FinanceReport() {
super();
}
public FinanceReport(Long bindno, String gctsname, String taxno,
String fpdtnm, String taxrate, String fpdtmodel, String pdtut,
String pdtnum, String finprc, String tmksid, String sellprc,
String gctemail, String finnt, String pdtprc, String finrate) {
super();
this.bindno = bindno;
this.gctsname = gctsname;
this.taxno = taxno;
this.fpdtnm = fpdtnm;
this.taxrate = taxrate;
this.fpdtmodel = fpdtmodel;
this.pdtut = pdtut;
this.pdtnum = pdtnum;
this.finprc = finprc;
this.tmksid = tmksid;
this.sellprc = sellprc;
this.gctemail = gctemail;
this.finnt = finnt;
this.pdtprc = pdtprc;
this.finrate = finrate;
}
public FinanceReport(Long bindno, String gctnm, String taxno,
String fpdtnm, String taxrate, String fpdtmodel, String pdtut,
String pdtnum, String finprc, String tmksid, String sellprc,
String gctemail, String finnt, String pdtprc, String finrate, String retailname, String retailtaxno) {
super();
this.bindno = bindno;
this.gctnm = gctnm;
this.taxno = taxno;
this.fpdtnm = fpdtnm;
this.taxrate = taxrate;
this.fpdtmodel = fpdtmodel;
this.pdtut = pdtut;
this.pdtnum = pdtnum;
this.finprc = finprc;
this.tmksid = tmksid;
this.sellprc = sellprc;
this.gctemail = gctemail;
this.finnt = finnt;
this.pdtprc = pdtprc;
this.finrate = finrate;
this.retailname = retailname;
this.retailtaxno = retailtaxno;
}
public String getGctaddr() {
return gctaddr;
}
public void setGctaddr(String gctaddr) {
this.gctaddr = gctaddr;
}
public String getGctdepositbank() {
return gctdepositbank;
}
public void setGctdepositbank(String gctdepositbank) {
this.gctdepositbank = gctdepositbank;
}
public String getGctdepositid() {
return gctdepositid;
}
public void setGctdepositid(String gctdepositid) {
this.gctdepositid = gctdepositid;
}
public String getGcttel() {
return gcttel;
}
public void setGcttel(String gcttel) {
this.gcttel = gcttel;
}
public String getGctnm() {
return gctnm;
}
public void setGctnm(String gctnm) {
this.gctnm = gctnm;
}
public String getRetailname() {
return retailname;
}
public void setRetailname(String retailname) {
this.retailname = retailname;
}
public String getRetailtaxno() {
return retailtaxno;
}
public void setRetailtaxno(String retailtaxno) {
this.retailtaxno = retailtaxno;
}
public String getGctmobilephone() {
return gctmobilephone;
}
public void setGctmobilephone(String gctmobilephone) {
this.gctmobilephone = gctmobilephone;
}
public String getPdtprc() {
return pdtprc;
}
public void setPdtprc(String pdtprc) {
this.pdtprc = pdtprc;
}
public String getFinrate() {
return finrate;
}
public void setFinrate(String finrate) {
this.finrate = finrate;
}
public Long getBindno() {
return bindno;
}
public void setBindno(Long bindno) {
this.bindno = bindno;
}
public String getGctsname() {
return gctsname;
}
public void setGctsname(String gctsname) {
this.gctsname = gctsname;
}
public String getTaxno() {
return taxno;
}
public void setTaxno(String taxno) {
this.taxno = taxno;
}
public String getFpdtnm() {
return fpdtnm;
}
public void setFpdtnm(String fpdtnm) {
this.fpdtnm = fpdtnm;
}
public String getTaxrate() {
return taxrate;
}
public void setTaxrate(String taxrate) {
this.taxrate = taxrate;
}
public String getFpdtmodel() {
return fpdtmodel;
}
public void setFpdtmodel(String fpdtmodel) {
this.fpdtmodel = fpdtmodel;
}
public String getPdtut() {
return pdtut;
}
public void setPdtut(String pdtut) {
this.pdtut = pdtut;
}
public String getPdtnum() {
return pdtnum;
}
public void setPdtnum(String pdtnum) {
this.pdtnum = pdtnum;
}
public String getFinprc() {
return finprc;
}
public void setFinprc(String finprc) {
this.finprc = finprc;
}
public String getTmksid() {
return tmksid;
}
public void setTmksid(String tmksid) {
this.tmksid = tmksid;
}
public String getSellprc() {
return sellprc;
}
public void setSellprc(String sellprc) {
this.sellprc = sellprc;
}
public String getGctemail() {
return gctemail;
}
public void setGctemail(String gctemail) {
this.gctemail = gctemail;
}
public String getFinnt() {
return finnt;
}
public void setFinnt(String finnt) {
this.finnt = finnt;
}
public String getComaddr() {
return comaddr;
}
public void setComaddr(String comaddr) {
this.comaddr = comaddr;
}
public String getDepositbank() {
return depositbank;
}
public void setDepositbank(String depositbank) {
this.depositbank = depositbank;
}
public String getDepositid() {
return depositid;
}
public void setDepositid(String depositid) {
this.depositid = depositid;
}
public String getSpecialtel() {
return specialtel;
}
public void setSpecialtel(String specialtel) {
this.specialtel = specialtel;
}
}
| UTF-8 | Java | 5,824 | java | FinanceReport.java | Java | [] | null | [] | package org.radf.apps.commons.entity;
import org.radf.plat.util.entity.EntitySupport;
public class FinanceReport extends EntitySupport {
private Long bindno;
private String gctsname;
private String taxno;
private String fpdtnm;
private String taxrate;
private String fpdtmodel;
private String pdtut;
private String pdtnum;
private String finprc;
private String tmksid;
private String sellprc;
private String gctemail;
private String finnt;
private String pdtprc;
private String finrate;
//private String fintel;
private String gctmobilephone;
private String gctaddr;
private String gctdepositbank;
private String gctdepositid;
private String gcttel;
private String comaddr;
private String depositbank;
private String depositid;
private String specialtel;
private String gctnm;
private String retailname;
private String retailtaxno;
public FinanceReport() {
super();
}
public FinanceReport(Long bindno, String gctsname, String taxno,
String fpdtnm, String taxrate, String fpdtmodel, String pdtut,
String pdtnum, String finprc, String tmksid, String sellprc,
String gctemail, String finnt, String pdtprc, String finrate) {
super();
this.bindno = bindno;
this.gctsname = gctsname;
this.taxno = taxno;
this.fpdtnm = fpdtnm;
this.taxrate = taxrate;
this.fpdtmodel = fpdtmodel;
this.pdtut = pdtut;
this.pdtnum = pdtnum;
this.finprc = finprc;
this.tmksid = tmksid;
this.sellprc = sellprc;
this.gctemail = gctemail;
this.finnt = finnt;
this.pdtprc = pdtprc;
this.finrate = finrate;
}
public FinanceReport(Long bindno, String gctnm, String taxno,
String fpdtnm, String taxrate, String fpdtmodel, String pdtut,
String pdtnum, String finprc, String tmksid, String sellprc,
String gctemail, String finnt, String pdtprc, String finrate, String retailname, String retailtaxno) {
super();
this.bindno = bindno;
this.gctnm = gctnm;
this.taxno = taxno;
this.fpdtnm = fpdtnm;
this.taxrate = taxrate;
this.fpdtmodel = fpdtmodel;
this.pdtut = pdtut;
this.pdtnum = pdtnum;
this.finprc = finprc;
this.tmksid = tmksid;
this.sellprc = sellprc;
this.gctemail = gctemail;
this.finnt = finnt;
this.pdtprc = pdtprc;
this.finrate = finrate;
this.retailname = retailname;
this.retailtaxno = retailtaxno;
}
public String getGctaddr() {
return gctaddr;
}
public void setGctaddr(String gctaddr) {
this.gctaddr = gctaddr;
}
public String getGctdepositbank() {
return gctdepositbank;
}
public void setGctdepositbank(String gctdepositbank) {
this.gctdepositbank = gctdepositbank;
}
public String getGctdepositid() {
return gctdepositid;
}
public void setGctdepositid(String gctdepositid) {
this.gctdepositid = gctdepositid;
}
public String getGcttel() {
return gcttel;
}
public void setGcttel(String gcttel) {
this.gcttel = gcttel;
}
public String getGctnm() {
return gctnm;
}
public void setGctnm(String gctnm) {
this.gctnm = gctnm;
}
public String getRetailname() {
return retailname;
}
public void setRetailname(String retailname) {
this.retailname = retailname;
}
public String getRetailtaxno() {
return retailtaxno;
}
public void setRetailtaxno(String retailtaxno) {
this.retailtaxno = retailtaxno;
}
public String getGctmobilephone() {
return gctmobilephone;
}
public void setGctmobilephone(String gctmobilephone) {
this.gctmobilephone = gctmobilephone;
}
public String getPdtprc() {
return pdtprc;
}
public void setPdtprc(String pdtprc) {
this.pdtprc = pdtprc;
}
public String getFinrate() {
return finrate;
}
public void setFinrate(String finrate) {
this.finrate = finrate;
}
public Long getBindno() {
return bindno;
}
public void setBindno(Long bindno) {
this.bindno = bindno;
}
public String getGctsname() {
return gctsname;
}
public void setGctsname(String gctsname) {
this.gctsname = gctsname;
}
public String getTaxno() {
return taxno;
}
public void setTaxno(String taxno) {
this.taxno = taxno;
}
public String getFpdtnm() {
return fpdtnm;
}
public void setFpdtnm(String fpdtnm) {
this.fpdtnm = fpdtnm;
}
public String getTaxrate() {
return taxrate;
}
public void setTaxrate(String taxrate) {
this.taxrate = taxrate;
}
public String getFpdtmodel() {
return fpdtmodel;
}
public void setFpdtmodel(String fpdtmodel) {
this.fpdtmodel = fpdtmodel;
}
public String getPdtut() {
return pdtut;
}
public void setPdtut(String pdtut) {
this.pdtut = pdtut;
}
public String getPdtnum() {
return pdtnum;
}
public void setPdtnum(String pdtnum) {
this.pdtnum = pdtnum;
}
public String getFinprc() {
return finprc;
}
public void setFinprc(String finprc) {
this.finprc = finprc;
}
public String getTmksid() {
return tmksid;
}
public void setTmksid(String tmksid) {
this.tmksid = tmksid;
}
public String getSellprc() {
return sellprc;
}
public void setSellprc(String sellprc) {
this.sellprc = sellprc;
}
public String getGctemail() {
return gctemail;
}
public void setGctemail(String gctemail) {
this.gctemail = gctemail;
}
public String getFinnt() {
return finnt;
}
public void setFinnt(String finnt) {
this.finnt = finnt;
}
public String getComaddr() {
return comaddr;
}
public void setComaddr(String comaddr) {
this.comaddr = comaddr;
}
public String getDepositbank() {
return depositbank;
}
public void setDepositbank(String depositbank) {
this.depositbank = depositbank;
}
public String getDepositid() {
return depositid;
}
public void setDepositid(String depositid) {
this.depositid = depositid;
}
public String getSpecialtel() {
return specialtel;
}
public void setSpecialtel(String specialtel) {
this.specialtel = specialtel;
}
}
| 5,824 | 0.718063 | 0.718063 | 311 | 17.726688 | 16.959547 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.604502 | false | false | 1 |
5a07335faac8111653e048be041af43af259cfd9 | 20,933,670,625,673 | 0811e139dac02a40895f492f95a59d57d7fa0a59 | /src/test/java/fr/mgdis/test/sampleTest.java | 6bbb5b0b1dc2ace15de105965e9c00d62e7b4fcd | [] | no_license | noushadali/Karaf-invalid-bundle-example | https://github.com/noushadali/Karaf-invalid-bundle-example | c798ae8278056e39c4022c43d85b82f9fbc81a32 | 5de34fc4cc6c3b8a1d4b6d693cf64d09aa4c9476 | refs/heads/master | 2020-04-01T17:15:34.728000 | 2014-07-06T12:11:28 | 2014-07-06T12:11:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.mgdis.test;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.TypeConversionException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.timer.TimerEndpoint;
import org.apache.camel.test.spring.DisableJmx;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This class has to be a template for all the testing units. You must implement
* two unit tests for all routes. One for nominal behavior One for nominal error
* handler
*
* @author Philippe-y
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
// Load camel-context-test.xml file for testing
@ContextConfiguration({ "/camel-context-test.xml" })
// Declare context as dirty. To remove it after all tests method
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@DisableJmx(false)
public class sampleTest {
static final Logger logger = LoggerFactory
.getLogger(sampleTest.class);
@Inject
@Named("testBroker")
// spring injection of broker configuration
// defined on broker-test.xml
protected BrokerService broker;
@Inject
@Named("test-context")
// spring injection of camel context for testing
// defined on camel-context-test.xml
protected CamelContext testContext;
@Inject
@Named("camel-context")
// spring injection of production camel context
// defined on META-INF/spring/camel-context.xml
protected CamelContext context;
@EndpointInject(uri = "mock://result", context = "camel-context")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct://start", context = "camel-context")
protected ProducerTemplate template;
@Value("${incoming.endpoint}")
protected String in;
@Value("${outgoing.endpoint}")
protected String out;
@Before
public void setUp() throws Exception {
// start the broker if it is not already started
if (!broker.isStarted()) {
broker.start(true);
}
// wait for all defined routes to be started
broker.waitUntilStarted();
// before all tests method, reset mock to ensure messages count.
for (Endpoint endP : context.getEndpoints()) {
if (endP instanceof MockEndpoint) {
((MockEndpoint) endP).reset();
}
}
// in this unit test, we need to send a message in an specific
// queue. We are creating a new route in test context that
// sends messages into this mediation queue.
testContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
}
});
// To test the result, all the messages are finally destined
// to a mock:result endPoint.
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct://start").inOut(in);
from(out).to("mock://result");
}
});
}
@After
public void tearDown() throws Exception {
// first of all, stop and shutdown all routes in test context
for (Route route : testContext.getRoutes()) {
testContext.stopRoute(route.getId());
testContext.removeRoute(route.getId());
}
// reset all mocks, even if this is done on setUp()
MockEndpoint.resetMocks(testContext);
// For all activeMQ destination queues, make a
// graceful shutdown with only 1sec timeout
for (ActiveMQDestination dest : broker.getRegionBroker()
.getDestinations()) {
broker.getRegionBroker().removeDestination(
broker.getAdminConnectionContext(), dest, 1000);
}
// kill all active endPoints on production camel context
for (Endpoint endP : context.getEndpoints()) {
if (endP instanceof TimerEndpoint) {
((TimerEndpoint) endP).shutdown();
}
}
}
@Test
public void testExample() throws Exception {
// Arrange
resultEndpoint.expectedMessageCount(1);
resultEndpoint.expectedMessagesMatches(new Predicate() {
private final transient Logger log = LoggerFactory.getLogger(this
.getClass());
public boolean matches(Exchange exchange) {
boolean isMatched = false;
try {
// response body string load
String body = exchange.getIn().getBody(String.class);
isMatched = body.contains("XSLT");
} catch (TypeConversionException e) {
log.error("When converting body", e);
}
return isMatched;
}
});
// Act
template.sendBody("<root/>");
// Assert
resultEndpoint.assertIsSatisfied();
}
}
| UTF-8 | Java | 5,824 | java | sampleTest.java | Java | [
{
"context": "or One for nominal error\n * handler\n * \n * @author Philippe-y\n * \n */\n@RunWith(SpringJUnit4ClassRunner.class)\n/",
"end": 1409,
"score": 0.9957765340805054,
"start": 1399,
"tag": "NAME",
"value": "Philippe-y"
}
] | null | [] | package fr.mgdis.test;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Predicate;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.TypeConversionException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.timer.TimerEndpoint;
import org.apache.camel.test.spring.DisableJmx;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This class has to be a template for all the testing units. You must implement
* two unit tests for all routes. One for nominal behavior One for nominal error
* handler
*
* @author Philippe-y
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
// Load camel-context-test.xml file for testing
@ContextConfiguration({ "/camel-context-test.xml" })
// Declare context as dirty. To remove it after all tests method
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@DisableJmx(false)
public class sampleTest {
static final Logger logger = LoggerFactory
.getLogger(sampleTest.class);
@Inject
@Named("testBroker")
// spring injection of broker configuration
// defined on broker-test.xml
protected BrokerService broker;
@Inject
@Named("test-context")
// spring injection of camel context for testing
// defined on camel-context-test.xml
protected CamelContext testContext;
@Inject
@Named("camel-context")
// spring injection of production camel context
// defined on META-INF/spring/camel-context.xml
protected CamelContext context;
@EndpointInject(uri = "mock://result", context = "camel-context")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct://start", context = "camel-context")
protected ProducerTemplate template;
@Value("${incoming.endpoint}")
protected String in;
@Value("${outgoing.endpoint}")
protected String out;
@Before
public void setUp() throws Exception {
// start the broker if it is not already started
if (!broker.isStarted()) {
broker.start(true);
}
// wait for all defined routes to be started
broker.waitUntilStarted();
// before all tests method, reset mock to ensure messages count.
for (Endpoint endP : context.getEndpoints()) {
if (endP instanceof MockEndpoint) {
((MockEndpoint) endP).reset();
}
}
// in this unit test, we need to send a message in an specific
// queue. We are creating a new route in test context that
// sends messages into this mediation queue.
testContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
}
});
// To test the result, all the messages are finally destined
// to a mock:result endPoint.
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct://start").inOut(in);
from(out).to("mock://result");
}
});
}
@After
public void tearDown() throws Exception {
// first of all, stop and shutdown all routes in test context
for (Route route : testContext.getRoutes()) {
testContext.stopRoute(route.getId());
testContext.removeRoute(route.getId());
}
// reset all mocks, even if this is done on setUp()
MockEndpoint.resetMocks(testContext);
// For all activeMQ destination queues, make a
// graceful shutdown with only 1sec timeout
for (ActiveMQDestination dest : broker.getRegionBroker()
.getDestinations()) {
broker.getRegionBroker().removeDestination(
broker.getAdminConnectionContext(), dest, 1000);
}
// kill all active endPoints on production camel context
for (Endpoint endP : context.getEndpoints()) {
if (endP instanceof TimerEndpoint) {
((TimerEndpoint) endP).shutdown();
}
}
}
@Test
public void testExample() throws Exception {
// Arrange
resultEndpoint.expectedMessageCount(1);
resultEndpoint.expectedMessagesMatches(new Predicate() {
private final transient Logger log = LoggerFactory.getLogger(this
.getClass());
public boolean matches(Exchange exchange) {
boolean isMatched = false;
try {
// response body string load
String body = exchange.getIn().getBody(String.class);
isMatched = body.contains("XSLT");
} catch (TypeConversionException e) {
log.error("When converting body", e);
}
return isMatched;
}
});
// Act
template.sendBody("<root/>");
// Assert
resultEndpoint.assertIsSatisfied();
}
}
| 5,824 | 0.653674 | 0.651786 | 171 | 33.058479 | 22.452213 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409357 | false | false | 1 |
3ec72b3156371e9380245cbbd7b3b66707a94945 | 13,529,147,007,158 | 77c787034d64d35b0ae2f036d0039ebae07a7708 | /src/main/java/pure/booking/controller/DataServiceTestController.java | 836a5413e4d6722958ada2ee96236e5aeec4b5f7 | [] | no_license | tath105/TFPureBook | https://github.com/tath105/TFPureBook | 4972e9ca92a2ca0ee28326ef18d3dc7830cc27c1 | 7078398e524eca35f438a72e19cc28bf7857b5d7 | refs/heads/master | 2016-09-19T03:24:00.352000 | 2016-09-18T16:23:46 | 2016-09-18T16:23:46 | 67,888,857 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pure.booking.controller;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pure.booking.model.PureClassPlan;
import pure.booking.model.PureLocation;
import pure.booking.model.UserAccount;
import pure.booking.model.UserBookingSchedule;
import pure.booking.repo.PureClassPlanRepo;
import pure.booking.repo.PureLocationRepo;
import pure.booking.repo.UserAccountRepo;
import pure.booking.repo.UserBookingScheduleRepo;
//Remove this class and src/main/resources/templates/test.html
//once you are familiar with data service usage
@Controller
public class DataServiceTestController {
@Autowired
PureLocationRepo centerRepo;
@Autowired
PureClassPlanRepo pureClassRepo;
@Autowired
UserAccountRepo userAccountRepo;
@Autowired
UserBookingScheduleRepo userBookingScheduleRepo;
PureLocation center = new PureLocation();
PureClassPlan pureClass = new PureClassPlan();
UserAccount userAccount = new UserAccount();
UserBookingSchedule schedule = new UserBookingSchedule();
@RequestMapping("/testCreateLocation")
public String test1(Model model) {
center.setLocationId("locationId");
center.setLocationName("name");
center.setTabId("tabId");
center.setType("type");
centerRepo.save(center);
return "test";
}
@RequestMapping("/testCreateClass")
public String test2(Model model) {
pureClass.setStartDate("startDate");
pureClass.setStartTime("startTime");
pureClass.setDuration("duration");
pureClass.setClassName("className");
pureClass.setSignUpId("signup");
pureClass.setTypeGroup("group");
pureClass.setLocationId("locationId");
pureClass.setLocationName("locationName");
pureClass.setStatus("status");
pureClass.setClassCode("classCode");
pureClass.setTutorId("tutorId");
pureClass.setTutorName("name");
pureClassRepo.save(pureClass);
return "test";
}
@RequestMapping("/testCreateUser")
public String test3(Model model) {
userAccount.setEmail("email");
userAccount.setPassword("password");
userAccountRepo.save(userAccount);
return "test";
}
@RequestMapping("/testCreateSchedule")
public String test4(Model model) {
schedule.setPureClassPlan(pureClass);
schedule.setUserAccount(userAccount);
schedule.setRegisterDate(DateTime.now());
schedule.setRunStatus("PENDING BOOKING");
schedule.setBookingResult("bookingResult");
userBookingScheduleRepo.save(schedule);
return "test";
}
@RequestMapping("/testCreateNewSchedule")
public String test5(Model model) {
UserBookingSchedule schedule = new UserBookingSchedule();
this.test2(null);
this.test3(null);
schedule.setPureClassPlan(pureClass);
schedule.setUserAccount(userAccount);
schedule.setRegisterDate(DateTime.now());
schedule.setRunStatus("PENDING BOOKING");
schedule.setBookingResult("bookingResult");
userBookingScheduleRepo.save(schedule);
return "test";
}
}
| UTF-8 | Java | 3,144 | java | DataServiceTestController.java | Java | [
{
"context": "nt.setEmail(\"email\");\r\n\t\tuserAccount.setPassword(\"password\");\r\n\t\tuserAccountRepo.save(userAccount);\r\n\t\tretur",
"end": 2236,
"score": 0.9992528557777405,
"start": 2228,
"tag": "PASSWORD",
"value": "password"
}
] | null | [] | package pure.booking.controller;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import pure.booking.model.PureClassPlan;
import pure.booking.model.PureLocation;
import pure.booking.model.UserAccount;
import pure.booking.model.UserBookingSchedule;
import pure.booking.repo.PureClassPlanRepo;
import pure.booking.repo.PureLocationRepo;
import pure.booking.repo.UserAccountRepo;
import pure.booking.repo.UserBookingScheduleRepo;
//Remove this class and src/main/resources/templates/test.html
//once you are familiar with data service usage
@Controller
public class DataServiceTestController {
@Autowired
PureLocationRepo centerRepo;
@Autowired
PureClassPlanRepo pureClassRepo;
@Autowired
UserAccountRepo userAccountRepo;
@Autowired
UserBookingScheduleRepo userBookingScheduleRepo;
PureLocation center = new PureLocation();
PureClassPlan pureClass = new PureClassPlan();
UserAccount userAccount = new UserAccount();
UserBookingSchedule schedule = new UserBookingSchedule();
@RequestMapping("/testCreateLocation")
public String test1(Model model) {
center.setLocationId("locationId");
center.setLocationName("name");
center.setTabId("tabId");
center.setType("type");
centerRepo.save(center);
return "test";
}
@RequestMapping("/testCreateClass")
public String test2(Model model) {
pureClass.setStartDate("startDate");
pureClass.setStartTime("startTime");
pureClass.setDuration("duration");
pureClass.setClassName("className");
pureClass.setSignUpId("signup");
pureClass.setTypeGroup("group");
pureClass.setLocationId("locationId");
pureClass.setLocationName("locationName");
pureClass.setStatus("status");
pureClass.setClassCode("classCode");
pureClass.setTutorId("tutorId");
pureClass.setTutorName("name");
pureClassRepo.save(pureClass);
return "test";
}
@RequestMapping("/testCreateUser")
public String test3(Model model) {
userAccount.setEmail("email");
userAccount.setPassword("<PASSWORD>");
userAccountRepo.save(userAccount);
return "test";
}
@RequestMapping("/testCreateSchedule")
public String test4(Model model) {
schedule.setPureClassPlan(pureClass);
schedule.setUserAccount(userAccount);
schedule.setRegisterDate(DateTime.now());
schedule.setRunStatus("PENDING BOOKING");
schedule.setBookingResult("bookingResult");
userBookingScheduleRepo.save(schedule);
return "test";
}
@RequestMapping("/testCreateNewSchedule")
public String test5(Model model) {
UserBookingSchedule schedule = new UserBookingSchedule();
this.test2(null);
this.test3(null);
schedule.setPureClassPlan(pureClass);
schedule.setUserAccount(userAccount);
schedule.setRegisterDate(DateTime.now());
schedule.setRunStatus("PENDING BOOKING");
schedule.setBookingResult("bookingResult");
userBookingScheduleRepo.save(schedule);
return "test";
}
}
| 3,146 | 0.758906 | 0.756679 | 101 | 29.128714 | 17.468876 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.841584 | false | false | 1 |
7303287ac42907117e6c51b08ae36b8825daacc9 | 17,111,149,742,416 | 34db8db49580476b991e615a33acc9411cab02c3 | /myGolombSolver.java | a588bf075b43a8dc255468acd3cca87abdfc3e63 | [] | no_license | YemowtRonoc/Second-Year_Algorithms2 | https://github.com/YemowtRonoc/Second-Year_Algorithms2 | 7a8e762c36736edd19f72397f978782e503e6398 | d98763900ec0845f632b6d06fe82c9b2b57f00af | refs/heads/master | 2017-10-31T14:51:00.868000 | 2017-01-15T00:50:46 | 2017-01-15T00:50:46 | 68,647,115 | 0 | 0 | null | false | 2017-01-15T00:50:47 | 2016-09-19T21:11:27 | 2016-09-19T21:11:27 | 2017-01-15T00:50:47 | 488 | 0 | 0 | 0 | null | null | null |
public class myGolombSolver {
//--------------------------------------------------
// Attributes
//--------------------------------------------------
private myGolombRuler bestSolution;
private myGolombRuler current;
//-------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------
public myGolombSolver(int n){
//1. Get the initial best solution using the upper bound
this.bestSolution = new myGolombRuler(n);
int val = 1;
for (int i = 1; i < n; i++){
val = val * 2;
bestSolution.addMark(val-1);
}
val = val - 1;
//2. Create the initial status to start the search
this.current = new myGolombRuler(n);
}
//-------------------------------------------------------------------
// getBestSolution
//-------------------------------------------------------------------
public myGolombRuler getBestSolution(){
return this.bestSolution;
}
//-------------------------------------------------------------------
// exploreSearchSpace
//-------------------------------------------------------------------
public void exploreSearchSpace(int k, int n, int ub){
//1 starting, 4 number of elements in ruler, 8 upper bound of the ruler
if (k == n){
if (current.getLastMark() < bestSolution.getLastMark()){
current.displayContent();
bestSolution = new myGolombRuler(current);
}
} else {
for (int i = current.getLastMark(); i < bestSolution.getLastMark() - (((n - k - 1) * (n - k)) / 2); i++){
if (current.addMark(i)){
exploreSearchSpace(k + 1, n, ub);
current.removeMark();
}
}
}
}
//for (int i = current.getLastMark() + 1; i < bestSolution.getLastMark() - (((n - k - 1) * (n - k)) / 2); i++){
}
| UTF-8 | Java | 1,844 | java | myGolombSolver.java | Java | [] | null | [] |
public class myGolombSolver {
//--------------------------------------------------
// Attributes
//--------------------------------------------------
private myGolombRuler bestSolution;
private myGolombRuler current;
//-------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------
public myGolombSolver(int n){
//1. Get the initial best solution using the upper bound
this.bestSolution = new myGolombRuler(n);
int val = 1;
for (int i = 1; i < n; i++){
val = val * 2;
bestSolution.addMark(val-1);
}
val = val - 1;
//2. Create the initial status to start the search
this.current = new myGolombRuler(n);
}
//-------------------------------------------------------------------
// getBestSolution
//-------------------------------------------------------------------
public myGolombRuler getBestSolution(){
return this.bestSolution;
}
//-------------------------------------------------------------------
// exploreSearchSpace
//-------------------------------------------------------------------
public void exploreSearchSpace(int k, int n, int ub){
//1 starting, 4 number of elements in ruler, 8 upper bound of the ruler
if (k == n){
if (current.getLastMark() < bestSolution.getLastMark()){
current.displayContent();
bestSolution = new myGolombRuler(current);
}
} else {
for (int i = current.getLastMark(); i < bestSolution.getLastMark() - (((n - k - 1) * (n - k)) / 2); i++){
if (current.addMark(i)){
exploreSearchSpace(k + 1, n, ub);
current.removeMark();
}
}
}
}
//for (int i = current.getLastMark() + 1; i < bestSolution.getLastMark() - (((n - k - 1) * (n - k)) / 2); i++){
}
| 1,844 | 0.427874 | 0.419197 | 58 | 29.758621 | 28.039572 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.241379 | false | false | 1 |
1195b729418ac7527e42f48acf90a706de01591d | 12,498,354,860,144 | a006590c81486b3a26becb346b57e13db2f1011a | /src/com/felixvn/PlayVideoFragmentActivity.java | 130805eab8a0c970786df5a74832dbe28fa3f3a4 | [] | no_license | RuynLe/FelixApp | https://github.com/RuynLe/FelixApp | fa5e03601ffe87c1c7fc20bc8d43b9b31de051ed | d32586e98cf389b6141f7351d49aff02cc4863d4 | refs/heads/master | 2016-06-12T05:09:26.439000 | 2016-06-01T01:41:10 | 2016-06-01T01:41:10 | 58,364,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.felixvn;
import java.util.Locale;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import com.felixvn.screen.utils.ScreenUtils;
import com.felixvn.utils.LogUtils;
import com.felixvn.utils.ShowMessageUtils;
import com.felixvn.utils.ShowMessageUtils.ShowMessageClickListener;
/**
* PlayVideoFragmentActivity
*
* @author nguyenquoccuong
*
*/
public class PlayVideoFragmentActivity extends BaseFragmentActivity {
public static String KEY_VIDEO = "pathvideo";
private VideoView videoView;
private String pathVideo = "";
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ScreenUtils.setFullScreen(this);
setContentView(R.layout.play_video_fragment_activity);
loadControl();
loadData();
}
@Override
public void loadControl() {
// TODO Auto-generated method stub
super.loadControl();
videoView = (VideoView) findViewById(R.id.videoView);
}
@Override
public void loadData() {
// TODO Auto-generated method stub
super.loadData();
try {
pathVideo = getIntent().getStringExtra(KEY_VIDEO);
//pathVideo = "http://techslides.com/demos/sample-videos/small.mp4";
String extension = pathVideo.substring(pathVideo.lastIndexOf(".")).toLowerCase(Locale.getDefault());
if (!extension.equals(".mp4")) {
ShowMessageUtils.showMessage(context, "",
getString(R.string.alert_not_support),
new ShowMessageClickListener() {
@Override
public void onClickOk() {
finish();
}
});
} else {
showProgressBar(context, "", getString(R.string.loading));
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(videoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(pathVideo);
videoView.setMediaController(mediacontroller);
videoView.setVideoURI(video);
videoView.requestFocus();
videoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
closeProgressBar();
videoView.start();
}
});
videoView.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
closeProgressBar();
String message = "";
if (MediaPlayer.MEDIA_ERROR_IO == extra) {
message = getString(R.string.alert_error_vtv_io);
} else if (MediaPlayer.MEDIA_ERROR_MALFORMED == extra) {
message = getString(R.string.alert_error_vtv_unsupported);
} else if (MediaPlayer.MEDIA_ERROR_UNSUPPORTED == extra) {
message = getString(R.string.alert_error_vtv_unsupported);
} else if (MediaPlayer.MEDIA_ERROR_TIMED_OUT == extra) {
message = getString(R.string.alert_error_vtv_io);
}
ShowMessageUtils.showMessage(context, "", message,
new ShowMessageClickListener() {
@Override
public void onClickOk() {
// TODO Auto-generated method stub
finish();
}
});
return true;
}
});
}
} catch (Exception e) {
LogUtils.logError(e.getMessage());
e.printStackTrace();
closeProgressBar();
}
}
}
| UTF-8 | Java | 3,661 | java | PlayVideoFragmentActivity.java | Java | [
{
"context": "/**\r\n * PlayVideoFragmentActivity\r\n * \r\n * @author nguyenquoccuong\r\n * \r\n */\r\npublic class PlayVideoFragmentActivity",
"end": 583,
"score": 0.9993202090263367,
"start": 568,
"tag": "USERNAME",
"value": "nguyenquoccuong"
}
] | null | [] | package com.felixvn;
import java.util.Locale;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import com.felixvn.screen.utils.ScreenUtils;
import com.felixvn.utils.LogUtils;
import com.felixvn.utils.ShowMessageUtils;
import com.felixvn.utils.ShowMessageUtils.ShowMessageClickListener;
/**
* PlayVideoFragmentActivity
*
* @author nguyenquoccuong
*
*/
public class PlayVideoFragmentActivity extends BaseFragmentActivity {
public static String KEY_VIDEO = "pathvideo";
private VideoView videoView;
private String pathVideo = "";
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ScreenUtils.setFullScreen(this);
setContentView(R.layout.play_video_fragment_activity);
loadControl();
loadData();
}
@Override
public void loadControl() {
// TODO Auto-generated method stub
super.loadControl();
videoView = (VideoView) findViewById(R.id.videoView);
}
@Override
public void loadData() {
// TODO Auto-generated method stub
super.loadData();
try {
pathVideo = getIntent().getStringExtra(KEY_VIDEO);
//pathVideo = "http://techslides.com/demos/sample-videos/small.mp4";
String extension = pathVideo.substring(pathVideo.lastIndexOf(".")).toLowerCase(Locale.getDefault());
if (!extension.equals(".mp4")) {
ShowMessageUtils.showMessage(context, "",
getString(R.string.alert_not_support),
new ShowMessageClickListener() {
@Override
public void onClickOk() {
finish();
}
});
} else {
showProgressBar(context, "", getString(R.string.loading));
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(videoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(pathVideo);
videoView.setMediaController(mediacontroller);
videoView.setVideoURI(video);
videoView.requestFocus();
videoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
closeProgressBar();
videoView.start();
}
});
videoView.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
closeProgressBar();
String message = "";
if (MediaPlayer.MEDIA_ERROR_IO == extra) {
message = getString(R.string.alert_error_vtv_io);
} else if (MediaPlayer.MEDIA_ERROR_MALFORMED == extra) {
message = getString(R.string.alert_error_vtv_unsupported);
} else if (MediaPlayer.MEDIA_ERROR_UNSUPPORTED == extra) {
message = getString(R.string.alert_error_vtv_unsupported);
} else if (MediaPlayer.MEDIA_ERROR_TIMED_OUT == extra) {
message = getString(R.string.alert_error_vtv_io);
}
ShowMessageUtils.showMessage(context, "", message,
new ShowMessageClickListener() {
@Override
public void onClickOk() {
// TODO Auto-generated method stub
finish();
}
});
return true;
}
});
}
} catch (Exception e) {
LogUtils.logError(e.getMessage());
e.printStackTrace();
closeProgressBar();
}
}
}
| 3,661 | 0.671128 | 0.670582 | 123 | 27.764227 | 22.093697 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.487805 | false | false | 1 |
9c440acb6409a51ef5bc7a594f2d642da00192e7 | 32,358,283,634,668 | d9ebb265489d341727f7357831bc7950e5094a25 | /Web/CAAC-CTF-2018-Web/WAFWTF/CAAC-SQL-Injection/src/com/wrlus/caac/Search.java | bdc4802b61ad7192f00fd2895fe160e4023ad033 | [
"Apache-2.0"
] | permissive | wrlu/CAAC-CTF-2018-Primary | https://github.com/wrlu/CAAC-CTF-2018-Primary | 779979acfcb5786170f6e9574e8b1ffea557bbfd | 46d87063db665c25bfff936fd7a06fcb4325f138 | refs/heads/master | 2022-07-17T16:34:39.614000 | 2020-05-15T02:26:16 | 2020-05-15T02:26:16 | 264,076,062 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wrlus.caac;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;
public class Search {
public static String doSearch(String air) throws SecurityException {
if(null==air || air.equals("")) {
return "";
}
if(doWaf(air)==false) {
throw new SecurityException("∫‹±ß«∏£¨ƒ˙Ã·Ωªµƒ≤Œ ˝ø…ƒ‹æfl”–π•ª˜––Œ™£¨“—±ªœµÕ≥π‹¿Ì‘±…Ë÷√¿πΩÿ°£");
}
Properties dbproperties = new Properties();
InputStream dbconfig = Search.class.getResourceAsStream("/config/config.properties");
try {
dbproperties.load(dbconfig);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = (Connection)DriverManager.getConnection("jdbc:mysql://127.0.0.1/caac", dbproperties);
String sql = "select name,details from air where id = ?";
System.out.println(sql);
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, air);
ResultSet resultSet = ps.executeQuery();
String result = "";
while(resultSet.next()==true) {
result += resultSet.getString(1)+" ";
result += resultSet.getString(2)+" ";
result += "<br>";
}
return result;
} catch (Exception e) {
return e.getLocalizedMessage();
}
}
public static boolean doWaf(String air) {
Scanner waffile = new Scanner(Search.class.getResourceAsStream("/config/waf.txt"));
while(waffile.hasNextLine()==true) {
String wafkeyword = waffile.nextLine();
if (air.contains(wafkeyword)) {
waffile.close();
return false;
}
}
waffile.close();
return true;
}
}
| UTF-8 | Java | 1,790 | java | Search.java | Java | [
{
"context": "nection)DriverManager.getConnection(\"jdbc:mysql://127.0.0.1/caac\", dbproperties);\n\t\t\tString sql = \"se",
"end": 867,
"score": 0.5606317520141602,
"start": 866,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "tion)DriverManager.getConnection(\"jdbc:mysql://127.0... | null | [] | package com.wrlus.caac;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;
public class Search {
public static String doSearch(String air) throws SecurityException {
if(null==air || air.equals("")) {
return "";
}
if(doWaf(air)==false) {
throw new SecurityException("∫‹±ß«∏£¨ƒ˙Ã·Ωªµƒ≤Œ ˝ø…ƒ‹æfl”–π•ª˜––Œ™£¨“—±ªœµÕ≥π‹¿Ì‘±…Ë÷√¿πΩÿ°£");
}
Properties dbproperties = new Properties();
InputStream dbconfig = Search.class.getResourceAsStream("/config/config.properties");
try {
dbproperties.load(dbconfig);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = (Connection)DriverManager.getConnection("jdbc:mysql://127.0.0.1/caac", dbproperties);
String sql = "select name,details from air where id = ?";
System.out.println(sql);
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, air);
ResultSet resultSet = ps.executeQuery();
String result = "";
while(resultSet.next()==true) {
result += resultSet.getString(1)+" ";
result += resultSet.getString(2)+" ";
result += "<br>";
}
return result;
} catch (Exception e) {
return e.getLocalizedMessage();
}
}
public static boolean doWaf(String air) {
Scanner waffile = new Scanner(Search.class.getResourceAsStream("/config/waf.txt"));
while(waffile.hasNextLine()==true) {
String wafkeyword = waffile.nextLine();
if (air.contains(wafkeyword)) {
waffile.close();
return false;
}
}
waffile.close();
return true;
}
}
| 1,790 | 0.679157 | 0.673888 | 60 | 27.466667 | 24.497255 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.6 | false | false | 1 |
26c5e945f45504a79b9cbac21c6905a093503484 | 29,944,512,021,189 | f81ca3daaf946a53dfdf7376048168fc7a309f1e | /Dataset2/mining_results/RepositoryMining5/201/632951898a2f1474f699094200367fb405397127/JsonInterpolationServiceTest.java | b47beb307a77005bed7f8d24985f4220bde5d120 | [] | no_license | bellmit/Predicting-Vulnerable-Code | https://github.com/bellmit/Predicting-Vulnerable-Code | 54a71f16f3f2f28d7d6e9d405ad3b9beb6e24cad | e004909d4cc2d6f1861212b4eae475c3c38b3b53 | refs/heads/master | 2022-12-02T01:48:09.169000 | 2020-07-31T18:56:31 | 2020-07-31T18:56:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.pivotal.security.service;
import io.pivotal.security.audit.EventAuditRecordParameters;
import io.pivotal.security.data.CredentialDataService;
import io.pivotal.security.domain.JsonCredential;
import io.pivotal.security.domain.PasswordCredential;
import io.pivotal.security.exceptions.ParameterizedValidationException;
import org.assertj.core.util.Maps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.pivotal.security.audit.AuditingOperationCode.CREDENTIAL_ACCESS;
import static io.pivotal.security.helper.JsonTestHelper.deserialize;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.samePropertyValuesAs;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(JUnit4.class)
public class JsonInterpolationServiceTest {
private JsonInterpolationService subject;
private Map<String, Object> response;
private List<EventAuditRecordParameters> eventAuditRecordParameters;
private CredentialDataService credentialDataService;
@Before
public void beforeEach() {
credentialDataService = mock(CredentialDataService.class);
subject = new JsonInterpolationService(credentialDataService);
eventAuditRecordParameters = new ArrayList<>();
}
@Test
public void interpolateCredHubReferences_replacesTheCredHubRefWithSomethingElse() throws Exception {
setupValidRequest();
final ArrayList firstService = (ArrayList) response.get("pp-config-server");
final ArrayList secondService = (ArrayList) response.get("pp-something-else");
Map<String, Object> firstCredentialsBlock = (Map<String, Object>) ((Map<String, Object>) firstService.get(0)).get("credentials");
Map<String, Object> secondCredentialsBlock = (Map<String, Object>) ((Map<String, Object>) firstService.get(1)).get("credentials");
Map<String, Object> secondServiceCredentials = (Map<String, Object>) ((Map<String, Object>) secondService.get(0)).get("credentials");
assertThat(firstCredentialsBlock.get("credhub-ref"), nullValue());
assertThat(firstCredentialsBlock.size(), equalTo(1));
assertThat(firstCredentialsBlock.get("secret1"), equalTo("secret1-value"));
assertThat(secondCredentialsBlock.get("credhub-ref"), nullValue());
assertThat(secondCredentialsBlock.size(), equalTo(1));
assertThat(secondCredentialsBlock.get("secret2"), equalTo("secret2-value"));
assertThat(secondServiceCredentials.get("credhub-ref"), nullValue());
assertThat(secondServiceCredentials.size(), equalTo(2));
assertThat(secondServiceCredentials.get("secret3-1"), equalTo("secret3-1-value"));
assertThat(secondServiceCredentials.get("secret3-2"), equalTo("secret3-2-value"));
}
@Test
public void interpolateCredHubReferences_updatesTheEventAuditRecordParameters() throws Exception {
setupValidRequest();
assertThat(eventAuditRecordParameters, hasSize(3));
assertThat(eventAuditRecordParameters, containsInAnyOrder(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred1")),
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred2")),
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred3"))));
}
@Test
public void interpolateCredHubReferences_whenAReferencedCredentialIsNotJsonType_itThrowsAnException() throws Exception {
String inputJson = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/password_cred))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ " ]"
+ "}";
PasswordCredential passwordCredential = mock(PasswordCredential.class);
when(passwordCredential.getName()).thenReturn("/password_cred");
doReturn(
passwordCredential
).when(credentialDataService).findMostRecent("/password_cred");
try {
subject.interpolateCredHubReferences(deserialize(inputJson, Map.class),
eventAuditRecordParameters);
} catch (ParameterizedValidationException exception) {
assertThat(exception.getMessage(), equalTo("error.interpolation.invalid_type"));
assertThat(eventAuditRecordParameters, hasSize(1));
assertThat(eventAuditRecordParameters, contains(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/password_cred"))
));
}
}
@Test
public void interpolateCredHubReferences_whenAReferencedCredentialDoesNotExist_itThrowsAnException() {
String inputJsonString = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/missing_cred))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ " ]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
doReturn(
null
).when(credentialDataService).findMostRecent("/missing_cred");
try {
subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
} catch (ParameterizedValidationException exception) {
assertThat(exception.getMessage(), equalTo("error.credential.invalid_access"));
assertThat(eventAuditRecordParameters, hasSize(1));
assertThat(eventAuditRecordParameters, contains(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/missing_cred"))
));
}
}
@Test
public void interpolateCredHubReferences_whenTheServicePropertiesLackCredentials_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{"
+ " \"pp-config-server\": [{"
+ " \"blah\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsPropertyHasNoRefs_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{"
+ " \"pp-config-server\": [{"
+ " \"credentials\": {"
+ " \"key\": \"((value))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsPropertyIsFormattedUnexpectedly_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [{"
+ " \"foo\": {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " }"
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenThePropertiesAreNotAHash_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [\"what is this?\"]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsAreNotAHashInAnArray_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [{"
+ " \"credentials\": \"moose\","
+ " \"label\": \"squirrel\""
+ " }]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenPropertiesAreEmpty_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenServicePropertiesAreNotArrays_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map response = subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
private void setupValidRequest() {
String inputJsonString = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " },"
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred2))\""
+ " }"
+ " }"
+ " ],"
+ " \"pp-something-else\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred3))\""
+ " },"
+ " \"something\": [\"pp-config-server\"]"
+ " }"
+ " ]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
JsonCredential jsonCredential = mock(JsonCredential.class);
when(jsonCredential.getName()).thenReturn("/cred1");
doReturn(Maps.newHashMap("secret1", "secret1-value")).when(jsonCredential).getValue();
JsonCredential jsonCredential1 = mock(JsonCredential.class);
when(jsonCredential1.getName()).thenReturn("/cred2");
doReturn(Maps.newHashMap("secret2", "secret2-value")).when(jsonCredential1).getValue();
JsonCredential jsonCredential2 = mock(JsonCredential.class);
when(jsonCredential2.getName()).thenReturn("/cred3");
Map<String, String> jsonCredetials = Maps.newHashMap("secret3-1", "secret3-1-value");
jsonCredetials.put("secret3-2", "secret3-2-value");
doReturn(jsonCredetials).when(jsonCredential2).getValue();
doReturn(
jsonCredential
).when(credentialDataService).findMostRecent("/cred1");
doReturn(
jsonCredential1
).when(credentialDataService).findMostRecent("/cred2");
doReturn(
jsonCredential2
).when(credentialDataService).findMostRecent("/cred3");
response = subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
}
}
| UTF-8 | Java | 12,141 | java | JsonInterpolationServiceTest.java | Java | [
{
"context": "\\\"credentials\\\": {\"\n + \" \\\"key\\\": \\\"((value))\\\"\"\n + \" },\"\n + \" \\\"label\\\": ",
"end": 6881,
"score": 0.6717296242713928,
"start": 6874,
"tag": "KEY",
"value": "value))"
}
] | null | [] | package io.pivotal.security.service;
import io.pivotal.security.audit.EventAuditRecordParameters;
import io.pivotal.security.data.CredentialDataService;
import io.pivotal.security.domain.JsonCredential;
import io.pivotal.security.domain.PasswordCredential;
import io.pivotal.security.exceptions.ParameterizedValidationException;
import org.assertj.core.util.Maps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.pivotal.security.audit.AuditingOperationCode.CREDENTIAL_ACCESS;
import static io.pivotal.security.helper.JsonTestHelper.deserialize;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.samePropertyValuesAs;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(JUnit4.class)
public class JsonInterpolationServiceTest {
private JsonInterpolationService subject;
private Map<String, Object> response;
private List<EventAuditRecordParameters> eventAuditRecordParameters;
private CredentialDataService credentialDataService;
@Before
public void beforeEach() {
credentialDataService = mock(CredentialDataService.class);
subject = new JsonInterpolationService(credentialDataService);
eventAuditRecordParameters = new ArrayList<>();
}
@Test
public void interpolateCredHubReferences_replacesTheCredHubRefWithSomethingElse() throws Exception {
setupValidRequest();
final ArrayList firstService = (ArrayList) response.get("pp-config-server");
final ArrayList secondService = (ArrayList) response.get("pp-something-else");
Map<String, Object> firstCredentialsBlock = (Map<String, Object>) ((Map<String, Object>) firstService.get(0)).get("credentials");
Map<String, Object> secondCredentialsBlock = (Map<String, Object>) ((Map<String, Object>) firstService.get(1)).get("credentials");
Map<String, Object> secondServiceCredentials = (Map<String, Object>) ((Map<String, Object>) secondService.get(0)).get("credentials");
assertThat(firstCredentialsBlock.get("credhub-ref"), nullValue());
assertThat(firstCredentialsBlock.size(), equalTo(1));
assertThat(firstCredentialsBlock.get("secret1"), equalTo("secret1-value"));
assertThat(secondCredentialsBlock.get("credhub-ref"), nullValue());
assertThat(secondCredentialsBlock.size(), equalTo(1));
assertThat(secondCredentialsBlock.get("secret2"), equalTo("secret2-value"));
assertThat(secondServiceCredentials.get("credhub-ref"), nullValue());
assertThat(secondServiceCredentials.size(), equalTo(2));
assertThat(secondServiceCredentials.get("secret3-1"), equalTo("secret3-1-value"));
assertThat(secondServiceCredentials.get("secret3-2"), equalTo("secret3-2-value"));
}
@Test
public void interpolateCredHubReferences_updatesTheEventAuditRecordParameters() throws Exception {
setupValidRequest();
assertThat(eventAuditRecordParameters, hasSize(3));
assertThat(eventAuditRecordParameters, containsInAnyOrder(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred1")),
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred2")),
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/cred3"))));
}
@Test
public void interpolateCredHubReferences_whenAReferencedCredentialIsNotJsonType_itThrowsAnException() throws Exception {
String inputJson = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/password_cred))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ " ]"
+ "}";
PasswordCredential passwordCredential = mock(PasswordCredential.class);
when(passwordCredential.getName()).thenReturn("/password_cred");
doReturn(
passwordCredential
).when(credentialDataService).findMostRecent("/password_cred");
try {
subject.interpolateCredHubReferences(deserialize(inputJson, Map.class),
eventAuditRecordParameters);
} catch (ParameterizedValidationException exception) {
assertThat(exception.getMessage(), equalTo("error.interpolation.invalid_type"));
assertThat(eventAuditRecordParameters, hasSize(1));
assertThat(eventAuditRecordParameters, contains(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/password_cred"))
));
}
}
@Test
public void interpolateCredHubReferences_whenAReferencedCredentialDoesNotExist_itThrowsAnException() {
String inputJsonString = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/missing_cred))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ " ]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
doReturn(
null
).when(credentialDataService).findMostRecent("/missing_cred");
try {
subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
} catch (ParameterizedValidationException exception) {
assertThat(exception.getMessage(), equalTo("error.credential.invalid_access"));
assertThat(eventAuditRecordParameters, hasSize(1));
assertThat(eventAuditRecordParameters, contains(
samePropertyValuesAs(new EventAuditRecordParameters(CREDENTIAL_ACCESS, "/missing_cred"))
));
}
}
@Test
public void interpolateCredHubReferences_whenTheServicePropertiesLackCredentials_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{"
+ " \"pp-config-server\": [{"
+ " \"blah\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsPropertyHasNoRefs_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{"
+ " \"pp-config-server\": [{"
+ " \"credentials\": {"
+ " \"key\": \"((value))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsPropertyIsFormattedUnexpectedly_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [{"
+ " \"foo\": {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " }"
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenThePropertiesAreNotAHash_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [\"what is this?\"]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenTheCredentialsAreNotAHashInAnArray_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": [{"
+ " \"credentials\": \"moose\","
+ " \"label\": \"squirrel\""
+ " }]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenPropertiesAreEmpty_doesNotInterpolateIt() {
Map<String, Object> inputJson = deserialize("{}", Map.class);
Map<String, Object> response = subject
.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
@Test
public void interpolateCredHubReferences_whenServicePropertiesAreNotArrays_doesNotInterpolateIt() {
String inputJsonString = "{"
+ " \"pp-config-server\": {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " }"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
Map response = subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
assertThat(response, equalTo(inputJson));
assertThat(eventAuditRecordParameters, hasSize(0));
}
private void setupValidRequest() {
String inputJsonString = "{"
+ " \"pp-config-server\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred1))\""
+ " },"
+ " \"label\": \"pp-config-server\""
+ " },"
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred2))\""
+ " }"
+ " }"
+ " ],"
+ " \"pp-something-else\": ["
+ " {"
+ " \"credentials\": {"
+ " \"credhub-ref\": \"((/cred3))\""
+ " },"
+ " \"something\": [\"pp-config-server\"]"
+ " }"
+ " ]"
+ "}";
Map<String, Object> inputJson = deserialize(inputJsonString, Map.class);
JsonCredential jsonCredential = mock(JsonCredential.class);
when(jsonCredential.getName()).thenReturn("/cred1");
doReturn(Maps.newHashMap("secret1", "secret1-value")).when(jsonCredential).getValue();
JsonCredential jsonCredential1 = mock(JsonCredential.class);
when(jsonCredential1.getName()).thenReturn("/cred2");
doReturn(Maps.newHashMap("secret2", "secret2-value")).when(jsonCredential1).getValue();
JsonCredential jsonCredential2 = mock(JsonCredential.class);
when(jsonCredential2.getName()).thenReturn("/cred3");
Map<String, String> jsonCredetials = Maps.newHashMap("secret3-1", "secret3-1-value");
jsonCredetials.put("secret3-2", "secret3-2-value");
doReturn(jsonCredetials).when(jsonCredential2).getValue();
doReturn(
jsonCredential
).when(credentialDataService).findMostRecent("/cred1");
doReturn(
jsonCredential1
).when(credentialDataService).findMostRecent("/cred2");
doReturn(
jsonCredential2
).when(credentialDataService).findMostRecent("/cred3");
response = subject.interpolateCredHubReferences(inputJson, eventAuditRecordParameters);
}
}
| 12,141 | 0.659419 | 0.654065 | 311 | 38.03537 | 31.194576 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.694534 | false | false | 1 |
09a98e39a3d804c5518259cd319d5ee47f27bac8 | 32,968,168,997,424 | d31a4fc19d6ad777b04d2894b78af5169e9c0cf0 | /java/swim-jaxb/swim-jaxb-tmfdata/target/generated-sources/xjc/us/gov/dot/faa/atm/tfm/tfmrequestreplytypes/TitleType.java | 931942d10b61d087b741496bfdd8e8b58df9f015 | [] | no_license | am1985/swim | https://github.com/am1985/swim | 71120c281f56a4e1962ae3cc822fc579822e8489 | 44a9295b62520560c61a0c1e7b982e23f886ea60 | refs/heads/master | 2021-05-21T19:00:20.206000 | 2020-04-03T17:17:31 | 2020-04-03T17:17:31 | 252,761,369 | 0 | 0 | null | false | 2020-10-13T20:53:13 | 2020-04-03T14:49:41 | 2020-04-03T17:17:45 | 2020-10-13T20:53:12 | 1,767 | 0 | 0 | 1 | Java | false | false | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.04.03 at 10:08:32 AM EDT
//
package us.gov.dot.faa.atm.tfm.tfmrequestreplytypes;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for titleType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="titleType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="facId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="titleDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="title" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "titleType", propOrder = {
"facId",
"titleDate",
"title"
})
public class TitleType {
protected String facId;
protected String titleDate;
protected String title;
/**
* Gets the value of the facId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFacId() {
return facId;
}
/**
* Sets the value of the facId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFacId(String value) {
this.facId = value;
}
/**
* Gets the value of the titleDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitleDate() {
return titleDate;
}
/**
* Sets the value of the titleDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitleDate(String value) {
this.titleDate = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
}
| UTF-8 | Java | 2,921 | java | TitleType.java | Java | [] | null | [] | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.04.03 at 10:08:32 AM EDT
//
package us.gov.dot.faa.atm.tfm.tfmrequestreplytypes;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for titleType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="titleType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="facId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="titleDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="title" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "titleType", propOrder = {
"facId",
"titleDate",
"title"
})
public class TitleType {
protected String facId;
protected String titleDate;
protected String title;
/**
* Gets the value of the facId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFacId() {
return facId;
}
/**
* Sets the value of the facId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFacId(String value) {
this.facId = value;
}
/**
* Gets the value of the titleDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitleDate() {
return titleDate;
}
/**
* Sets the value of the titleDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitleDate(String value) {
this.titleDate = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
}
| 2,921 | 0.577884 | 0.563506 | 121 | 23.140495 | 24.35458 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.322314 | false | false | 1 |
7244ef45164707609a436effe5ec3a2cab011726 | 2,499,670,998,155 | 8b2b54319b4d61fe86e25d2d2b38d9b9b54539b3 | /LAB1/app/src/main/java/com/example/woody_lin/lab1/MainActivity.java | eac339bc7a117d0586c7ac88cb49030c453d03fe | [] | no_license | KUASWoodyLIN/Android-example | https://github.com/KUASWoodyLIN/Android-example | 4aed3cc83ec35858be4d69082299ed6fa35f8ac6 | f177028f9bb8719f9b8b7d33d5d0f881703f7e6b | refs/heads/master | 2021-01-19T08:59:38.881000 | 2017-05-04T03:15:27 | 2017-05-04T03:15:27 | 87,708,322 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.woody_lin.lab1;
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.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText gamer;
TextView status,name,winner,myMora,computerMora;
RadioGroup radioGroup;
RadioButton radioButton1,radioButton2,radioButton3;
Button play;
int playerMora = -1;
String[] mora = {"剪刀","石頭","布"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gamer =(EditText) findViewById(R.id.gamer);
status = (TextView)findViewById(R.id.status);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
radioButton1 = (RadioButton)findViewById(R.id.radioButton1);
radioButton2 = (RadioButton)findViewById(R.id.radioButton2);
radioButton3 = (RadioButton)findViewById(R.id.radioButton3);
play = (Button)findViewById(R.id.play);
name =(TextView)findViewById(R.id.name);
winner = (TextView)findViewById(R.id.winner);
myMora = (TextView)findViewById(R.id.myMora);
computerMora =(TextView)findViewById(R.id.computerMora);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (gamer.getText().toString().equals("")){
status.setText("請選擇玩家名稱");
}
else if(playerMora == -1){
status.setText("請選擇出拳的種類");
}
else{
name.setText(gamer.getText());
myMora.setText(mora[playerMora]);
int computer_random = (int) (Math.random()*3);
computerMora.setText(mora[computer_random]);
if (playerMora == computer_random){
winner.setText("平手");
status.setText("平手!再試一場看看");
}
else if ((playerMora==0 && computer_random==1)||(playerMora==1 && computer_random==2)||(playerMora==2 && computer_random==0))
{
winner.setText("電腦");
status.setText("可惜電腦獲勝了");
}
else
{
winner.setText(gamer.getText());
status.setText("恭喜你獲勝了");
}
}
}
});
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.radioButton1:
playerMora = 0;
break;
case R.id.radioButton2:
playerMora = 1;
break;
case R.id.radioButton3:
playerMora = 2;
break;
}
}
});
}
}
| UTF-8 | Java | 3,597 | java | MainActivity.java | Java | [
{
"context": "package com.example.woody_lin.lab1;\n\nimport android.support.v7.app.AppCompatAct",
"end": 29,
"score": 0.9725866913795471,
"start": 20,
"tag": "USERNAME",
"value": "woody_lin"
},
{
"context": " {\n winner.setText(\"電腦\");\n ... | null | [] | package com.example.woody_lin.lab1;
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.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText gamer;
TextView status,name,winner,myMora,computerMora;
RadioGroup radioGroup;
RadioButton radioButton1,radioButton2,radioButton3;
Button play;
int playerMora = -1;
String[] mora = {"剪刀","石頭","布"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gamer =(EditText) findViewById(R.id.gamer);
status = (TextView)findViewById(R.id.status);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
radioButton1 = (RadioButton)findViewById(R.id.radioButton1);
radioButton2 = (RadioButton)findViewById(R.id.radioButton2);
radioButton3 = (RadioButton)findViewById(R.id.radioButton3);
play = (Button)findViewById(R.id.play);
name =(TextView)findViewById(R.id.name);
winner = (TextView)findViewById(R.id.winner);
myMora = (TextView)findViewById(R.id.myMora);
computerMora =(TextView)findViewById(R.id.computerMora);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (gamer.getText().toString().equals("")){
status.setText("請選擇玩家名稱");
}
else if(playerMora == -1){
status.setText("請選擇出拳的種類");
}
else{
name.setText(gamer.getText());
myMora.setText(mora[playerMora]);
int computer_random = (int) (Math.random()*3);
computerMora.setText(mora[computer_random]);
if (playerMora == computer_random){
winner.setText("平手");
status.setText("平手!再試一場看看");
}
else if ((playerMora==0 && computer_random==1)||(playerMora==1 && computer_random==2)||(playerMora==2 && computer_random==0))
{
winner.setText("電腦");
status.setText("可惜電腦獲勝了");
}
else
{
winner.setText(gamer.getText());
status.setText("恭喜你獲勝了");
}
}
}
});
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (radioGroup.getCheckedRadioButtonId()){
case R.id.radioButton1:
playerMora = 0;
break;
case R.id.radioButton2:
playerMora = 1;
break;
case R.id.radioButton3:
playerMora = 2;
break;
}
}
});
}
}
| 3,597 | 0.5355 | 0.528087 | 94 | 36.30851 | 23.466602 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670213 | false | false | 1 |
2f3a0522f5c85162c4c8422b7af2f4c56a5a2578 | 609,885,394,662 | 98eca7fd2bc69662eacabf43ea9be7c866c66666 | /hi-auth-web/src/main/java/com/bestaone/hiauth/domain/enums/ResourceDomainType.java | 442a05aaef411401a42a750903073c507959fd4e | [
"MIT"
] | permissive | driphub/HiAuth | https://github.com/driphub/HiAuth | 4fe79e905404e48bac6c44e647c1e5aa47724dc7 | e50a8420e9946b297fa98da5a3e2464f046934cb | refs/heads/master | 2020-05-13T06:33:01.573000 | 2019-04-11T09:26:04 | 2019-04-11T09:26:04 | 181,619,048 | 1 | 0 | MIT | true | 2019-04-16T05:13:42 | 2019-04-16T05:13:39 | 2019-04-16T05:13:42 | 2019-04-11T09:26:31 | 10,903 | 0 | 0 | 0 | Vue | false | false | package com.bestaone.hiauth.domain.enums;
public enum ResourceDomainType {
AUTH("认证系统"),USER("用户系统"),GOODS("商品系统"),ORDER("订单系统");
private String text;
ResourceDomainType(String text){
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| UTF-8 | Java | 397 | java | ResourceDomainType.java | Java | [] | null | [] | package com.bestaone.hiauth.domain.enums;
public enum ResourceDomainType {
AUTH("认证系统"),USER("用户系统"),GOODS("商品系统"),ORDER("订单系统");
private String text;
ResourceDomainType(String text){
this.text = text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| 397 | 0.608219 | 0.608219 | 21 | 16.380953 | 17.343796 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 1 |
291291d28dc58aa3fc2d5d09bccd961cd167001b | 13,743,895,354,169 | b85d0ce8280cff639a80de8bf35e2ad110ac7e16 | /com/fossil/alr.java | 46b49a1d019074e0ad08f7fc03677f5d1815ee23 | [] | no_license | MathiasMonstrey/fosil_decompiled | https://github.com/MathiasMonstrey/fosil_decompiled | 3d90433663db67efdc93775145afc0f4a3dd150c | 667c5eea80c829164220222e8fa64bf7185c9aae | refs/heads/master | 2020-03-19T12:18:30.615000 | 2018-06-07T17:26:09 | 2018-06-07T17:26:09 | 136,509,743 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fossil;
import com.fasterxml.jackson.core.JsonGenerator;
public abstract class alr {
static final class C1673a extends ald {
protected final Class<?>[] _views;
protected final ald aUA;
public /* synthetic */ ald mo1082b(amo com_fossil_amo) {
return m3756d(com_fossil_amo);
}
protected C1673a(ald com_fossil_ald, Class<?>[] clsArr) {
super(com_fossil_ald);
this.aUA = com_fossil_ald;
this._views = clsArr;
}
public C1673a m3756d(amo com_fossil_amo) {
return new C1673a(this.aUA.mo1082b(com_fossil_amo), this._views);
}
public void mo1081a(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1081a((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1083b(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1083b((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1072b(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView != null) {
int i = 0;
int length = this._views.length;
while (i < length && !this._views[i].isAssignableFrom(activeView)) {
i++;
}
if (i == length) {
this.aUA.mo1073c(obj, jsonGenerator, com_fossil_ahg);
return;
}
}
this.aUA.mo1072b(obj, jsonGenerator, com_fossil_ahg);
}
public void mo1074d(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView != null) {
int i = 0;
int length = this._views.length;
while (i < length && !this._views[i].isAssignableFrom(activeView)) {
i++;
}
if (i == length) {
this.aUA.m3702e(obj, jsonGenerator, com_fossil_ahg);
return;
}
}
this.aUA.mo1074d(obj, jsonGenerator, com_fossil_ahg);
}
}
static final class C1674b extends ald {
protected final Class<?> _view;
protected final ald aUA;
public /* synthetic */ ald mo1082b(amo com_fossil_amo) {
return m3763e(com_fossil_amo);
}
protected C1674b(ald com_fossil_ald, Class<?> cls) {
super(com_fossil_ald);
this.aUA = com_fossil_ald;
this._view = cls;
}
public C1674b m3763e(amo com_fossil_amo) {
return new C1674b(this.aUA.mo1082b(com_fossil_amo), this._view);
}
public void mo1081a(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1081a((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1083b(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1083b((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1072b(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView == null || this._view.isAssignableFrom(activeView)) {
this.aUA.mo1072b(obj, jsonGenerator, com_fossil_ahg);
} else {
this.aUA.mo1073c(obj, jsonGenerator, com_fossil_ahg);
}
}
public void mo1074d(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView == null || this._view.isAssignableFrom(activeView)) {
this.aUA.mo1074d(obj, jsonGenerator, com_fossil_ahg);
} else {
this.aUA.m3702e(obj, jsonGenerator, com_fossil_ahg);
}
}
}
public static ald m3764a(ald com_fossil_ald, Class<?>[] clsArr) {
if (clsArr.length == 1) {
return new C1674b(com_fossil_ald, clsArr[0]);
}
return new C1673a(com_fossil_ald, clsArr);
}
}
| UTF-8 | Java | 4,272 | java | alr.java | Java | [] | null | [] | package com.fossil;
import com.fasterxml.jackson.core.JsonGenerator;
public abstract class alr {
static final class C1673a extends ald {
protected final Class<?>[] _views;
protected final ald aUA;
public /* synthetic */ ald mo1082b(amo com_fossil_amo) {
return m3756d(com_fossil_amo);
}
protected C1673a(ald com_fossil_ald, Class<?>[] clsArr) {
super(com_fossil_ald);
this.aUA = com_fossil_ald;
this._views = clsArr;
}
public C1673a m3756d(amo com_fossil_amo) {
return new C1673a(this.aUA.mo1082b(com_fossil_amo), this._views);
}
public void mo1081a(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1081a((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1083b(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1083b((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1072b(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView != null) {
int i = 0;
int length = this._views.length;
while (i < length && !this._views[i].isAssignableFrom(activeView)) {
i++;
}
if (i == length) {
this.aUA.mo1073c(obj, jsonGenerator, com_fossil_ahg);
return;
}
}
this.aUA.mo1072b(obj, jsonGenerator, com_fossil_ahg);
}
public void mo1074d(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView != null) {
int i = 0;
int length = this._views.length;
while (i < length && !this._views[i].isAssignableFrom(activeView)) {
i++;
}
if (i == length) {
this.aUA.m3702e(obj, jsonGenerator, com_fossil_ahg);
return;
}
}
this.aUA.mo1074d(obj, jsonGenerator, com_fossil_ahg);
}
}
static final class C1674b extends ald {
protected final Class<?> _view;
protected final ald aUA;
public /* synthetic */ ald mo1082b(amo com_fossil_amo) {
return m3763e(com_fossil_amo);
}
protected C1674b(ald com_fossil_ald, Class<?> cls) {
super(com_fossil_ald);
this.aUA = com_fossil_ald;
this._view = cls;
}
public C1674b m3763e(amo com_fossil_amo) {
return new C1674b(this.aUA.mo1082b(com_fossil_amo), this._view);
}
public void mo1081a(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1081a((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1083b(ahb<Object> com_fossil_ahb_java_lang_Object) {
this.aUA.mo1083b((ahb) com_fossil_ahb_java_lang_Object);
}
public void mo1072b(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView == null || this._view.isAssignableFrom(activeView)) {
this.aUA.mo1072b(obj, jsonGenerator, com_fossil_ahg);
} else {
this.aUA.mo1073c(obj, jsonGenerator, com_fossil_ahg);
}
}
public void mo1074d(Object obj, JsonGenerator jsonGenerator, ahg com_fossil_ahg) throws Exception {
Class activeView = com_fossil_ahg.getActiveView();
if (activeView == null || this._view.isAssignableFrom(activeView)) {
this.aUA.mo1074d(obj, jsonGenerator, com_fossil_ahg);
} else {
this.aUA.m3702e(obj, jsonGenerator, com_fossil_ahg);
}
}
}
public static ald m3764a(ald com_fossil_ald, Class<?>[] clsArr) {
if (clsArr.length == 1) {
return new C1674b(com_fossil_ald, clsArr[0]);
}
return new C1673a(com_fossil_ald, clsArr);
}
}
| 4,272 | 0.551966 | 0.514513 | 117 | 35.512821 | 29.777699 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65812 | false | false | 1 |
76c9affa06799412d17638c9d3e15908eefe9c23 | 25,915,832,696,212 | dc76b9940d61b4cc40ed414889c5a16cce4cf49c | /src/praktek02/PenjualanTas.java | effaffbc89284e5eb4df2669d761ff4eed6f924c | [] | no_license | LailaAgustina/Praktek02 | https://github.com/LailaAgustina/Praktek02 | dbafbf94e53b5eb17602ab6ba0b7823aa9ece995 | d3c74bbbd8d6a2db6c33796974f6fce5dcb607ab | refs/heads/master | 2020-03-07T13:51:09.242000 | 2018-03-31T07:59:54 | 2018-03-31T07:59:54 | 127,511,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package praktek02;
public class PenjualanTas {
int hrgtas;
int jmlbeli;
public PenjualanTas() {
hrgtas=250000;
jmlbeli=4;
}
public PenjualanTas(int hrgtas, int jmlbeli) {
this.hrgtas = hrgtas;
this.jmlbeli = jmlbeli;
}
void cetakInfo(){
System.out.println("=====================");
System.out.println("hrgtas : "+hrgtas);
System.out.println("jmlbeli : "+jmlbeli);
System.out.println("=====================");
}
int hitungTotal(){
int total;
total=hrgtas*jmlbeli;
return total;
}
void cetakTotal(){
System.out.println("Total PenjualanTas = "+hitungTotal());
}
}
| UTF-8 | Java | 693 | java | PenjualanTas.java | Java | [] | null | [] | package praktek02;
public class PenjualanTas {
int hrgtas;
int jmlbeli;
public PenjualanTas() {
hrgtas=250000;
jmlbeli=4;
}
public PenjualanTas(int hrgtas, int jmlbeli) {
this.hrgtas = hrgtas;
this.jmlbeli = jmlbeli;
}
void cetakInfo(){
System.out.println("=====================");
System.out.println("hrgtas : "+hrgtas);
System.out.println("jmlbeli : "+jmlbeli);
System.out.println("=====================");
}
int hitungTotal(){
int total;
total=hrgtas*jmlbeli;
return total;
}
void cetakTotal(){
System.out.println("Total PenjualanTas = "+hitungTotal());
}
}
| 693 | 0.546898 | 0.533911 | 34 | 19.382353 | 17.435621 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 1 |
445ebf3f9f1cbd88669bdb293ec8b88861c3a9ca | 28,492,813,090,264 | f10feaaa9ec1cb488d036fb5b34df7209999ac1b | /src/main/java/com/richstonedt/garnet/mapper/ResourceMapper.java | 867606bfafde34906aa588efb5c0b6523d93b709 | [
"Apache-2.0"
] | permissive | richstonedt/garnet | https://github.com/richstonedt/garnet | d4d4fcdcd2fe8ba357a64c69504eb0df4c6ed829 | 973b9c59b14cf8aa46bb62ac4e27ec52db9756f6 | refs/heads/master | 2022-10-24T19:56:38.343000 | 2019-06-23T18:44:38 | 2019-06-23T18:44:38 | 157,103,312 | 0 | 1 | Apache-2.0 | false | 2022-10-12T20:27:06 | 2018-11-11T17:27:59 | 2019-06-23T18:50:56 | 2022-10-12T20:27:05 | 4,788 | 0 | 0 | 7 | Java | false | false | package com.richstonedt.garnet.mapper;
import com.richstonedt.garnet.model.Resource;
import com.richstonedt.garnet.model.criteria.ResourceCriteria;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Repository
@Mapper
public interface ResourceMapper extends BaseMapper<Resource, ResourceCriteria, Long> {
Resource selectSingleByCriteria(ResourceCriteria criteria);
int insertBatchSelective(List<Resource> records);
int updateBatchByPrimaryKeySelective(List<Resource> records);
}
| UTF-8 | Java | 655 | java | ResourceMapper.java | Java | [] | null | [] | package com.richstonedt.garnet.mapper;
import com.richstonedt.garnet.model.Resource;
import com.richstonedt.garnet.model.criteria.ResourceCriteria;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Repository
@Mapper
public interface ResourceMapper extends BaseMapper<Resource, ResourceCriteria, Long> {
Resource selectSingleByCriteria(ResourceCriteria criteria);
int insertBatchSelective(List<Resource> records);
int updateBatchByPrimaryKeySelective(List<Resource> records);
}
| 655 | 0.832061 | 0.832061 | 20 | 31.75 | 26.93302 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 1 |
e3539ad5ebfe51f5ccc8df10bd4b6a46bbe055a7 | 28,046,136,495,738 | 5a2c60f6bf7170ff03033c9c5596b3633924c040 | /src/main/java/com/github/mongo/controller/IComplexDataController.java | 4e26245e9c0392114c54314d798730790ffd5748 | [] | no_license | miverse/spring-boot-mongo | https://github.com/miverse/spring-boot-mongo | b5193abdb26df7d103703a5945ab93b801c92e55 | 2828917cbd4ab2e38cb17823d3fb1041d3a95d8c | refs/heads/master | 2023-08-04T15:49:57.565000 | 2021-09-23T05:59:47 | 2021-09-23T05:59:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.mongo.controller;
import com.github.mongo.pojo.bo.ComplexDataBO;
import com.github.mongo.pojo.dto.ComplexDataDTO;
import com.github.mongo.pojo.dto.ResultDTO;
import java.util.List;
/**
* <p>
* 创建时间为 下午3:43 2019/10/16
* 项目名称 spring-boot-mongo
* </p>
*
* @author 石少东
* @version 0.0.1
* @since 0.0.1
*/
public interface IComplexDataController {
ResultDTO<List<ComplexDataBO>> getByDateBetween(ComplexDataDTO complexDataDTO);
}
| UTF-8 | Java | 490 | java | IComplexDataController.java | Java | [
{
"context": "6\n * 项目名称 spring-boot-mongo\n * </p>\n *\n * @author 石少东\n * @version 0.0.1\n * @since 0.0.1\n */\n\npublic int",
"end": 292,
"score": 0.998551607131958,
"start": 289,
"tag": "NAME",
"value": "石少东"
}
] | null | [] | package com.github.mongo.controller;
import com.github.mongo.pojo.bo.ComplexDataBO;
import com.github.mongo.pojo.dto.ComplexDataDTO;
import com.github.mongo.pojo.dto.ResultDTO;
import java.util.List;
/**
* <p>
* 创建时间为 下午3:43 2019/10/16
* 项目名称 spring-boot-mongo
* </p>
*
* @author 石少东
* @version 0.0.1
* @since 0.0.1
*/
public interface IComplexDataController {
ResultDTO<List<ComplexDataBO>> getByDateBetween(ComplexDataDTO complexDataDTO);
}
| 490 | 0.731602 | 0.694805 | 24 | 18.25 | 21.158627 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
8d3a82e5e123ca8cf171099cccae33e61d3ce953 | 18,468,359,388,928 | 85333932dfa75d88d210df5c6d51ccaaf42565a1 | /src/Sudoku/SudokuFrame.java | ee2aced0c9e115eeb5120a8eb2b4103c06c30002 | [] | no_license | tatena/oop-2020-hw-03 | https://github.com/tatena/oop-2020-hw-03 | 1454186464e38448936d9aab94c7bdb76af7e158 | d485eb704f40b98dbcb1e596b6d1d18a0ddce746 | refs/heads/master | 2022-07-03T11:10:41.702000 | 2020-05-13T19:45:01 | 2020-05-13T19:45:01 | 262,372,492 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Sudoku;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.*;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.*;
public class SudokuFrame extends JFrame {
JTextArea left;
JTextArea right;
JButton check;
JCheckBox autoCheck;
public SudokuFrame() {
super("Sudoku Solver");
JPanel main = new JPanel();
main.setLayout(new BorderLayout(4, 4));
left = new JTextArea(15, 20);
left.setBorder(new TitledBorder("Puzzle"));
main.add(left, BorderLayout.WEST);
right = new JTextArea(15, 20);
right.setBorder(new TitledBorder("Solution"));
main.add(right, BorderLayout.EAST);
JPanel lowerPanel = new JPanel();
lowerPanel.setLayout(new BorderLayout());
check = new JButton("Check");
lowerPanel.add(check, BorderLayout.WEST);
autoCheck = new JCheckBox("Auto Check", true);
lowerPanel.add(autoCheck);
this.add(main);
this.add(lowerPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
addListeners();
}
private void addListeners() {
check.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
updateGUI();
}
});
Document initial = left.getDocument();
initial.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent documentEvent) {
updateGUI();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
updateGUI();
}
@Override
public void changedUpdate(DocumentEvent documentEvent) {
updateGUI();
}
});
}
private void updateGUI() {
String initial = left.getText();
int[][] grid;
try {
grid = Sudoku.textToGrid(initial);
} catch (RuntimeException ex) {
right.setText("Parsing Problem :(");
return;
}
Sudoku board = new Sudoku(grid);
int numSolutions = board.solve();
String solution = board.getSolutionText();
right.setText(solution);
right.append("\nSolutions: " + numSolutions + "\n");
right.append("Time elapsed: " + board.getElapsed() + "ms");
}
public static void main(String[] args) {
// GUI Look And Feel
// Do this incantation at the start of main() to tell Swing
// to use the GUI LookAndFeel of the native platform. It's ok
// to ignore the exception.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) { }
SudokuFrame frame = new SudokuFrame();
}
}
| UTF-8 | Java | 2,530 | java | SudokuFrame.java | Java | [] | null | [] | package Sudoku;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.*;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.*;
public class SudokuFrame extends JFrame {
JTextArea left;
JTextArea right;
JButton check;
JCheckBox autoCheck;
public SudokuFrame() {
super("Sudoku Solver");
JPanel main = new JPanel();
main.setLayout(new BorderLayout(4, 4));
left = new JTextArea(15, 20);
left.setBorder(new TitledBorder("Puzzle"));
main.add(left, BorderLayout.WEST);
right = new JTextArea(15, 20);
right.setBorder(new TitledBorder("Solution"));
main.add(right, BorderLayout.EAST);
JPanel lowerPanel = new JPanel();
lowerPanel.setLayout(new BorderLayout());
check = new JButton("Check");
lowerPanel.add(check, BorderLayout.WEST);
autoCheck = new JCheckBox("Auto Check", true);
lowerPanel.add(autoCheck);
this.add(main);
this.add(lowerPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
addListeners();
}
private void addListeners() {
check.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
updateGUI();
}
});
Document initial = left.getDocument();
initial.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent documentEvent) {
updateGUI();
}
@Override
public void removeUpdate(DocumentEvent documentEvent) {
updateGUI();
}
@Override
public void changedUpdate(DocumentEvent documentEvent) {
updateGUI();
}
});
}
private void updateGUI() {
String initial = left.getText();
int[][] grid;
try {
grid = Sudoku.textToGrid(initial);
} catch (RuntimeException ex) {
right.setText("Parsing Problem :(");
return;
}
Sudoku board = new Sudoku(grid);
int numSolutions = board.solve();
String solution = board.getSolutionText();
right.setText(solution);
right.append("\nSolutions: " + numSolutions + "\n");
right.append("Time elapsed: " + board.getElapsed() + "ms");
}
public static void main(String[] args) {
// GUI Look And Feel
// Do this incantation at the start of main() to tell Swing
// to use the GUI LookAndFeel of the native platform. It's ok
// to ignore the exception.
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) { }
SudokuFrame frame = new SudokuFrame();
}
}
| 2,530 | 0.690909 | 0.686957 | 110 | 22 | 19.558304 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.054545 | false | false | 1 |
f2c3628bab91606c109d631e7dbb88828978d1e5 | 16,879,221,506,735 | f071236d532970a753e4e6ff3c14d214c096a312 | /week3/day2/MapSolution.java | 92adecd193889bc59ffdce555758924c93929dfd | [] | no_license | Dhivya-prabha/SelNovember | https://github.com/Dhivya-prabha/SelNovember | 9aec72f8b8a29ff9863691efd04eada15c9acb9e | 98993db3a51988db5c5f6e0b0152c63a824d22e5 | refs/heads/master | 2020-12-03T18:10:30.953000 | 2020-07-06T10:29:34 | 2020-07-06T10:29:34 | 231,424,579 | 0 | 0 | null | true | 2020-01-02T17:02:32 | 2020-01-02T17:02:31 | 2019-12-30T13:08:42 | 2019-12-30T13:08:40 | 36 | 0 | 0 | 0 | null | false | false | package week3.day2;
import java.util.LinkedHashMap;
import java.util.Map;
public class MapSolution {
public static void main(String[] args) {
// Create a String with your name as value
String name = "Maharajan";
// Convert the string into array
char[] array = name.toCharArray();
// Create an empty map<Character,Integer>
Map<Character,Integer> map = new LinkedHashMap<>();
// Iterate over the array
for (char eachChar : array) {
//if(map.contains(Character))
if(map.containsKey(eachChar)) {
// get the value using key +1
Integer value = map.get(eachChar)+1;
map.put(eachChar, value);
}
else {
// add the character in the map & set the value as 1
map.put(eachChar, 1);
}
}
System.out.println(map);
}
}
| UTF-8 | Java | 832 | java | MapSolution.java | Java | [
{
"context": " String with your name as value\r\n\t\tString name = \"Maharajan\";\r\n\t\t// Convert the string into array\r\n\t\tchar[] a",
"end": 224,
"score": 0.9997413754463196,
"start": 215,
"tag": "NAME",
"value": "Maharajan"
}
] | null | [] | package week3.day2;
import java.util.LinkedHashMap;
import java.util.Map;
public class MapSolution {
public static void main(String[] args) {
// Create a String with your name as value
String name = "Maharajan";
// Convert the string into array
char[] array = name.toCharArray();
// Create an empty map<Character,Integer>
Map<Character,Integer> map = new LinkedHashMap<>();
// Iterate over the array
for (char eachChar : array) {
//if(map.contains(Character))
if(map.containsKey(eachChar)) {
// get the value using key +1
Integer value = map.get(eachChar)+1;
map.put(eachChar, value);
}
else {
// add the character in the map & set the value as 1
map.put(eachChar, 1);
}
}
System.out.println(map);
}
}
| 832 | 0.610577 | 0.603365 | 40 | 18.799999 | 17.187496 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.275 | false | false | 1 |
8288c92d2b5b795dae31c4974646267ad1ce5a2d | 31,602,369,385,401 | 81c01f3fdc998e8fdeb854edfa5fea7fa0a69a9c | /projetos/usaha/tags/0.2.2/src/java/tarefa/relatorio/vo/Relatorio1Sistema.java | 01a1eda09c741ce9fe2819785a1cb6ddabcd0431 | [] | no_license | rwolosker/google | https://github.com/rwolosker/google | dd5eff0d9309a0b8a1217c08141ee9de57f55860 | 6a4ef798e9e617f471db6b5a2a62a26f2484e33b | refs/heads/master | 2018-03-30T12:11:03.859000 | 2015-03-15T03:31:16 | 2015-03-15T03:31:16 | 32,192,546 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /********************************************************************
********************************************************************/
package tarefa.relatorio.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import tarefa.domain.Tarefa;
public class Relatorio1Sistema implements Serializable{
private static final long serialVersionUID=1;
private String nome;
private List<Relatorio1Tarefa>demandas=new ArrayList<Relatorio1Tarefa>();
/*=======================================================
=======================================================*/
public void plus(Tarefa tarefa,int esforco){
Relatorio1Tarefa demanda=new Relatorio1Tarefa();
demanda.setEsforco(esforco);
demanda.setTarefa(tarefa);
demandas.add(demanda);
}
/*=======================================================
=======================================================*/
public int total(){
return demandas.size();
}
/*=======================================================
=======================================================*/
public int totalEsforco(){
int total=0;
for(Relatorio1Tarefa demanda:demandas)
total+=demanda.getEsforco();
return total;
}
/*=======================================================
=======================================================*/
public String getNome(){return nome;}
public void setNome(String nome){this.nome=nome;}
public List<Relatorio1Tarefa> getDemandas(){return demandas;}
public void setDemandas(List<Relatorio1Tarefa> demandas){this.demandas=demandas;}
}
| UTF-8 | Java | 1,625 | java | Relatorio1Sistema.java | Java | [] | null | [] | /********************************************************************
********************************************************************/
package tarefa.relatorio.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import tarefa.domain.Tarefa;
public class Relatorio1Sistema implements Serializable{
private static final long serialVersionUID=1;
private String nome;
private List<Relatorio1Tarefa>demandas=new ArrayList<Relatorio1Tarefa>();
/*=======================================================
=======================================================*/
public void plus(Tarefa tarefa,int esforco){
Relatorio1Tarefa demanda=new Relatorio1Tarefa();
demanda.setEsforco(esforco);
demanda.setTarefa(tarefa);
demandas.add(demanda);
}
/*=======================================================
=======================================================*/
public int total(){
return demandas.size();
}
/*=======================================================
=======================================================*/
public int totalEsforco(){
int total=0;
for(Relatorio1Tarefa demanda:demandas)
total+=demanda.getEsforco();
return total;
}
/*=======================================================
=======================================================*/
public String getNome(){return nome;}
public void setNome(String nome){this.nome=nome;}
public List<Relatorio1Tarefa> getDemandas(){return demandas;}
public void setDemandas(List<Relatorio1Tarefa> demandas){this.demandas=demandas;}
}
| 1,625 | 0.456 | 0.449846 | 48 | 32.854168 | 24.309626 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 1 |
8aa1a0747e135afe2f6937199f3a4b6808d40f57 | 13,331,578,527,929 | 3517d111036aed7ecaaacc708e96d676fd212de1 | /src/main/java/cn/kinkii/novice/framework/entity/LogicalDeleteable.java | 14d3c822392a05300c2aaa92a41ad67ab57d3671 | [] | no_license | TrueOrFalseYuan/novice-boot-framework | https://github.com/TrueOrFalseYuan/novice-boot-framework | 3e4307271b1cf73c73576f372ee68e9876ac6e7c | 6dc47dd26314c6dce042040de052aeb575b98911 | refs/heads/master | 2021-12-03T13:03:42.700000 | 2021-10-19T10:57:26 | 2021-10-19T10:57:26 | 107,101,297 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.kinkii.novice.framework.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
public interface LogicalDeleteable {
@JsonIgnore
String getDelFlag();
@JsonIgnore
String getDelTimeFlag();
}
| UTF-8 | Java | 224 | java | LogicalDeleteable.java | Java | [] | null | [] | package cn.kinkii.novice.framework.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
public interface LogicalDeleteable {
@JsonIgnore
String getDelFlag();
@JsonIgnore
String getDelTimeFlag();
}
| 224 | 0.754464 | 0.754464 | 12 | 17.666666 | 17.622587 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
73cbd777ce9b427ad0d778f373fac9381df8c78d | 2,791,728,772,795 | ab80b9451b1d197e188d9956cd0ec08c68436f07 | /model/src/org/jetbrains/jps/idea/OwnServiceLoader.java | 78cc1d3dc74e03e8a47cbe26a6fa4d996973e731 | [
"Apache-2.0"
] | permissive | JetBrains/JPS | https://github.com/JetBrains/JPS | 79d3648757dfc5ef22f0070b981bee289505d359 | a17bf38a66ae06af1ad65807215d7f24fca3a23b | refs/heads/master | 2023-05-29T09:40:39.467000 | 2023-02-01T14:44:01 | 2023-02-01T14:44:01 | 294,457 | 17 | 8 | null | false | 2012-11-14T12:16:01 | 2009-09-01T16:34:40 | 2012-11-14T12:16:01 | 2012-11-14T12:16:01 | 144 | null | 4 | 0 | Java | null | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.jps.idea;
import java.util.Iterator;
/**
* This class should be used instead of {@link java.util.ServiceLoader} because the standard ServiceLoader
* is not available in JDK 1.5
*
* @author nik
*/
public class OwnServiceLoader<S> implements Iterable<S> {
private Class<S> serviceClass;
private OwnServiceLoader(Class<S> serviceClass) {
this.serviceClass = serviceClass;
}
public static <S> OwnServiceLoader<S> load(Class<S> serviceClass) {
return new OwnServiceLoader<S>(serviceClass);
}
public Iterator<S> iterator() {
return sun.misc.Service.providers(serviceClass);
}
}
| UTF-8 | Java | 751 | java | OwnServiceLoader.java | Java | [
{
"context": "oader\n * is not available in JDK 1.5\n *\n * @author nik\n */\npublic class OwnServiceLoader<S> implements It",
"end": 341,
"score": 0.9807215332984924,
"start": 338,
"tag": "USERNAME",
"value": "nik"
}
] | null | [] | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.jps.idea;
import java.util.Iterator;
/**
* This class should be used instead of {@link java.util.ServiceLoader} because the standard ServiceLoader
* is not available in JDK 1.5
*
* @author nik
*/
public class OwnServiceLoader<S> implements Iterable<S> {
private Class<S> serviceClass;
private OwnServiceLoader(Class<S> serviceClass) {
this.serviceClass = serviceClass;
}
public static <S> OwnServiceLoader<S> load(Class<S> serviceClass) {
return new OwnServiceLoader<S>(serviceClass);
}
public Iterator<S> iterator() {
return sun.misc.Service.providers(serviceClass);
}
}
| 751 | 0.73502 | 0.719041 | 26 | 27.884615 | 32.463383 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.230769 | false | false | 1 |
91c8528e2d961b8915efb963a29e8e18847d1ff6 | 24,833,500,922,260 | 1d96cb341eae5940fca7d4e6156406525c0e60e9 | /src/main/java/com/ti/techmania/glgservice/service/LotService.java | fceb24a5103cf71560e221074dfd289185305579 | [] | no_license | yousingillplay/glgService | https://github.com/yousingillplay/glgService | 2aeda54ff286b7a8b5b792a9b2e9323fd134ca76 | 249ae4eb5f99b3dd701d2b1a63be3359848386d4 | refs/heads/master | 2020-03-28T09:19:27.719000 | 2018-09-13T06:01:08 | 2018-09-13T06:01:08 | 148,029,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //$Id: LotService.java,v 1.3 2012/11/16 22:09:31 a0199948 Exp $
package com.ti.techmania.glgservice.service;
import com.ti.techmania.glgservice.domain.Lot;
import java.util.List;
/**
* Lot service definition. The service layer is where the application's
* business logic resides (business logic and DAO interaction should normally
* not appear in the controller).
* TODO: remove (demonstration only)
*/
public interface LotService {
/**
* Gets the list of lots.
* @param facility The facility identifier.
* @return A List of Lot objects.
*/
List<Lot> getLotList(String facility);
/**
* Gets a particular lot's details.
* @param facility The facility identifier.
* @param lot The lot number.
* @return The Lot object.
*/
Lot getLot(String facility, String lot);
/**
* Updates the lot details.
* @param facility The facility identifier.
* @param lot The lot number.
*/
void setLot(String facility, Lot lot);
/**
* Gets the total number of lots.
* @param facility The facility identifier.
* @return The number of lots.
*/
int getLotTotal(String facility);
/**
* Gets the number of lots that match some search criteria.
* @param facility The facility identifier.
* @param lotSearch The lot search string
* @param lptSearch The logpoint search string
* @param qtySearch The quantity search string
* @return The number of lots.
*/
int getMatchingLotTotal(String facility,
String lotSearch, String lptSearch, String qtySearch);
/**
* Returns a subset of the lots that match some search criteria.
* @param facility The facility identifier.
* @param start The first row from the matching lots to return
* @param length The number of rows from the matching lots to return
* @param sortCol The column to sort the results by
* @param sortDir Either "asc" or "desc" for ascending or descending sort
* @param lotSearch The lot search string
* @param lptSearch The logpoint search string
* @param qtySearch The quantity search string
* @return The number of lots.
*/
List<Lot> getMatchingLots(String facility, int start,
int length, int sortCol, String sortDir, String lotSearch,
String lptSearch, String qtySearch);
}
| UTF-8 | Java | 2,378 | java | LotService.java | Java | [] | null | [] | //$Id: LotService.java,v 1.3 2012/11/16 22:09:31 a0199948 Exp $
package com.ti.techmania.glgservice.service;
import com.ti.techmania.glgservice.domain.Lot;
import java.util.List;
/**
* Lot service definition. The service layer is where the application's
* business logic resides (business logic and DAO interaction should normally
* not appear in the controller).
* TODO: remove (demonstration only)
*/
public interface LotService {
/**
* Gets the list of lots.
* @param facility The facility identifier.
* @return A List of Lot objects.
*/
List<Lot> getLotList(String facility);
/**
* Gets a particular lot's details.
* @param facility The facility identifier.
* @param lot The lot number.
* @return The Lot object.
*/
Lot getLot(String facility, String lot);
/**
* Updates the lot details.
* @param facility The facility identifier.
* @param lot The lot number.
*/
void setLot(String facility, Lot lot);
/**
* Gets the total number of lots.
* @param facility The facility identifier.
* @return The number of lots.
*/
int getLotTotal(String facility);
/**
* Gets the number of lots that match some search criteria.
* @param facility The facility identifier.
* @param lotSearch The lot search string
* @param lptSearch The logpoint search string
* @param qtySearch The quantity search string
* @return The number of lots.
*/
int getMatchingLotTotal(String facility,
String lotSearch, String lptSearch, String qtySearch);
/**
* Returns a subset of the lots that match some search criteria.
* @param facility The facility identifier.
* @param start The first row from the matching lots to return
* @param length The number of rows from the matching lots to return
* @param sortCol The column to sort the results by
* @param sortDir Either "asc" or "desc" for ascending or descending sort
* @param lotSearch The lot search string
* @param lptSearch The logpoint search string
* @param qtySearch The quantity search string
* @return The number of lots.
*/
List<Lot> getMatchingLots(String facility, int start,
int length, int sortCol, String sortDir, String lotSearch,
String lptSearch, String qtySearch);
}
| 2,378 | 0.671573 | 0.661901 | 71 | 32.492958 | 23.456205 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.309859 | false | false | 1 |
6fdb44d352bc1030572965e2723bb1d7b93cce26 | 11,269,994,215,269 | 86fe502a443bc97883ca301d1f80e0434801a8c1 | /checkstand-service/src/main/java/com/cloudwing/checkstand/user/service/impl/UserServiceImpl.java | d69c76ec61a98295dc30825e5791948eac318cd1 | [] | no_license | rain13798668961/cloudwing-checkstand | https://github.com/rain13798668961/cloudwing-checkstand | 792b51840380e99657a44d92e06b420175e890ab | 56cc38e544346833e080056ce124a8ee65b91ee6 | refs/heads/master | 2020-04-25T14:02:56.697000 | 2019-02-27T03:07:47 | 2019-02-27T03:07:47 | 172,828,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cloudwing.checkstand.user.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.cloudwing.checkstand.common.enums.PlatformRoleEnum;
import com.cloudwing.checkstand.common.enums.RoleEnum;
import com.cloudwing.checkstand.company.entity.Company;
import com.cloudwing.checkstand.company.service.CompanyService;
import com.cloudwing.checkstand.consumer.platform.beans.UserDetail;
import com.cloudwing.checkstand.common.enums.BaseStatusEnum;
import com.cloudwing.checkstand.common.exception.ValidateException;
import com.cloudwing.checkstand.merchant.mapper.MerchantMapper;
import com.cloudwing.checkstand.office.mapper.OfficeMapper;
import com.cloudwing.checkstand.office.service.impl.OfficeManager;
import com.cloudwing.checkstand.permission.entity.Permission;
import com.cloudwing.checkstand.permission.mapper.PermissionMapper;
import com.cloudwing.checkstand.permission.mapper.RoleMapper;
import cn.hutool.core.bean.BeanUtil;
import com.cloudwing.checkstand.common.result.BaseResult;
import com.cloudwing.checkstand.common.utils.UserHelper;
import com.cloudwing.checkstand.company.service.impl.CompanyManager;
import com.cloudwing.checkstand.permission.service.RoleService;
import com.cloudwing.checkstand.permission.service.impl.RoleManager;
import com.cloudwing.checkstand.user.entity.UserRole;
import com.cloudwing.checkstand.user.mapper.UserOfficeMapper;
import com.cloudwing.checkstand.user.mapper.UserRoleMapper;
import com.cloudwing.checkstand.user.vo.UserEmpowerVo;
import com.cloudwing.checkstand.user.vo.UserQueryVo;
import com.cloudwing.checkstand.user.dto.RadioDto;
import com.cloudwing.checkstand.user.entity.User;
import com.cloudwing.checkstand.user.mapper.UserMapper;
import com.cloudwing.checkstand.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunyitg.rpc.base.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@Service
public class UserServiceImpl implements UserService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserMapper userMapper;
@Autowired
private CompanyManager companyManager;
@Autowired
private CompanyService companyService;
@Autowired
private RoleService roleService;
@Autowired
private RoleManager roleManager;
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private OfficeMapper officeMapper;
@Autowired
private OfficeManager officeManager;
@Autowired
private PermissionMapper permissionMapper;
@Autowired
private MerchantMapper merchantMapper;
@Autowired
private UserOfficeMapper userOfficeMapper;
@Autowired
private com.cloudwing.checkstand.consumer.platform.UserService platformUserService;
@Override
public User login(String account, String password) {
return userMapper.findByAccountAndPassword(account, password);
}
@Override
@Transactional
public User platformLogin(String token, String appSessKey) throws InterruptedException,ExecutionException,TimeoutException,RpcException {
String jsonInfo = platformUserService.authToken(token);
if (!"false".equals(jsonInfo)) {
JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
String platUserId = jsonObject.getString("user_id");
String platServiceId = jsonObject.getString("service_id");
String platSessionId = jsonObject.getString("sessionid");
String platAppSessKey = jsonObject.getString("app_sess_key");
if (!appSessKey.equals(platAppSessKey)) { // appSessKey不匹配
log.info("平台用户服务ahthToken方法中app_sess_key匹配失败");
return null;
}
User u = userMapper.findByPlatformUserId(Integer.valueOf(platUserId));
if (u == null) { //用户不存在本应用
UserDetail userDetail = platformUserService.getUserInfo(Integer.valueOf(platUserId));
Company company = companyService.lookupByPlatformCompanyId(userDetail.getCompany_id());
User newUser = exchangeToUser(userDetail, company.getId());
userMapper.insert(newUser);
//新用户赋予角色
configureUserRole(newUser.getId(), userDetail.getRole_code());
newUser.setSessionid(platSessionId);
return newUser;
} else {
u.setSessionid(platSessionId);
return u;
}
} else {
return null;
}
}
private void configureUserRole(Integer userId, String platformUserRole) {
UserRole userRole = new UserRole();
userRole.setUid(userId);
//超级平台管理员和平台管理员
if(PlatformRoleEnum.PLATFORMADMIN.getCode().equals(platformUserRole) ||
PlatformRoleEnum.PLATFORMORDINARY.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.SuperAdmin.getCode()).getId());
}
// 主账号(企业管理员)
else if(PlatformRoleEnum.ADMIN.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.Admin.getCode()).getId());
}
// 普通账号(企业操作员)
else if (PlatformRoleEnum.ORDINARY.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.OfficeOperator.getCode()).getId());
} else {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.Obeserver.getCode()).getId());
}
userRoleMapper.insert(userRole);
}
private User exchangeToUser(UserDetail userDetail, Integer companyId) {
User u = new User();
u.setCompanyId(companyId);
u.setPlatformUserId(userDetail.getId());
u.setPlatformCompanyId(Integer.valueOf(userDetail.getCompany_id()));
u.setRoleId(Integer.valueOf(userDetail.getRole_id()));
u.setName(userDetail.getName());
u.setAccount(userDetail.getAccount());
u.setPhone(userDetail.getPhone());
u.setEmail(userDetail.getEmail());
u.setAvatar(userDetail.getAvatar());
u.setAvatarType(userDetail.getAvatar_type());
u.setStatus(userDetail.getStatus());
// u.setNote(userDetail.getN);
return u;
}
@Override
public Set<String> listRolesByUserId(Integer userId) {
return roleMapper.listCodeByUserId(userId);
}
@Override
public Set<String> listPermissionsByUserId(User user) {
// 若用户拥有超级管理员角色,用户拥有该系统所有权限
if (UserHelper.hasSuperAdminRoles(user.getRoles())) {
log.info("当前用户为超级管理员,用户id:" + user.getId());
List<Permission> perms = permissionMapper.selectAll();
Set<String> permUrls = new HashSet<String>();
for (Permission p : perms) {
if (null != p.getUrl())
permUrls.add(p.getUrl());
}
return permUrls;
}
return permissionMapper.listUrlByUserId(user.getId());
}
@Override
public int updateById(User user) {
return userMapper.updateByPrimaryKeySelective(user);
}
public BaseResult<PageInfo<UserQueryVo>> listPage(User user, int page, int limit) {
Set<String> roles = user.getRoles();
PageInfo<UserQueryVo> userPageInfo;
List<UserQueryVo> userQueryVos = new ArrayList<>();
if (UserHelper.hasSuperAdminRoles(roles)) { //超级管理员
// 获取所有用户数据
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVo();
userPageInfo = new PageInfo<>(userQueryVos);
} else if (UserHelper.hasAdminRoles(roles)) { //管理员
// 获取对应企业下的所有用户数据
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVoByCompanyId(user.getCompanyId());
userPageInfo = new PageInfo<>(userQueryVos);
} else if (UserHelper.hasOfficeLeaderRoles(roles)) { // 现场负责人
// 获取所属现场所有用户数据
Integer[] oids = userOfficeMapper.selectOidByUid(user.getId());
Integer[] uids = userOfficeMapper.selectUidByOid(oids);
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVoByUid(uids);
userPageInfo = new PageInfo<>(userQueryVos);
} else { //操作员 or 观察者
// 获取自己的数据
userQueryVos.add(userMapper.getUserQueryVoById(user.getId()));
userPageInfo = new PageInfo<>(userQueryVos);
}
log.info("userPageInfo分页数据: " + userPageInfo);
return new BaseResult<PageInfo<UserQueryVo>>(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), userPageInfo);
}
@Override
public BaseResult updateStatusById(Integer id, String status) {
User user = new User();
user.setId(id);
user.setStatus(status);
int resultStatus = userMapper.updateByPrimaryKeySelective(user);
if (resultStatus == 1) {
return new BaseResult(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), null);
}
return new BaseResult(BaseStatusEnum.FAILED.getStatus(), BaseStatusEnum.FAILED.getMsg(), null);
}
@Override
public BaseResult<PageInfo<UserEmpowerVo>> listOperate(Integer userId, Integer companyId, int page, int limit) {
PageInfo<UserEmpowerVo> userEmpowerVoPageInfo;
PageHelper.startPage(page, limit);
List<UserEmpowerVo> userEmpowerVos = officeMapper.listUserEmpowerVosByUserIdAndCompanyId(userId, companyId);
for (UserEmpowerVo userEmpowerVo : userEmpowerVos) {
userEmpowerVo.setCompanyName(companyManager.getCompanyNameById(userEmpowerVo.getCompanyId()));
}
userEmpowerVoPageInfo = new PageInfo<>(userEmpowerVos);
log.info("userEmpowerVoPageInfo分页数据: " + userEmpowerVoPageInfo);
return new BaseResult<PageInfo<UserEmpowerVo>>(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), userEmpowerVoPageInfo);
}
@Override
public BaseResult operateUpdateByOfficeIdAndChecked(Integer userId, Integer officeId, boolean checked) {
int resultStatus = 0;
if (checked) {
resultStatus = userOfficeMapper.saveByUserIdAndOfficeId(userId, officeId);
} else {
resultStatus = userOfficeMapper.removeByUserIdAndOfficeId(userId, officeId);
}
if (resultStatus == 1) {
return new BaseResult(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), null);
}
return new BaseResult(BaseStatusEnum.FAILED.getStatus(), BaseStatusEnum.FAILED.getMsg(), null);
}
/**
* 将数据库表Bean转换为返回前端时的Bean
* @param userList
* @return
*/
public List<UserQueryVo> userToUserQueryVo (List<User> userList) {
List<UserQueryVo> userQueryVoList = new ArrayList<>();
if (null != userList && userList.size() != 0) {
for (User user : userList) {
UserQueryVo userQueryVo = BeanUtil.toBean(user, UserQueryVo.class);
userQueryVo.setCompanyName(companyManager.getCompanyNameById(userQueryVo.getCompanyId()));
// userQueryVo.setPassword(null);// 密码不返回
userQueryVo.setDescription(roleService.roleDescriptionByUserId(userQueryVo.getId()));
userQueryVoList.add(userQueryVo);
}
return userQueryVoList;
}
return null;
}
@Override
public List<RadioDto> listOfficeByUserId(Integer userId) {
return officeMapper.listCodeAndNameByUserId(userId);
}
@Override
public List<RadioDto> listMerchantByUserIdAndOfficeId(String officeCode) {
Integer officeId = officeManager.getIdByCode(officeCode);
return merchantMapper.listCodeAndNameByOfficeId(officeId);
}
}
| UTF-8 | Java | 12,764 | java | UserServiceImpl.java | Java | [] | null | [] | package com.cloudwing.checkstand.user.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.cloudwing.checkstand.common.enums.PlatformRoleEnum;
import com.cloudwing.checkstand.common.enums.RoleEnum;
import com.cloudwing.checkstand.company.entity.Company;
import com.cloudwing.checkstand.company.service.CompanyService;
import com.cloudwing.checkstand.consumer.platform.beans.UserDetail;
import com.cloudwing.checkstand.common.enums.BaseStatusEnum;
import com.cloudwing.checkstand.common.exception.ValidateException;
import com.cloudwing.checkstand.merchant.mapper.MerchantMapper;
import com.cloudwing.checkstand.office.mapper.OfficeMapper;
import com.cloudwing.checkstand.office.service.impl.OfficeManager;
import com.cloudwing.checkstand.permission.entity.Permission;
import com.cloudwing.checkstand.permission.mapper.PermissionMapper;
import com.cloudwing.checkstand.permission.mapper.RoleMapper;
import cn.hutool.core.bean.BeanUtil;
import com.cloudwing.checkstand.common.result.BaseResult;
import com.cloudwing.checkstand.common.utils.UserHelper;
import com.cloudwing.checkstand.company.service.impl.CompanyManager;
import com.cloudwing.checkstand.permission.service.RoleService;
import com.cloudwing.checkstand.permission.service.impl.RoleManager;
import com.cloudwing.checkstand.user.entity.UserRole;
import com.cloudwing.checkstand.user.mapper.UserOfficeMapper;
import com.cloudwing.checkstand.user.mapper.UserRoleMapper;
import com.cloudwing.checkstand.user.vo.UserEmpowerVo;
import com.cloudwing.checkstand.user.vo.UserQueryVo;
import com.cloudwing.checkstand.user.dto.RadioDto;
import com.cloudwing.checkstand.user.entity.User;
import com.cloudwing.checkstand.user.mapper.UserMapper;
import com.cloudwing.checkstand.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunyitg.rpc.base.exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Set;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@Service
public class UserServiceImpl implements UserService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserMapper userMapper;
@Autowired
private CompanyManager companyManager;
@Autowired
private CompanyService companyService;
@Autowired
private RoleService roleService;
@Autowired
private RoleManager roleManager;
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private OfficeMapper officeMapper;
@Autowired
private OfficeManager officeManager;
@Autowired
private PermissionMapper permissionMapper;
@Autowired
private MerchantMapper merchantMapper;
@Autowired
private UserOfficeMapper userOfficeMapper;
@Autowired
private com.cloudwing.checkstand.consumer.platform.UserService platformUserService;
@Override
public User login(String account, String password) {
return userMapper.findByAccountAndPassword(account, password);
}
@Override
@Transactional
public User platformLogin(String token, String appSessKey) throws InterruptedException,ExecutionException,TimeoutException,RpcException {
String jsonInfo = platformUserService.authToken(token);
if (!"false".equals(jsonInfo)) {
JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
String platUserId = jsonObject.getString("user_id");
String platServiceId = jsonObject.getString("service_id");
String platSessionId = jsonObject.getString("sessionid");
String platAppSessKey = jsonObject.getString("app_sess_key");
if (!appSessKey.equals(platAppSessKey)) { // appSessKey不匹配
log.info("平台用户服务ahthToken方法中app_sess_key匹配失败");
return null;
}
User u = userMapper.findByPlatformUserId(Integer.valueOf(platUserId));
if (u == null) { //用户不存在本应用
UserDetail userDetail = platformUserService.getUserInfo(Integer.valueOf(platUserId));
Company company = companyService.lookupByPlatformCompanyId(userDetail.getCompany_id());
User newUser = exchangeToUser(userDetail, company.getId());
userMapper.insert(newUser);
//新用户赋予角色
configureUserRole(newUser.getId(), userDetail.getRole_code());
newUser.setSessionid(platSessionId);
return newUser;
} else {
u.setSessionid(platSessionId);
return u;
}
} else {
return null;
}
}
private void configureUserRole(Integer userId, String platformUserRole) {
UserRole userRole = new UserRole();
userRole.setUid(userId);
//超级平台管理员和平台管理员
if(PlatformRoleEnum.PLATFORMADMIN.getCode().equals(platformUserRole) ||
PlatformRoleEnum.PLATFORMORDINARY.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.SuperAdmin.getCode()).getId());
}
// 主账号(企业管理员)
else if(PlatformRoleEnum.ADMIN.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.Admin.getCode()).getId());
}
// 普通账号(企业操作员)
else if (PlatformRoleEnum.ORDINARY.getCode().equals(platformUserRole)) {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.OfficeOperator.getCode()).getId());
} else {
userRole.setRid(roleManager.getCodeMapRole().get(RoleEnum.Obeserver.getCode()).getId());
}
userRoleMapper.insert(userRole);
}
private User exchangeToUser(UserDetail userDetail, Integer companyId) {
User u = new User();
u.setCompanyId(companyId);
u.setPlatformUserId(userDetail.getId());
u.setPlatformCompanyId(Integer.valueOf(userDetail.getCompany_id()));
u.setRoleId(Integer.valueOf(userDetail.getRole_id()));
u.setName(userDetail.getName());
u.setAccount(userDetail.getAccount());
u.setPhone(userDetail.getPhone());
u.setEmail(userDetail.getEmail());
u.setAvatar(userDetail.getAvatar());
u.setAvatarType(userDetail.getAvatar_type());
u.setStatus(userDetail.getStatus());
// u.setNote(userDetail.getN);
return u;
}
@Override
public Set<String> listRolesByUserId(Integer userId) {
return roleMapper.listCodeByUserId(userId);
}
@Override
public Set<String> listPermissionsByUserId(User user) {
// 若用户拥有超级管理员角色,用户拥有该系统所有权限
if (UserHelper.hasSuperAdminRoles(user.getRoles())) {
log.info("当前用户为超级管理员,用户id:" + user.getId());
List<Permission> perms = permissionMapper.selectAll();
Set<String> permUrls = new HashSet<String>();
for (Permission p : perms) {
if (null != p.getUrl())
permUrls.add(p.getUrl());
}
return permUrls;
}
return permissionMapper.listUrlByUserId(user.getId());
}
@Override
public int updateById(User user) {
return userMapper.updateByPrimaryKeySelective(user);
}
public BaseResult<PageInfo<UserQueryVo>> listPage(User user, int page, int limit) {
Set<String> roles = user.getRoles();
PageInfo<UserQueryVo> userPageInfo;
List<UserQueryVo> userQueryVos = new ArrayList<>();
if (UserHelper.hasSuperAdminRoles(roles)) { //超级管理员
// 获取所有用户数据
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVo();
userPageInfo = new PageInfo<>(userQueryVos);
} else if (UserHelper.hasAdminRoles(roles)) { //管理员
// 获取对应企业下的所有用户数据
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVoByCompanyId(user.getCompanyId());
userPageInfo = new PageInfo<>(userQueryVos);
} else if (UserHelper.hasOfficeLeaderRoles(roles)) { // 现场负责人
// 获取所属现场所有用户数据
Integer[] oids = userOfficeMapper.selectOidByUid(user.getId());
Integer[] uids = userOfficeMapper.selectUidByOid(oids);
PageHelper.startPage(page, limit).setOrderBy("id desc");
userQueryVos = userMapper.listUserQueryVoByUid(uids);
userPageInfo = new PageInfo<>(userQueryVos);
} else { //操作员 or 观察者
// 获取自己的数据
userQueryVos.add(userMapper.getUserQueryVoById(user.getId()));
userPageInfo = new PageInfo<>(userQueryVos);
}
log.info("userPageInfo分页数据: " + userPageInfo);
return new BaseResult<PageInfo<UserQueryVo>>(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), userPageInfo);
}
@Override
public BaseResult updateStatusById(Integer id, String status) {
User user = new User();
user.setId(id);
user.setStatus(status);
int resultStatus = userMapper.updateByPrimaryKeySelective(user);
if (resultStatus == 1) {
return new BaseResult(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), null);
}
return new BaseResult(BaseStatusEnum.FAILED.getStatus(), BaseStatusEnum.FAILED.getMsg(), null);
}
@Override
public BaseResult<PageInfo<UserEmpowerVo>> listOperate(Integer userId, Integer companyId, int page, int limit) {
PageInfo<UserEmpowerVo> userEmpowerVoPageInfo;
PageHelper.startPage(page, limit);
List<UserEmpowerVo> userEmpowerVos = officeMapper.listUserEmpowerVosByUserIdAndCompanyId(userId, companyId);
for (UserEmpowerVo userEmpowerVo : userEmpowerVos) {
userEmpowerVo.setCompanyName(companyManager.getCompanyNameById(userEmpowerVo.getCompanyId()));
}
userEmpowerVoPageInfo = new PageInfo<>(userEmpowerVos);
log.info("userEmpowerVoPageInfo分页数据: " + userEmpowerVoPageInfo);
return new BaseResult<PageInfo<UserEmpowerVo>>(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), userEmpowerVoPageInfo);
}
@Override
public BaseResult operateUpdateByOfficeIdAndChecked(Integer userId, Integer officeId, boolean checked) {
int resultStatus = 0;
if (checked) {
resultStatus = userOfficeMapper.saveByUserIdAndOfficeId(userId, officeId);
} else {
resultStatus = userOfficeMapper.removeByUserIdAndOfficeId(userId, officeId);
}
if (resultStatus == 1) {
return new BaseResult(BaseStatusEnum.SUCCESS.getStatus(), BaseStatusEnum.SUCCESS.getMsg(), null);
}
return new BaseResult(BaseStatusEnum.FAILED.getStatus(), BaseStatusEnum.FAILED.getMsg(), null);
}
/**
* 将数据库表Bean转换为返回前端时的Bean
* @param userList
* @return
*/
public List<UserQueryVo> userToUserQueryVo (List<User> userList) {
List<UserQueryVo> userQueryVoList = new ArrayList<>();
if (null != userList && userList.size() != 0) {
for (User user : userList) {
UserQueryVo userQueryVo = BeanUtil.toBean(user, UserQueryVo.class);
userQueryVo.setCompanyName(companyManager.getCompanyNameById(userQueryVo.getCompanyId()));
// userQueryVo.setPassword(null);// 密码不返回
userQueryVo.setDescription(roleService.roleDescriptionByUserId(userQueryVo.getId()));
userQueryVoList.add(userQueryVo);
}
return userQueryVoList;
}
return null;
}
@Override
public List<RadioDto> listOfficeByUserId(Integer userId) {
return officeMapper.listCodeAndNameByUserId(userId);
}
@Override
public List<RadioDto> listMerchantByUserIdAndOfficeId(String officeCode) {
Integer officeId = officeManager.getIdByCode(officeCode);
return merchantMapper.listCodeAndNameByOfficeId(officeId);
}
}
| 12,764 | 0.694575 | 0.69409 | 295 | 40.986443 | 31.250109 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.654237 | false | false | 1 |
0ce4a4bb3e1db52238248e71f2b191031e8b9c26 | 16,363,825,432,163 | 45415130204c50eef3e31d9147771ee4c0b3e2b3 | /com/netflix/model/branches/FalkorKidsCharacter$1.java | 3e8f1522adf552556b38674244be9d9f1c2d724e | [] | no_license | codacy-badger/evolucionNetflix | https://github.com/codacy-badger/evolucionNetflix | 928075e45b25df1d11abd9cb98354d76077fdbd6 | ae966d9f0efb42e00dd9978d73b4b5ecaf665e75 | refs/heads/master | 2018-04-16T19:08:18.226000 | 2017-05-07T16:54:28 | 2017-05-07T16:54:28 | 90,551,432 | 0 | 0 | null | true | 2017-05-07T17:58:25 | 2017-05-07T17:58:25 | 2017-05-07T03:20:55 | 2017-05-07T16:54:35 | 19,643 | 0 | 0 | 0 | null | null | null | //
// Decompiled by Procyon v0.5.30
//
package com.netflix.model.branches;
import java.util.Comparator;
final class FalkorKidsCharacter$1 implements Comparator<FalkorVideo>
{
@Override
public int compare(final FalkorVideo falkorVideo, final FalkorVideo falkorVideo2) {
if (falkorVideo.getYear() < falkorVideo2.getYear()) {
return 1;
}
if (falkorVideo.getYear() > falkorVideo2.getYear()) {
return -1;
}
return 0;
}
}
| UTF-8 | Java | 497 | java | FalkorKidsCharacter$1.java | Java | [] | null | [] | //
// Decompiled by Procyon v0.5.30
//
package com.netflix.model.branches;
import java.util.Comparator;
final class FalkorKidsCharacter$1 implements Comparator<FalkorVideo>
{
@Override
public int compare(final FalkorVideo falkorVideo, final FalkorVideo falkorVideo2) {
if (falkorVideo.getYear() < falkorVideo2.getYear()) {
return 1;
}
if (falkorVideo.getYear() > falkorVideo2.getYear()) {
return -1;
}
return 0;
}
}
| 497 | 0.637827 | 0.615694 | 21 | 22.666666 | 25.325186 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 1 |
b9fc7f52dbb1f4ae9284801606be771def9240c7 | 25,039,659,376,411 | d0832697580377d470037aaa43618af94a8f4177 | /health_interface/src/main/java/cn/itcast/service/OrderService.java | 280638d83253a9a695d7d451c136e8c86d8521d3 | [] | no_license | zlzong/repo1 | https://github.com/zlzong/repo1 | beacc15e2116e7e917a5c10421fc964fba13c45a | b9a81772fb965caafed453ac12acd3015692c099 | refs/heads/master | 2022-12-24T05:40:12.431000 | 2020-04-18T06:50:38 | 2020-04-18T06:50:38 | 234,026,003 | 1 | 0 | null | false | 2022-12-16T04:29:50 | 2020-01-15T07:43:43 | 2020-04-18T06:50:50 | 2022-12-16T04:29:47 | 191,411 | 1 | 0 | 15 | JavaScript | false | false | package cn.itcast.service;
import java.util.Map;
public interface OrderService {
public String submit(Map map) throws Exception;
public Map findById(String id);
}
| UTF-8 | Java | 183 | java | OrderService.java | Java | [] | null | [] | package cn.itcast.service;
import java.util.Map;
public interface OrderService {
public String submit(Map map) throws Exception;
public Map findById(String id);
}
| 183 | 0.710383 | 0.710383 | 9 | 18.333334 | 17.888544 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 1 |
8eccc6bdf5327d9f8acacf5d7dbb6286f6c8a54b | 15,934,328,702,398 | 57e6bd515aa53ad4d95f05d92f5fe98f00d294a9 | /src/main/java/org/jimkast/http/adapters/SunHandler.java | bf49e647b5a6d77896a702cb58795ef6830fa37e | [] | no_license | jimkast/httpio | https://github.com/jimkast/httpio | 6167541d818afa7bbc798891d503a316bd1a0e09 | 76d8b3c4170762df40ada971759277c6034a36b2 | refs/heads/master | 2020-03-21T20:49:12.352000 | 2018-07-20T08:58:28 | 2018-07-20T08:58:28 | 139,030,459 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jimkast.http.adapters;
import java.io.IOException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jimkast.http.HttpServerMapping;
public final class SunHandler implements HttpHandler {
private final HttpServerMapping mapping;
public SunHandler(HttpServerMapping mapping) {
this.mapping = mapping;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
new RsSun(mapping.exchange(new RqSun(exchange))).apply(exchange);
}
}
| UTF-8 | Java | 549 | java | SunHandler.java | Java | [] | null | [] | package org.jimkast.http.adapters;
import java.io.IOException;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.jimkast.http.HttpServerMapping;
public final class SunHandler implements HttpHandler {
private final HttpServerMapping mapping;
public SunHandler(HttpServerMapping mapping) {
this.mapping = mapping;
}
@Override
public void handle(HttpExchange exchange) throws IOException {
new RsSun(mapping.exchange(new RqSun(exchange))).apply(exchange);
}
}
| 549 | 0.757741 | 0.757741 | 19 | 27.894737 | 23.726278 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 1 |
fccfefd1eaefde3d80a2937365b72778953b1a13 | 29,085,518,531,205 | 15161224a30ebcf6f6df9ac81fe8ce620e30ba94 | /java_programs/src/fw/dd/CsvFiles/Write_Data_To_CsvFiles.java | ce8ba0cf028dc62a243b1fd61715fd5c18939d13 | [] | no_license | namratha-p/programs | https://github.com/namratha-p/programs | 2a99e0acd7a31bf604be6ef1bcb58174f8eb5cae | 224b5514e7252e572fa22279c34c1079dd6f5872 | refs/heads/master | 2021-03-11T23:55:59.023000 | 2020-03-11T14:27:55 | 2020-03-11T14:27:55 | 246,571,956 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fw.dd.CsvFiles;
import java.io.FileWriter;
import com.opencsv.CSVWriter;
public class Write_Data_To_CsvFiles {
public static void main(String[] args) throws Exception
{
FileWriter fw=new FileWriter("C:\\Users\\mithr\\OneDrive\\Desktop\\csv_output.csv");
CSVWriter writer=new CSVWriter(fw);
String line1[]= {"result1","testpass"};
writer.writeNext(line1);
String line2[]= {"result2","testpass"};
writer.writeNext(line2);
writer.close();
}
}
| UTF-8 | Java | 528 | java | Write_Data_To_CsvFiles.java | Java | [
{
"context": " \r\n\t{\r\n\t\tFileWriter fw=new FileWriter(\"C:\\\\Users\\\\mithr\\\\OneDrive\\\\Desktop\\\\csv_output.csv\");\r\n\t\tCSVWrite",
"end": 246,
"score": 0.5849224925041199,
"start": 241,
"tag": "USERNAME",
"value": "mithr"
}
] | null | [] | package fw.dd.CsvFiles;
import java.io.FileWriter;
import com.opencsv.CSVWriter;
public class Write_Data_To_CsvFiles {
public static void main(String[] args) throws Exception
{
FileWriter fw=new FileWriter("C:\\Users\\mithr\\OneDrive\\Desktop\\csv_output.csv");
CSVWriter writer=new CSVWriter(fw);
String line1[]= {"result1","testpass"};
writer.writeNext(line1);
String line2[]= {"result2","testpass"};
writer.writeNext(line2);
writer.close();
}
}
| 528 | 0.636364 | 0.625 | 29 | 16.068966 | 21.161011 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.517241 | false | false | 0 |
94d5f9c04de51c442e41b9df61597cd48515a84e | 21,388,937,166,378 | 1e94cc11c3beef0791cdd39aa0003a05dbd62ff1 | /garden-jpg-lib/src/main/java/org/m410/garden/module/ormbuilder/orm/OneToMany.java | 3579eed3edc22f716a52b31409d7ccbe683bdcda | [
"Apache-2.0"
] | permissive | m410/garden | https://github.com/m410/garden | 1267fd0c44756601b211725c3c15630d361447d0 | 36d87bf4f3d598ed6c06ac1ea1955769cd5cea6e | refs/heads/master | 2021-01-10T19:03:48.395000 | 2021-01-10T16:15:54 | 2021-01-10T16:15:54 | 14,930,246 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.m410.garden.module.ormbuilder.orm;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <pre>
*
* <xsd:annotationgt;
* <xsd:documentationgt;
* Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface OneToMany {
* Class targetEntity() default void.class;
* CascadeType[] cascade() default {};
* FetchType fetch() default LAZY;
* String mappedBy() default ""; }
* </xsd:documentationgt;
* </xsd:annotationgt;
* <xsd:sequencegt;
* <xsd:choicegt;
* <xsd:element name="order-by" type="orm:order-by" minOccurs="0" /gt;
* <xsd:element name="order-column" type="orm:order-column" minOccurs="0" /gt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="map-key" type="orm:map-key" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-class" type="orm:map-key-class" minOccurs="0" /gt;
* <xsd:choicegt;
* <xsd:element name="map-key-temporal" type="orm:temporal" minOccurs="0" /gt;
* <xsd:element name="map-key-enumerated" type="orm:enumerated" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-attribute-override" type="orm:attribute-override" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="map-key-convert" type="orm:convert" minOccurs="0" maxOccurs="unbounded" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="map-key-column" type="orm:map-key-column" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-join-column" type="orm:map-key-join-column" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="map-key-foreign-key" type="orm:foreign-key" minOccurs="0" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="join-table" type="orm:join-table" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="join-column" type="orm:join-column" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="foreign-key" type="orm:foreign-key" minOccurs="0" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:element name="cascade" type="orm:cascade-type" minOccurs="0" /gt;
* </xsd:sequencegt;
* <xsd:attribute name="name" type="xsd:string" use="required" /gt;
* <xsd:attribute name="target-entity" type="xsd:string" /gt;
* <xsd:attribute name="fetch" type="orm:fetch-type" /gt;
* <xsd:attribute name="access" type="orm:access-type" /gt;
* <xsd:attribute name="mapped-by" type="xsd:string" /gt;
* <xsd:attribute name="orphan-removal" type="xsd:boolean" /gt;
*
* </pre>
*
* @author m410
*/
public final class OneToMany extends Node {
private String name;
private String mappedBy = "";
private ORM.Cascade[] cascade = {};// should be enum
private ORM.Fetch fetch = ORM.Fetch.LAZY; // should be enum
private Class targetEntity = void.class;
private boolean orphanRemoval = true;
private ORM.Access access = null;
public OneToMany() {
super(2, 6);
}
public <T> OneToMany(String name, Class<T> targetEntity, String mappedBy) {
this();
this.name = name;
this.targetEntity = targetEntity;
this.mappedBy = mappedBy;
}
public <T> OneToMany(String name, Class<T> targetEntity) {
this();
this.name = name;
this.targetEntity = targetEntity;
}
public OneToMany(String name, String mappedBy, ORM.Cascade[] cascade, ORM.Fetch fetch,
Class targetEntity, boolean orphanRemoval) {
this();
this.name = name;
this.mappedBy = mappedBy;
this.cascade = cascade;
this.fetch = fetch;
this.targetEntity = targetEntity;
this.orphanRemoval = orphanRemoval;
}
@Override
public void appendElement(Document root, Element parent) {
Element id = root.createElement("one-to-many");
id.setAttribute("name", name);
if(targetEntity != void.class)
id.setAttribute("target-entity", targetEntity.getName());
id.setAttribute("fetch", fetch.toString());
if (access != null)
id.setAttribute("access", access.toString());
if(!"".equals(mappedBy))
id.setAttribute("mapped-by", mappedBy);
id.setAttribute("orphan-removal", String.valueOf(orphanRemoval));
// children
// foreignKey,joinTable,joinColumn,orderBy,orderColumn, etc
children.stream().forEach(n -> n.appendElement(root, id));
parent.appendChild(id);
}
}
| UTF-8 | Java | 4,816 | java | OneToMany.java | Java | [
{
"context": "type=\"xsd:boolean\" /gt;\n *\n * </pre>\n *\n * @author m410\n */\npublic final class OneToMany extends Node {\n ",
"end": 2884,
"score": 0.9993407726287842,
"start": 2880,
"tag": "USERNAME",
"value": "m410"
}
] | null | [] | package org.m410.garden.module.ormbuilder.orm;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <pre>
*
* <xsd:annotationgt;
* <xsd:documentationgt;
* Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface OneToMany {
* Class targetEntity() default void.class;
* CascadeType[] cascade() default {};
* FetchType fetch() default LAZY;
* String mappedBy() default ""; }
* </xsd:documentationgt;
* </xsd:annotationgt;
* <xsd:sequencegt;
* <xsd:choicegt;
* <xsd:element name="order-by" type="orm:order-by" minOccurs="0" /gt;
* <xsd:element name="order-column" type="orm:order-column" minOccurs="0" /gt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="map-key" type="orm:map-key" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-class" type="orm:map-key-class" minOccurs="0" /gt;
* <xsd:choicegt;
* <xsd:element name="map-key-temporal" type="orm:temporal" minOccurs="0" /gt;
* <xsd:element name="map-key-enumerated" type="orm:enumerated" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-attribute-override" type="orm:attribute-override" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="map-key-convert" type="orm:convert" minOccurs="0" maxOccurs="unbounded" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="map-key-column" type="orm:map-key-column" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="map-key-join-column" type="orm:map-key-join-column" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="map-key-foreign-key" type="orm:foreign-key" minOccurs="0" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:choicegt;
* <xsd:element name="join-table" type="orm:join-table" minOccurs="0" /gt;
* <xsd:sequencegt;
* <xsd:element name="join-column" type="orm:join-column" minOccurs="0" maxOccurs="unbounded" /gt;
* <xsd:element name="foreign-key" type="orm:foreign-key" minOccurs="0" /gt;
* </xsd:sequencegt;
* </xsd:choicegt;
* <xsd:element name="cascade" type="orm:cascade-type" minOccurs="0" /gt;
* </xsd:sequencegt;
* <xsd:attribute name="name" type="xsd:string" use="required" /gt;
* <xsd:attribute name="target-entity" type="xsd:string" /gt;
* <xsd:attribute name="fetch" type="orm:fetch-type" /gt;
* <xsd:attribute name="access" type="orm:access-type" /gt;
* <xsd:attribute name="mapped-by" type="xsd:string" /gt;
* <xsd:attribute name="orphan-removal" type="xsd:boolean" /gt;
*
* </pre>
*
* @author m410
*/
public final class OneToMany extends Node {
private String name;
private String mappedBy = "";
private ORM.Cascade[] cascade = {};// should be enum
private ORM.Fetch fetch = ORM.Fetch.LAZY; // should be enum
private Class targetEntity = void.class;
private boolean orphanRemoval = true;
private ORM.Access access = null;
public OneToMany() {
super(2, 6);
}
public <T> OneToMany(String name, Class<T> targetEntity, String mappedBy) {
this();
this.name = name;
this.targetEntity = targetEntity;
this.mappedBy = mappedBy;
}
public <T> OneToMany(String name, Class<T> targetEntity) {
this();
this.name = name;
this.targetEntity = targetEntity;
}
public OneToMany(String name, String mappedBy, ORM.Cascade[] cascade, ORM.Fetch fetch,
Class targetEntity, boolean orphanRemoval) {
this();
this.name = name;
this.mappedBy = mappedBy;
this.cascade = cascade;
this.fetch = fetch;
this.targetEntity = targetEntity;
this.orphanRemoval = orphanRemoval;
}
@Override
public void appendElement(Document root, Element parent) {
Element id = root.createElement("one-to-many");
id.setAttribute("name", name);
if(targetEntity != void.class)
id.setAttribute("target-entity", targetEntity.getName());
id.setAttribute("fetch", fetch.toString());
if (access != null)
id.setAttribute("access", access.toString());
if(!"".equals(mappedBy))
id.setAttribute("mapped-by", mappedBy);
id.setAttribute("orphan-removal", String.valueOf(orphanRemoval));
// children
// foreignKey,joinTable,joinColumn,orderBy,orderColumn, etc
children.stream().forEach(n -> n.appendElement(root, id));
parent.appendChild(id);
}
}
| 4,816 | 0.622508 | 0.617317 | 124 | 37.838711 | 29.640423 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.217742 | false | false | 0 |
fe82103a48685dd12db67a7593cfa46162b7438e | 21,019,569,983,662 | 4431e581372f277282ba19a162269d8692dd4dfb | /src/com/mzinck/fwa/FWA.java | f820363d753521b7b612de4b6e7d483c0546c984 | [] | no_license | MitchZinck/Fun-with-Arithmetic | https://github.com/MitchZinck/Fun-with-Arithmetic | ecb760262591861b9b5e6f422d8805b6acf74af7 | 7842d3492f1bb296b8bb774fb3e007d7a787fb83 | refs/heads/master | 2021-01-10T16:22:24.265000 | 2015-12-08T18:20:14 | 2015-12-08T18:20:14 | 47,633,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mzinck.fwa;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
/**
* Program that teaches and helps kids with arithmetic
*
* @author Mitchell Zinck <mitch@mzinck.com> <mitchellzinck@yahoo.com>
*/
public class FWA {
private static State state = State.START;
private static Properties props = new Properties();
private static String name = "";
private static Scanner scan = new Scanner(System.in);
private static int timeCount = 0,
hardTime = Integer.MAX_VALUE / 1001;
private static File output;
/**
* Start of our program. Loads the properties files and reads their highscores.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
output = new File(System.getProperty("user.home") + "\\arithmetic.properties");
try {
props.load(new FileInputStream(System.getProperty("user.home") + "\\arithmetic.properties"));
} catch (FileNotFoundException e){
try {
output.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(props.getProperty("timeCount") != null) {
timeCount = Integer.parseInt(props.getProperty("timeCount"));
hardTime = Integer.parseInt(props.getProperty("hardTime"));
name = props.getProperty("name");
} else {
log("What is your name?");
name = scan.nextLine();
setProps();
}
setState();
}
/**
* Menu picker for our program. Sets the state based on what the user types into the console
* and then initiates the main loop.
*/
public static void setState() {
state = State.START;
log("Welcome to Fun with Arithmetic " + name + "!\nPlease enter the letters:\n"
+ "'N' = New users press this!\n"
+ "'T' = Time Attack Mode\n"
+ "'L' = Learner Mode\n"
+ "'H' = Hard Mode\n"
+ "'HS' = Check your Highscores\n"
+ "'X' = Exit Program");
switch(scan.nextLine()) {
case "N":
state = State.NEW;
break;
case "T":
state = State.TIME;
break;
case "L":
state = State.LEARNER;
break;
case "H":
state = State.HARD;
break;
case "X":
System.exit(0);
break;
case "HS":
log(name + ", your highscores are:\n"
+ "Time Attack: " + timeCount + " questions!\n"
+ "Hard Mode: " + hardTime + " seconds!\n"
+ "Press any key to go back to the main menu!");
scan.nextLine();
break;
default:
log("Wrong input please try again!");
break;
}
if(state == State.START) {
setState();
} else {
mainLoop();
}
}
/**
* Switches through the states. Whichever state was picked has a set of instructions.
*/
public static void mainLoop() {
switch(state) {
case NEW:
log("=====Fun with Arithmetic=====\n"
+ "Fun with Arithmetic is a teaching tool that is used to teach kids of\n"
+ "all ages basic math skills. You will be given asterick formations\n"
+ "that you will have to compute mathematically in your head. Each asterick is\n"
+ "equal to one unit. So (*) plus (*) would equal (**) or 2!\n"
+ "Lets get started with the tutorial! We will give you 3 starter questions\n"
+ "and then you can jump into the full experience!\n");
submitQuestion(getQuery(4, false));
log("You completed the tutorial, press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case HARD:
log("In Hard mode you are given 5 questions that you have to complete as fast as possible.\n"
+ "Questions will start in 3 seconds.");
countDown();
long time = System.currentTimeMillis();
submitQuestion(getQuery(1, true));
time = System.currentTimeMillis() - time;
if(time < hardTime * 1000) {
log("Congratulations you beat your highscore! 5 hard questions in " + (time / 1000) + " seconds!");
hardTime = (int) (time / 1000);
setProps();
} else {
log("You completed 5 hard questions in " + (time / 1000) + " seconds!");
}
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case LEARNER:
log("In Learner mode you are given a infinite number of medium questions. Type -1000 to quit.");
int c = 0;
while(submitQuestion(getQuery(1, true))){
c++;
}
log("You completed " + c + " questions!");
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case TIME:
log("In Time Attack mode you will try to do as many questions as possible in 30 seconds.");
countDown();
int counter = 0;
long current = System.currentTimeMillis();
while(true) {
submitQuestion(getQuery(1, false));
counter++;
if(System.currentTimeMillis() - current > 10000) {
break;
}
}
if(timeCount < counter) {
log("Congratulations, you beat your highscore by " + (counter - timeCount) + "!");
timeCount = counter;
setProps();
} else {
log("Congratulations, you completed " + counter + " questions in 30 seconds!");
}
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
}
System.out.println();
System.out.println();
setState();
}
/**
* Stores the users highscores as a properties file.
*/
public static void setProps() {
props.setProperty("hardTime", Integer.toString(hardTime));
props.setProperty("timeCount", Integer.toString(timeCount));
props.setProperty("name", name);
try {
FileWriter writer = new FileWriter(output);
props.store(writer, null);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Method for counting down.
*/
public static void countDown() {
try {
Thread.sleep(1000);
log("3...");
Thread.sleep(1000);
log("2...");
Thread.sleep(1000);
log("1...");
Thread.sleep(1000);
log("GO!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Returns a String array of questions for the user.
*
* @param totalQ
* Amount of questions needed.
* @param hard
* Determines whether the questions are harder than usual.
* @return a <code>String[] array</code>
*/
public static String[] getQuery(int totalQ, boolean hard) {
String[] array = new String[totalQ];
Random rand = new Random();
String query = "What is ";
int total = 0;
int indexes = rand.nextInt(2) + 2;
int z;
for(int e = 0; e < totalQ; e++) {
if(hard == true) {
z = rand.nextInt(4) + 1;
} else {
z = rand.nextInt(1) + 1;
}
total += z;
query += new String(new char[z]).replace("\0", "*");
for(int i = 0; i < indexes; i++) {
if(rand.nextInt(2) == 0) {
z = hard == true ? rand.nextInt(4) + 1 : rand.nextInt(2) + 1;
query += " - " + new String(new char[z]).replace("\0", "*");
total -= z;
} else {
z = hard == true ? rand.nextInt(4) + 1 : rand.nextInt(2) + 1;
query += " + " + new String(new char[z]).replace("\0", "*");
total += z;
}
}
array[e] = query + "?." + total;
query = "What is ";
total = 0;
}
return array;
}
/**
* Queries the user with questions.
*
* @param query
* The array with questions
* @return <code>true</code> if user didn't exit.
*/
public static boolean submitQuestion(String[] query) {
for(int i = 0; i < query.length; i++) {
if(query.length > 1) {
log("Question " + (i + 1) + ": " + query[i].substring(0, query[i].indexOf(".")));
} else {
log("Question: " + query[i].substring(0, query[i].indexOf(".")));
}
int a;
while((a = scan.nextInt()) != Integer.parseInt(query[i].split("\\.")[1])) {
if(a == -1000) {
return false;
}
log("Wrong answer! Try again: ");
}
}
return true;
}
/**
* Prints the given message.
*
* @param message
* The message to be printed.
*/
public static void log(String message) {
System.out.println(message);
}
}
| UTF-8 | Java | 10,756 | java | FWA.java | Java | [
{
"context": "ches and helps kids with arithmetic\n * \n * @author Mitchell Zinck <mitch@mzinck.com> <mitchellzinck@yahoo.com>\n */\n",
"end": 340,
"score": 0.9998826384544373,
"start": 326,
"tag": "NAME",
"value": "Mitchell Zinck"
},
{
"context": "ds with arithmetic\n * \n * @author... | null | [] | package com.mzinck.fwa;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
/**
* Program that teaches and helps kids with arithmetic
*
* @author <NAME> <<EMAIL>> <<EMAIL>>
*/
public class FWA {
private static State state = State.START;
private static Properties props = new Properties();
private static String name = "";
private static Scanner scan = new Scanner(System.in);
private static int timeCount = 0,
hardTime = Integer.MAX_VALUE / 1001;
private static File output;
/**
* Start of our program. Loads the properties files and reads their highscores.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
output = new File(System.getProperty("user.home") + "\\arithmetic.properties");
try {
props.load(new FileInputStream(System.getProperty("user.home") + "\\arithmetic.properties"));
} catch (FileNotFoundException e){
try {
output.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(props.getProperty("timeCount") != null) {
timeCount = Integer.parseInt(props.getProperty("timeCount"));
hardTime = Integer.parseInt(props.getProperty("hardTime"));
name = props.getProperty("name");
} else {
log("What is your name?");
name = scan.nextLine();
setProps();
}
setState();
}
/**
* Menu picker for our program. Sets the state based on what the user types into the console
* and then initiates the main loop.
*/
public static void setState() {
state = State.START;
log("Welcome to Fun with Arithmetic " + name + "!\nPlease enter the letters:\n"
+ "'N' = New users press this!\n"
+ "'T' = Time Attack Mode\n"
+ "'L' = Learner Mode\n"
+ "'H' = Hard Mode\n"
+ "'HS' = Check your Highscores\n"
+ "'X' = Exit Program");
switch(scan.nextLine()) {
case "N":
state = State.NEW;
break;
case "T":
state = State.TIME;
break;
case "L":
state = State.LEARNER;
break;
case "H":
state = State.HARD;
break;
case "X":
System.exit(0);
break;
case "HS":
log(name + ", your highscores are:\n"
+ "Time Attack: " + timeCount + " questions!\n"
+ "Hard Mode: " + hardTime + " seconds!\n"
+ "Press any key to go back to the main menu!");
scan.nextLine();
break;
default:
log("Wrong input please try again!");
break;
}
if(state == State.START) {
setState();
} else {
mainLoop();
}
}
/**
* Switches through the states. Whichever state was picked has a set of instructions.
*/
public static void mainLoop() {
switch(state) {
case NEW:
log("=====Fun with Arithmetic=====\n"
+ "Fun with Arithmetic is a teaching tool that is used to teach kids of\n"
+ "all ages basic math skills. You will be given asterick formations\n"
+ "that you will have to compute mathematically in your head. Each asterick is\n"
+ "equal to one unit. So (*) plus (*) would equal (**) or 2!\n"
+ "Lets get started with the tutorial! We will give you 3 starter questions\n"
+ "and then you can jump into the full experience!\n");
submitQuestion(getQuery(4, false));
log("You completed the tutorial, press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case HARD:
log("In Hard mode you are given 5 questions that you have to complete as fast as possible.\n"
+ "Questions will start in 3 seconds.");
countDown();
long time = System.currentTimeMillis();
submitQuestion(getQuery(1, true));
time = System.currentTimeMillis() - time;
if(time < hardTime * 1000) {
log("Congratulations you beat your highscore! 5 hard questions in " + (time / 1000) + " seconds!");
hardTime = (int) (time / 1000);
setProps();
} else {
log("You completed 5 hard questions in " + (time / 1000) + " seconds!");
}
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case LEARNER:
log("In Learner mode you are given a infinite number of medium questions. Type -1000 to quit.");
int c = 0;
while(submitQuestion(getQuery(1, true))){
c++;
}
log("You completed " + c + " questions!");
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
case TIME:
log("In Time Attack mode you will try to do as many questions as possible in 30 seconds.");
countDown();
int counter = 0;
long current = System.currentTimeMillis();
while(true) {
submitQuestion(getQuery(1, false));
counter++;
if(System.currentTimeMillis() - current > 10000) {
break;
}
}
if(timeCount < counter) {
log("Congratulations, you beat your highscore by " + (counter - timeCount) + "!");
timeCount = counter;
setProps();
} else {
log("Congratulations, you completed " + counter + " questions in 30 seconds!");
}
log("Press any key to continue!");
scan.nextLine();
scan.nextLine();
break;
}
System.out.println();
System.out.println();
setState();
}
/**
* Stores the users highscores as a properties file.
*/
public static void setProps() {
props.setProperty("hardTime", Integer.toString(hardTime));
props.setProperty("timeCount", Integer.toString(timeCount));
props.setProperty("name", name);
try {
FileWriter writer = new FileWriter(output);
props.store(writer, null);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Method for counting down.
*/
public static void countDown() {
try {
Thread.sleep(1000);
log("3...");
Thread.sleep(1000);
log("2...");
Thread.sleep(1000);
log("1...");
Thread.sleep(1000);
log("GO!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Returns a String array of questions for the user.
*
* @param totalQ
* Amount of questions needed.
* @param hard
* Determines whether the questions are harder than usual.
* @return a <code>String[] array</code>
*/
public static String[] getQuery(int totalQ, boolean hard) {
String[] array = new String[totalQ];
Random rand = new Random();
String query = "What is ";
int total = 0;
int indexes = rand.nextInt(2) + 2;
int z;
for(int e = 0; e < totalQ; e++) {
if(hard == true) {
z = rand.nextInt(4) + 1;
} else {
z = rand.nextInt(1) + 1;
}
total += z;
query += new String(new char[z]).replace("\0", "*");
for(int i = 0; i < indexes; i++) {
if(rand.nextInt(2) == 0) {
z = hard == true ? rand.nextInt(4) + 1 : rand.nextInt(2) + 1;
query += " - " + new String(new char[z]).replace("\0", "*");
total -= z;
} else {
z = hard == true ? rand.nextInt(4) + 1 : rand.nextInt(2) + 1;
query += " + " + new String(new char[z]).replace("\0", "*");
total += z;
}
}
array[e] = query + "?." + total;
query = "What is ";
total = 0;
}
return array;
}
/**
* Queries the user with questions.
*
* @param query
* The array with questions
* @return <code>true</code> if user didn't exit.
*/
public static boolean submitQuestion(String[] query) {
for(int i = 0; i < query.length; i++) {
if(query.length > 1) {
log("Question " + (i + 1) + ": " + query[i].substring(0, query[i].indexOf(".")));
} else {
log("Question: " + query[i].substring(0, query[i].indexOf(".")));
}
int a;
while((a = scan.nextInt()) != Integer.parseInt(query[i].split("\\.")[1])) {
if(a == -1000) {
return false;
}
log("Wrong answer! Try again: ");
}
}
return true;
}
/**
* Prints the given message.
*
* @param message
* The message to be printed.
*/
public static void log(String message) {
System.out.println(message);
}
}
| 10,723 | 0.461231 | 0.451841 | 297 | 35.21212 | 25.321611 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531987 | false | false | 0 |
0799708fb86f9080684092b965babd7c822c44da | 19,318,762,926,072 | 13b685368ba74760628b730152b99e8d50cd96be | /src/main/java/com/google/code/geocoder/model/GeocoderResultType.java | 3c6d2742024e40b6e1acd84f0ef31dddabfaf155 | [] | no_license | panchmp/geocoder-java | https://github.com/panchmp/geocoder-java | 62b50e5af4860aee7fd90383d55f2cd2efcaed61 | 2eeece3af09124da2b528e99c841108ec679631f | refs/heads/master | 2021-01-19T02:17:54.386000 | 2016-08-04T10:12:55 | 2016-08-04T10:12:55 | 32,188,070 | 4 | 9 | null | false | 2016-08-04T10:12:56 | 2015-03-14T00:17:43 | 2016-08-02T18:34:07 | 2016-08-04T10:12:55 | 1,722 | 2 | 3 | 5 | Java | null | null | package com.google.code.geocoder.model;
/**
* @author <a href="mailto:panchmp@gmail.com">Michael Panchenko</a>
*/
public enum GeocoderResultType {
STREET_ADDRESS("street_address"),
ROUTE("route"),
INTERSECTION("intersection"),
POLITICAL("political"),
COUNTRY("country"),
ADMINISTRATIVE_AREA_LEVEL_1("administrative_area_level_1"),
ADMINISTRATIVE_AREA_LEVEL_2("administrative_area_level_2"),
ADMINISTRATIVE_AREA_LEVEL_3("administrative_area_level_3"),
COLLOQUIAL_AREA("colloquial_area"),
LOCALITY("locality"),
SUBLOCALITY("sublocality"),
NEIGHBORHOOD("neighborhood"),
PREMISE("premise"),
SUBPREMISE("subpremise"),
POSTAL_CODE("postal_code"),
NATURAL_FEATURE("natural_feature"),
AIRPORT("airport"),
PARK("park"),
POINT_OF_INTEREST("point_of_interest"),
POST_BOX("post_box"),
STREET_NUMBER("street_number"),
FLOOR("floor"),
ROOM("room");
private final String value;
GeocoderResultType(final String v) {
value = v;
}
public String value() {
return value;
}
public static GeocoderResultType fromValue(final String v) {
for (GeocoderResultType c : GeocoderResultType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
} | UTF-8 | Java | 1,364 | java | GeocoderResultType.java | Java | [
{
"context": "e.geocoder.model;\n\n/**\n * @author <a href=\"mailto:panchmp@gmail.com\">Michael Panchenko</a>\n */\npublic enum GeocoderRe",
"end": 89,
"score": 0.9998573660850525,
"start": 72,
"tag": "EMAIL",
"value": "panchmp@gmail.com"
},
{
"context": "/**\n * @author <a href=\"ma... | null | [] | package com.google.code.geocoder.model;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public enum GeocoderResultType {
STREET_ADDRESS("street_address"),
ROUTE("route"),
INTERSECTION("intersection"),
POLITICAL("political"),
COUNTRY("country"),
ADMINISTRATIVE_AREA_LEVEL_1("administrative_area_level_1"),
ADMINISTRATIVE_AREA_LEVEL_2("administrative_area_level_2"),
ADMINISTRATIVE_AREA_LEVEL_3("administrative_area_level_3"),
COLLOQUIAL_AREA("colloquial_area"),
LOCALITY("locality"),
SUBLOCALITY("sublocality"),
NEIGHBORHOOD("neighborhood"),
PREMISE("premise"),
SUBPREMISE("subpremise"),
POSTAL_CODE("postal_code"),
NATURAL_FEATURE("natural_feature"),
AIRPORT("airport"),
PARK("park"),
POINT_OF_INTEREST("point_of_interest"),
POST_BOX("post_box"),
STREET_NUMBER("street_number"),
FLOOR("floor"),
ROOM("room");
private final String value;
GeocoderResultType(final String v) {
value = v;
}
public String value() {
return value;
}
public static GeocoderResultType fromValue(final String v) {
for (GeocoderResultType c : GeocoderResultType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
} | 1,343 | 0.634164 | 0.629765 | 52 | 25.25 | 19.595795 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557692 | false | false | 0 |
b86f62fd7ca0397809745a3e7b3950341b2582d0 | 25,383,256,722,577 | ee3959d2f41871b08b0fdcbb85133f58133ccb21 | /opensaml-storage-api/src/main/java/org/opensaml/storage/StorageSerializer.java | 17a6dd38196389a6af85104f43b9d87760ed56e0 | [] | no_license | superturbooffenaffen/opensaml3 | https://github.com/superturbooffenaffen/opensaml3 | 2540074a6e0a61999a05c0c38ca2cd255e910160 | 239384965a95b7bc07e834786b77ce4f03cccb85 | refs/heads/master | 2023-09-02T17:11:17.224000 | 2019-03-27T13:25:35 | 2019-03-27T13:25:35 | 178,211,043 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.storage;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.shibboleth.utilities.java.support.annotation.constraint.NotEmpty;
import net.shibboleth.utilities.java.support.annotation.constraint.ThreadSafeAfterInit;
import net.shibboleth.utilities.java.support.component.InitializableComponent;
/**
* Interface to a serialization/deserialization process used by a {@link StorageService} implementation
* to optimize the handling of complex objects.
*
* @param <Type> the type of object handled
*/
@ThreadSafeAfterInit
public interface StorageSerializer<Type> extends InitializableComponent {
/**
* Returns a string representing the input object.
*
* @param instance object to serialize
* @return a string
* @throws IOException if an error occurs during serialization
*/
@Nonnull @NotEmpty String serialize(@Nonnull final Type instance) throws IOException;
/**
* Returns an object recovered from a string produced through the {@link #serialize} method.
*
* @param version record version
* @param context context of record
* @param key key of record
* @param value data to deserialize
* @param expiration expiration of record, if any
* @return a deserialized object
* @throws IOException if an error occurs during deserialization
*/
@Nonnull Type deserialize(final long version, @Nonnull @NotEmpty final String context,
@Nonnull @NotEmpty final String key, @Nonnull @NotEmpty final String value, @Nullable Long expiration)
throws IOException;
} | UTF-8 | Java | 2,504 | java | StorageSerializer.java | Java | [] | null | [] | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.storage;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.shibboleth.utilities.java.support.annotation.constraint.NotEmpty;
import net.shibboleth.utilities.java.support.annotation.constraint.ThreadSafeAfterInit;
import net.shibboleth.utilities.java.support.component.InitializableComponent;
/**
* Interface to a serialization/deserialization process used by a {@link StorageService} implementation
* to optimize the handling of complex objects.
*
* @param <Type> the type of object handled
*/
@ThreadSafeAfterInit
public interface StorageSerializer<Type> extends InitializableComponent {
/**
* Returns a string representing the input object.
*
* @param instance object to serialize
* @return a string
* @throws IOException if an error occurs during serialization
*/
@Nonnull @NotEmpty String serialize(@Nonnull final Type instance) throws IOException;
/**
* Returns an object recovered from a string produced through the {@link #serialize} method.
*
* @param version record version
* @param context context of record
* @param key key of record
* @param value data to deserialize
* @param expiration expiration of record, if any
* @return a deserialized object
* @throws IOException if an error occurs during deserialization
*/
@Nonnull Type deserialize(final long version, @Nonnull @NotEmpty final String context,
@Nonnull @NotEmpty final String key, @Nonnull @NotEmpty final String value, @Nullable Long expiration)
throws IOException;
} | 2,504 | 0.742812 | 0.741214 | 61 | 40.065575 | 33.093941 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327869 | false | false | 0 |
4f15e19057e43925a45f5a50d94ef70fd06b882b | 33,603,824,130,613 | 4e2542135bdb804278c2afb40b7c159d6e7e8570 | /src/main/java/fr/tse/fise3/info6/kanban/utils/LoadDatabase.java | 98a1e0371d7d9176fdc7989da4206ccbaf50ee29 | [] | no_license | samiaymane/kanban | https://github.com/samiaymane/kanban | 5c907e9febc91c0aa7dc54ecf96f4e2137f184e3 | fecd348f0dc03b85c162e02c2e8115a632aa5860 | refs/heads/main | 2023-01-28T17:56:19.093000 | 2020-12-04T17:14:31 | 2020-12-04T17:14:31 | 318,584,330 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.tse.fise3.info6.kanban.utils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import fr.tse.fise3.info6.kanban.dao.ChangeLogRepository;
import fr.tse.fise3.info6.kanban.dao.DeveloperRepository;
import fr.tse.fise3.info6.kanban.dao.TaskRepository;
import fr.tse.fise3.info6.kanban.dao.TaskStatusRepository;
import fr.tse.fise3.info6.kanban.dao.TaskTypeRepository;
import fr.tse.fise3.info6.kanban.domain.ChangeLog;
import fr.tse.fise3.info6.kanban.domain.Developer;
import fr.tse.fise3.info6.kanban.domain.Task;
import fr.tse.fise3.info6.kanban.domain.TaskStatus;
import fr.tse.fise3.info6.kanban.domain.TaskType;
@Configuration
public class LoadDatabase {
@Bean
CommandLineRunner initTaskStatus(TaskStatusRepository taskStatusRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
TaskStatus todo = new TaskStatus(Constants.TODO, "TODO");
taskStatusRepository.save(todo);
TaskStatus doing = new TaskStatus(Constants.DOING, "DOING");
taskStatusRepository.save(doing);
TaskStatus done = new TaskStatus(Constants.DONE, "DONE");
taskStatusRepository.save(done);
}
};
}
@Bean
CommandLineRunner initTaskType(TaskTypeRepository taskTypeRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
TaskType bug = new TaskType(Constants.BUG, "BUG");
taskTypeRepository.save(bug);
TaskType update = new TaskType(Constants.UPDATE, "UPDATE");
taskTypeRepository.save(update);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initTasks(TaskRepository taskRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
Task task1 = new Task("Task_1");
taskRepository.save(task1);
Task task2 = new Task("Task_2");
taskRepository.save(task2);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initDevelopers(DeveloperRepository developerRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
Developer developer1 = new Developer();
developerRepository.save(developer1);
Developer developer2 = new Developer();
developerRepository.save(developer2);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initChangeLogs(ChangeLogRepository changeLogRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
ChangeLog changeLog1 = new ChangeLog();
changeLogRepository.save(changeLog1);
ChangeLog changeLog2 = new ChangeLog();
changeLogRepository.save(changeLog2);
ChangeLog changeLog3 = new ChangeLog();
changeLogRepository.save(changeLog3);
}
};
}
}
| UTF-8 | Java | 3,157 | java | LoadDatabase.java | Java | [] | null | [] | package fr.tse.fise3.info6.kanban.utils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import fr.tse.fise3.info6.kanban.dao.ChangeLogRepository;
import fr.tse.fise3.info6.kanban.dao.DeveloperRepository;
import fr.tse.fise3.info6.kanban.dao.TaskRepository;
import fr.tse.fise3.info6.kanban.dao.TaskStatusRepository;
import fr.tse.fise3.info6.kanban.dao.TaskTypeRepository;
import fr.tse.fise3.info6.kanban.domain.ChangeLog;
import fr.tse.fise3.info6.kanban.domain.Developer;
import fr.tse.fise3.info6.kanban.domain.Task;
import fr.tse.fise3.info6.kanban.domain.TaskStatus;
import fr.tse.fise3.info6.kanban.domain.TaskType;
@Configuration
public class LoadDatabase {
@Bean
CommandLineRunner initTaskStatus(TaskStatusRepository taskStatusRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
TaskStatus todo = new TaskStatus(Constants.TODO, "TODO");
taskStatusRepository.save(todo);
TaskStatus doing = new TaskStatus(Constants.DOING, "DOING");
taskStatusRepository.save(doing);
TaskStatus done = new TaskStatus(Constants.DONE, "DONE");
taskStatusRepository.save(done);
}
};
}
@Bean
CommandLineRunner initTaskType(TaskTypeRepository taskTypeRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
TaskType bug = new TaskType(Constants.BUG, "BUG");
taskTypeRepository.save(bug);
TaskType update = new TaskType(Constants.UPDATE, "UPDATE");
taskTypeRepository.save(update);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initTasks(TaskRepository taskRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
Task task1 = new Task("Task_1");
taskRepository.save(task1);
Task task2 = new Task("Task_2");
taskRepository.save(task2);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initDevelopers(DeveloperRepository developerRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
Developer developer1 = new Developer();
developerRepository.save(developer1);
Developer developer2 = new Developer();
developerRepository.save(developer2);
}
};
}
@Bean
@Profile("test")
CommandLineRunner initChangeLogs(ChangeLogRepository changeLogRepository) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception{
ChangeLog changeLog1 = new ChangeLog();
changeLogRepository.save(changeLog1);
ChangeLog changeLog2 = new ChangeLog();
changeLogRepository.save(changeLog2);
ChangeLog changeLog3 = new ChangeLog();
changeLogRepository.save(changeLog3);
}
};
}
}
| 3,157 | 0.700348 | 0.688312 | 117 | 24.982906 | 23.360052 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.649573 | false | false | 0 |
99d4adaed1ac35dabaa461fb4d66e4fdd720f6c5 | 17,609,365,916,521 | c99fd1603662bca5b31bcc5e4b030f7815d905ac | /chirper/chirper-services/src/test/java/it/unifi/ing/chirper/services/endpoints/UserFriendEndpointIT.java | 061e504664f07fe1f2736aa332c5d935ae80f557 | [] | no_license | NekoStark/chirper | https://github.com/NekoStark/chirper | 3d782c2599e825b85e4ef742d65d82aab6638446 | dd04f845807a1e91c6bbd2111dcf30d4182ca4af | refs/heads/master | 2021-01-11T16:10:18.121000 | 2017-04-02T18:23:13 | 2017-04-02T18:23:13 | 80,025,051 | 0 | 0 | null | false | 2017-04-02T18:23:14 | 2017-01-25T15:04:04 | 2017-03-14T14:51:24 | 2017-04-02T18:23:13 | 15,985 | 0 | 0 | 0 | Java | null | null | package it.unifi.ing.chirper.services.endpoints;
import org.junit.Test;
import it.unifi.ing.chirper.services.endpoints.delegates.UserFriendEndpointTestDelegate;
import it.unifi.ing.chirper.test.exception.TestInitializationException;
import it.unifi.ing.chirper.test.services.ServiceIT;
public class UserFriendEndpointIT extends ServiceIT {
private UserFriendEndpointTestDelegate testDelegate;
@Override
public void initTest() throws TestInitializationException {
testDelegate = new UserFriendEndpointTestDelegate();
testDelegate.init(entityManager);
testDelegate.insertData();
}
@Test
public void testQuery() {
testDelegate.testQuery();
}
@Test
public void testQueryWrongId() {
testDelegate.testQueryWrongId();
}
@Test
public void testAdd() {
testDelegate.testAdd();
}
@Test
public void testAddWrongIds() {
testDelegate.testAddWrongIds();
}
@Test
public void testRemove() {
testDelegate.testRemove();
}
@Test
public void testRemoveWrongIds() {
testDelegate.testRemoveWrongIds();
}
}
| UTF-8 | Java | 1,034 | java | UserFriendEndpointIT.java | Java | [] | null | [] | package it.unifi.ing.chirper.services.endpoints;
import org.junit.Test;
import it.unifi.ing.chirper.services.endpoints.delegates.UserFriendEndpointTestDelegate;
import it.unifi.ing.chirper.test.exception.TestInitializationException;
import it.unifi.ing.chirper.test.services.ServiceIT;
public class UserFriendEndpointIT extends ServiceIT {
private UserFriendEndpointTestDelegate testDelegate;
@Override
public void initTest() throws TestInitializationException {
testDelegate = new UserFriendEndpointTestDelegate();
testDelegate.init(entityManager);
testDelegate.insertData();
}
@Test
public void testQuery() {
testDelegate.testQuery();
}
@Test
public void testQueryWrongId() {
testDelegate.testQueryWrongId();
}
@Test
public void testAdd() {
testDelegate.testAdd();
}
@Test
public void testAddWrongIds() {
testDelegate.testAddWrongIds();
}
@Test
public void testRemove() {
testDelegate.testRemove();
}
@Test
public void testRemoveWrongIds() {
testDelegate.testRemoveWrongIds();
}
}
| 1,034 | 0.775629 | 0.775629 | 49 | 20.102041 | 22.114033 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.122449 | false | false | 0 |
f8f85e67e0d8cbdbc37fdb9fa001eb0fe386ecc7 | 29,403,346,131,186 | 89bddf43b12671da7650eb28cc6362a6f8cd8aee | /src/main/java/bo/ucb/edu/ingsoft/dao/ProjectDao.java | ac9767a60135582bb339e6a1930eb044a5c22766 | [] | no_license | JuanJo53/ingsoft | https://github.com/JuanJo53/ingsoft | dbdee5bc8f9ebd08234139b04c80be0cd51614d1 | 8e3d5208d8b789f06349190b44d5b5ed786817ca | refs/heads/main | 2023-02-18T04:35:47.091000 | 2021-01-14T20:57:31 | 2021-01-14T20:57:31 | 307,218,215 | 3 | 0 | null | true | 2020-10-26T00:02:46 | 2020-10-26T00:02:45 | 2020-10-16T01:32:50 | 2020-10-16T01:32:48 | 55 | 0 | 0 | 0 | null | false | false | package bo.ucb.edu.ingsoft.dao;
import bo.ucb.edu.ingsoft.model.Certificate;
import bo.ucb.edu.ingsoft.model.Project;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ProjectDao {
//detailsproyect
public void newProject(Project project);
public void updateproyect(Project project);
public Project detailsproyect(Integer projectsId);
public void increaseProjectViews(Integer userid,Integer projectsId);
public List<Project> listproyect();
public List<Project> listproyectuser(Integer UserId);
public Integer getLastInsertIdProject();
public List<Project> listproyectuserparticipate(Integer UserId);
public Project proyectuser(Integer UserId,Integer projectsId);
public List<Project>listproyectag(Integer Tagsid);
public List<Project>listproyecserch(String serch);
}
| UTF-8 | Java | 861 | java | ProjectDao.java | Java | [] | null | [] | package bo.ucb.edu.ingsoft.dao;
import bo.ucb.edu.ingsoft.model.Certificate;
import bo.ucb.edu.ingsoft.model.Project;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ProjectDao {
//detailsproyect
public void newProject(Project project);
public void updateproyect(Project project);
public Project detailsproyect(Integer projectsId);
public void increaseProjectViews(Integer userid,Integer projectsId);
public List<Project> listproyect();
public List<Project> listproyectuser(Integer UserId);
public Integer getLastInsertIdProject();
public List<Project> listproyectuserparticipate(Integer UserId);
public Project proyectuser(Integer UserId,Integer projectsId);
public List<Project>listproyectag(Integer Tagsid);
public List<Project>listproyecserch(String serch);
}
| 861 | 0.783972 | 0.783972 | 24 | 34.875 | 23.076527 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 0 |
6c07f6b95ceea3194b9fa02856d8adc7614fe707 | 4,922,032,539,034 | ee2981fdc92019c7a3fd81fd3ed3356e80dce0ea | /vendorIdlJava/org/omg/CosEventChannelAdmin/EventChannelPOATie.java | cd66941346e0d9bb6173f2ada78bdd308632d6f6 | [] | no_license | zy5163165/cdcp-zj-fhM2000 | https://github.com/zy5163165/cdcp-zj-fhM2000 | b7332ead9ac682c7f15df39bd3ce44c5f7e07e48 | e975ba3a794d5438adf9ee3bbbd79927dbc6dfb0 | refs/heads/master | 2021-06-17T20:10:33.306000 | 2020-12-28T08:49:36 | 2020-12-28T08:49:36 | 129,201,444 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.omg.CosEventChannelAdmin;
import org.omg.PortableServer.POA;
/**
* Generated from IDL definition of interface "EventChannel"
* @author JacORB IDL compiler
*/
public class EventChannelPOATie
extends EventChannelPOA
{
private EventChannelOperations _delegate;
private POA _poa;
public EventChannelPOATie(EventChannelOperations delegate)
{
_delegate = delegate;
}
public EventChannelPOATie(EventChannelOperations delegate, POA poa)
{
_delegate = delegate;
_poa = poa;
}
public org.omg.CosEventChannelAdmin.EventChannel _this()
{
return org.omg.CosEventChannelAdmin.EventChannelHelper.narrow(_this_object());
}
public org.omg.CosEventChannelAdmin.EventChannel _this(org.omg.CORBA.ORB orb)
{
return org.omg.CosEventChannelAdmin.EventChannelHelper.narrow(_this_object(orb));
}
public EventChannelOperations _delegate()
{
return _delegate;
}
public void _delegate(EventChannelOperations delegate)
{
_delegate = delegate;
}
public org.omg.CosEventChannelAdmin.ConsumerAdmin for_consumers()
{
return _delegate.for_consumers();
}
public void destroy()
{
_delegate.destroy();
}
public org.omg.CosEventChannelAdmin.SupplierAdmin for_suppliers()
{
return _delegate.for_suppliers();
}
}
| UTF-8 | Java | 1,244 | java | EventChannelPOATie.java | Java | [
{
"context": " definition of interface \"EventChannel\"\n *\t@author JacORB IDL compiler \n */\n\npublic class EventChannelPOATi",
"end": 157,
"score": 0.8159420490264893,
"start": 151,
"tag": "USERNAME",
"value": "JacORB"
}
] | null | [] | package org.omg.CosEventChannelAdmin;
import org.omg.PortableServer.POA;
/**
* Generated from IDL definition of interface "EventChannel"
* @author JacORB IDL compiler
*/
public class EventChannelPOATie
extends EventChannelPOA
{
private EventChannelOperations _delegate;
private POA _poa;
public EventChannelPOATie(EventChannelOperations delegate)
{
_delegate = delegate;
}
public EventChannelPOATie(EventChannelOperations delegate, POA poa)
{
_delegate = delegate;
_poa = poa;
}
public org.omg.CosEventChannelAdmin.EventChannel _this()
{
return org.omg.CosEventChannelAdmin.EventChannelHelper.narrow(_this_object());
}
public org.omg.CosEventChannelAdmin.EventChannel _this(org.omg.CORBA.ORB orb)
{
return org.omg.CosEventChannelAdmin.EventChannelHelper.narrow(_this_object(orb));
}
public EventChannelOperations _delegate()
{
return _delegate;
}
public void _delegate(EventChannelOperations delegate)
{
_delegate = delegate;
}
public org.omg.CosEventChannelAdmin.ConsumerAdmin for_consumers()
{
return _delegate.for_consumers();
}
public void destroy()
{
_delegate.destroy();
}
public org.omg.CosEventChannelAdmin.SupplierAdmin for_suppliers()
{
return _delegate.for_suppliers();
}
}
| 1,244 | 0.761254 | 0.761254 | 56 | 21.214285 | 25.099598 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.160714 | false | false | 0 |
7f2315296813664f2f62fa764152d23c573134dc | 21,225,728,393,688 | 4f352e6a4ab4272e71d379005d79b5f9c7e0fbda | /src/Aop/util/DBUPUtil.java | 6a79867d2d5505b172eadcf9e355f858ef5a388e | [] | no_license | 123Jun321/AOPDemo | https://github.com/123Jun321/AOPDemo | 7a7d783a289f6df1b09ec1a3f191f36b3e6dc626 | bf20e7864ce54d16e9eb9ebca95e2e725c59bae0 | refs/heads/master | 2021-08-29T01:32:29.876000 | 2017-12-13T09:21:36 | 2017-12-13T09:21:36 | 114,053,775 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Aop.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.dbutils.*;
public class DBUPUtil {
private static DataSource dataSource;
static {
InputStream inputStream = DBUPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties props = new Properties();
try {
props.load(inputStream);
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
}
| UTF-8 | Java | 939 | java | DBUPUtil.java | Java | [] | null | [] | package Aop.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.dbutils.*;
public class DBUPUtil {
private static DataSource dataSource;
static {
InputStream inputStream = DBUPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties props = new Properties();
try {
props.load(inputStream);
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
}
| 939 | 0.766773 | 0.764643 | 40 | 22.475 | 22.969532 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.325 | false | false | 0 |
8cc7263cb601475ecf627a3ecac9e586666fb772 | 14,431,090,140,842 | 19c1cfeccec162afc9bd9a65f2fc0c51107b1372 | /src/main/java/com/example/TestMod/blocks/Amethyst.java | c223761e370590a3e3e1d54c83a135d198f69a77 | [] | no_license | noobguy57/amethystmod | https://github.com/noobguy57/amethystmod | f4d8e878e3ad379041c7f7415c8c717a75c2313f | 72e958d48d73f43e84a7a739a64fc97b538bfec7 | refs/heads/master | 2021-01-01T10:16:53.776000 | 2020-02-09T17:29:14 | 2020-02-09T17:29:14 | 239,235,073 | 0 | 0 | null | false | 2020-02-09T17:29:15 | 2020-02-09T02:30:00 | 2020-02-09T02:38:46 | 2020-02-09T17:29:14 | 5 | 0 | 0 | 0 | Java | false | false | package com.example.TestMod.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
public class Amethyst extends Block
{
public Amethyst(String name, Material material)
{
super(Material.ROCK);
setUnlocalizedName("amethystore");
setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
setRegistryName("amethystore");
setHardness(4.0F);
setHarvestLevel("pickaxe", 2); // 2 = iron or greater 1 = stone, 0 = wood/gold
setSoundType(SoundType.STONE);
setLightLevel(1.0F);
}
}
| UTF-8 | Java | 656 | java | Amethyst.java | Java | [] | null | [] | package com.example.TestMod.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
public class Amethyst extends Block
{
public Amethyst(String name, Material material)
{
super(Material.ROCK);
setUnlocalizedName("amethystore");
setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
setRegistryName("amethystore");
setHardness(4.0F);
setHarvestLevel("pickaxe", 2); // 2 = iron or greater 1 = stone, 0 = wood/gold
setSoundType(SoundType.STONE);
setLightLevel(1.0F);
}
}
| 656 | 0.702744 | 0.690549 | 21 | 30.238094 | 21.531605 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.761905 | false | false | 0 |
011029a055aa61a1789e349f276b399f174d0c1b | 14,431,090,138,231 | 20fe79f2cd442b78c802cca0643b554e3b4207c4 | /src/main/java/bean/GiangVien.java | d6b8006da437bad337739ffcddd52d04b9d21fb9 | [] | no_license | tea1504/Tn208Nhom3 | https://github.com/tea1504/Tn208Nhom3 | f159a63618f3d09659cffc4aa2426fb48e29553a | eb5dab3c0cf44b8708e3bf69ca781392c041454c | refs/heads/master | 2023-06-02T04:00:26.749000 | 2021-06-13T00:42:51 | 2021-06-13T00:42:51 | 372,419,106 | 0 | 0 | null | false | 2021-06-13T00:42:51 | 2021-05-31T07:25:35 | 2021-06-12T16:52:10 | 2021-06-13T00:42:51 | 792 | 0 | 0 | 0 | Java | false | false | package bean;
/**
* Class dùng để lưu dữ liệu giảng viên. Bao gồm:
* <ul>
* <li>Mã giảng viên - <strong>String</strong></li>
* <li>Tên giảng viên - <strong>String</strong></li>
* <li>Quyền sửa dụng - <strong>int</strong></li>
* </ul>
*
* @author Trịnh Thanh Thảo
*
*/
public class GiangVien {
private String maGiangVien;
private String tenGiangVien;
private int quyenSD;
public GiangVien() {
super();
}
/**
* Hàm xây dựng 2 đối số
*
* @param maGiangVien String
* @param tenGiangVien String
*/
public GiangVien(String maGiangVien, String tenGiangVien) {
super();
this.maGiangVien = maGiangVien;
this.tenGiangVien = tenGiangVien;
}
/**
* Hàm xây dựng 3 đối số
*
* @param maGiangVien String
* @param tenGiangVien String
* @param quyenSD int (0-user, 1-admin)
*/
public GiangVien(String maGiangVien, String tenGiangVien, int quyenSD) {
super();
this.maGiangVien = maGiangVien;
this.tenGiangVien = tenGiangVien;
this.quyenSD = quyenSD;
}
public String getMaGiangVien() {
return maGiangVien;
}
public void setMaGiangVien(String maGiangVien) {
this.maGiangVien = maGiangVien;
}
public String getTenGiangVien() {
return tenGiangVien;
}
public void setTenGiangVien(String tenGiangVien) {
this.tenGiangVien = tenGiangVien;
}
public int getQuyenSD() {
return quyenSD;
}
public void setQuyenSD(int quyenSD) {
this.quyenSD = quyenSD;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return getMaGiangVien() + "\t" + getTenGiangVien();
}
}
| UTF-8 | Java | 1,612 | java | GiangVien.java | Java | [
{
"context": " <strong>int</strong></li>\n * </ul>\n * \n * @author Trịnh Thanh Thảo\n *\n */\npublic class GiangVien {\n\tprivate String m",
"end": 272,
"score": 0.9998685121536255,
"start": 256,
"tag": "NAME",
"value": "Trịnh Thanh Thảo"
}
] | null | [] | package bean;
/**
* Class dùng để lưu dữ liệu giảng viên. Bao gồm:
* <ul>
* <li>Mã giảng viên - <strong>String</strong></li>
* <li>Tên giảng viên - <strong>String</strong></li>
* <li>Quyền sửa dụng - <strong>int</strong></li>
* </ul>
*
* @author <NAME>
*
*/
public class GiangVien {
private String maGiangVien;
private String tenGiangVien;
private int quyenSD;
public GiangVien() {
super();
}
/**
* Hàm xây dựng 2 đối số
*
* @param maGiangVien String
* @param tenGiangVien String
*/
public GiangVien(String maGiangVien, String tenGiangVien) {
super();
this.maGiangVien = maGiangVien;
this.tenGiangVien = tenGiangVien;
}
/**
* Hàm xây dựng 3 đối số
*
* @param maGiangVien String
* @param tenGiangVien String
* @param quyenSD int (0-user, 1-admin)
*/
public GiangVien(String maGiangVien, String tenGiangVien, int quyenSD) {
super();
this.maGiangVien = maGiangVien;
this.tenGiangVien = tenGiangVien;
this.quyenSD = quyenSD;
}
public String getMaGiangVien() {
return maGiangVien;
}
public void setMaGiangVien(String maGiangVien) {
this.maGiangVien = maGiangVien;
}
public String getTenGiangVien() {
return tenGiangVien;
}
public void setTenGiangVien(String tenGiangVien) {
this.tenGiangVien = tenGiangVien;
}
public int getQuyenSD() {
return quyenSD;
}
public void setQuyenSD(int quyenSD) {
this.quyenSD = quyenSD;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return getMaGiangVien() + "\t" + getTenGiangVien();
}
}
| 1,598 | 0.681818 | 0.679257 | 78 | 19.02564 | 18.238432 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.179487 | false | false | 0 |
a747c8fddf927559ffa93a2d1b9be51256532f3f | 6,871,947,704,891 | 6f4824702a6d84e9eb4383bf2e84cb0e36ba8299 | /java/DAY1/Large_number_q10.java | d375ad2b315f5912dfa7b17bd77cd33b0e97d824 | [] | no_license | roykishan8/20247_kishan_dailypractice | https://github.com/roykishan8/20247_kishan_dailypractice | c2a3e6ebb82313f369f254ee4240020072b18ad3 | 69f87329a66918b8c270b59e0a4bc532130c0dca | refs/heads/main | 2023-07-15T21:12:29.323000 | 2021-08-31T10:20:17 | 2021-08-31T10:20:17 | 392,963,413 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ASSIGNMENT;
public class Large_number_q10 {
public static void main(String[] args) {
int arr[]= {3,8,45,26,7,9};
int max1=arr[0];
int max2=max1;
for(int i=0;i<arr.length;i++) {
if (max2<arr[i]) {
max1=max2;
max2=arr[i];
}else if(max1<arr[i]) {
max1=arr[i];
}
}
System.out.println(max1+" "+max2);
}
}
| UTF-8 | Java | 380 | java | Large_number_q10.java | Java | [] | null | [] | package ASSIGNMENT;
public class Large_number_q10 {
public static void main(String[] args) {
int arr[]= {3,8,45,26,7,9};
int max1=arr[0];
int max2=max1;
for(int i=0;i<arr.length;i++) {
if (max2<arr[i]) {
max1=max2;
max2=arr[i];
}else if(max1<arr[i]) {
max1=arr[i];
}
}
System.out.println(max1+" "+max2);
}
}
| 380 | 0.523684 | 0.463158 | 21 | 16.095238 | 13.273335 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.380952 | false | false | 0 |
2ff5e851c3cdd6b57ec2ae9831a78734c4d4a5ba | 24,730,421,714,968 | 2b18730375d88084ac68461520e1f923875db3ef | /app/src/main/java/duongmh3/bittrexmanager/common/Util.java | 7f9ccc5ee718611e6d8f64f81edfd2403fd5c3fc | [] | no_license | alimogh/BittrexWarningAndroid | https://github.com/alimogh/BittrexWarningAndroid | a97f35c1e01644438a740f48d12f03306f292b72 | 0282dfeaa62636ce321f87b083b0cc209f807185 | refs/heads/master | 2021-06-20T04:32:49.673000 | 2017-07-15T04:46:13 | 2017-07-15T04:46:13 | 281,206,735 | 1 | 0 | null | true | 2020-07-20T19:23:33 | 2020-07-20T19:23:32 | 2020-07-20T19:23:26 | 2017-07-15T04:46:25 | 7,355 | 0 | 0 | 0 | null | false | false | package duongmh3.bittrexmanager.common;
import android.content.Context;
import android.content.Intent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import android.net.Uri;
import android.os.AsyncTask;
/**
* Created by duongmatheo on 7/12/17.
*/
public class Util {
public static void checkAndCancelTasks(AsyncTask task) {
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
}
}
public static void showWebBrowserByMarketName(Context context, String marketName) {
String url = "https://bittrex.com/Market/Index?MarketName=" + marketName;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
public static String formatNumber(double value, String format) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat numberFormat = new DecimalFormat(format, symbols);
return numberFormat.format(value);
}
}
| UTF-8 | Java | 1,126 | java | Util.java | Java | [
{
"context": "i;\nimport android.os.AsyncTask;\n\n/**\n * Created by duongmatheo on 7/12/17.\n */\n\npublic class Util {\n public s",
"end": 316,
"score": 0.9995778799057007,
"start": 305,
"tag": "USERNAME",
"value": "duongmatheo"
}
] | null | [] | package duongmh3.bittrexmanager.common;
import android.content.Context;
import android.content.Intent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
import android.net.Uri;
import android.os.AsyncTask;
/**
* Created by duongmatheo on 7/12/17.
*/
public class Util {
public static void checkAndCancelTasks(AsyncTask task) {
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
}
}
public static void showWebBrowserByMarketName(Context context, String marketName) {
String url = "https://bittrex.com/Market/Index?MarketName=" + marketName;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
public static String formatNumber(double value, String format) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
DecimalFormat numberFormat = new DecimalFormat(format, symbols);
return numberFormat.format(value);
}
}
| 1,126 | 0.711368 | 0.706039 | 37 | 29.432432 | 26.911808 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 0 |
bc4c83f09e4f7dfb0cb4bca80646af518a428530 | 29,738,353,599,921 | 026e926de627cc08bd80d17fd8fa5a21241f9bb5 | /src/main/java/com/playbuzz/automation/core/enums/Browser.java | ed476b6938d2d15ea59900f5f5b82c0a7f29dcfa | [] | no_license | AROS-/playbuzz | https://github.com/AROS-/playbuzz | 6d583f827c3519fd8f6ef19add28f4eac536f3d6 | cec1771b9a79c98705a310e36ec1c7376cddaf6d | refs/heads/master | 2020-04-19T04:24:49.519000 | 2019-01-29T20:09:18 | 2019-01-29T20:09:18 | 167,962,141 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.playbuzz.automation.core.enums;
import java.util.regex.Pattern;
public enum Browser {
CHROME("chrome"),
FIREFOX("firefox");
private static final Pattern FFPattern = Pattern.compile("(?i)F(ire)?.?F(ox)?.*");
private static final Pattern CHROMEPattern = Pattern.compile("(?i)G?(OOGLE)?.?C(HROME)?.*");
private final String browser;
Browser(String browser) {
this.browser = browser;
}
public static Browser getBrowser(String browser) {
if (CHROMEPattern.matcher(browser).matches()) {
return CHROME;
} else if (FFPattern.matcher(browser).matches()) {
return FIREFOX;
} else {
throw new RuntimeException(browser + " is not supported browser");
}
}
}
| UTF-8 | Java | 777 | java | Browser.java | Java | [] | null | [] | package com.playbuzz.automation.core.enums;
import java.util.regex.Pattern;
public enum Browser {
CHROME("chrome"),
FIREFOX("firefox");
private static final Pattern FFPattern = Pattern.compile("(?i)F(ire)?.?F(ox)?.*");
private static final Pattern CHROMEPattern = Pattern.compile("(?i)G?(OOGLE)?.?C(HROME)?.*");
private final String browser;
Browser(String browser) {
this.browser = browser;
}
public static Browser getBrowser(String browser) {
if (CHROMEPattern.matcher(browser).matches()) {
return CHROME;
} else if (FFPattern.matcher(browser).matches()) {
return FIREFOX;
} else {
throw new RuntimeException(browser + " is not supported browser");
}
}
}
| 777 | 0.624196 | 0.624196 | 29 | 25.793104 | 27.299589 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.37931 | false | false | 0 |
4a8d64ad364a5f1d06d593daea4fee97b1c256b6 | 36,301,063,592,923 | 203569b0594a4aff733e5bf14f0dd0d08d6fd2c0 | /csc326-204-Project-03-master/iTrust/test/edu/ncsu/csc/itrust/unit/action/OrthopedicVisitActionTest.java | f93e7ace32e30f8e4d4d78613f774d210b0a7aa5 | [] | no_license | shuxiangru/CSC326-Software-Engineering | https://github.com/shuxiangru/CSC326-Software-Engineering | c20f35c8fe33c67d6fb5090b49e2da2871e9e0a3 | 818ae867824b454ef53314e418b0031c3181d1fc | refs/heads/master | 2021-08-19T16:18:52.536000 | 2017-11-26T21:57:17 | 2017-11-26T21:57:17 | 112,111,788 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package edu.ncsu.csc.itrust.unit.action;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.ncsu.csc.itrust.action.OrthopedicVisitAction;
import edu.ncsu.csc.itrust.beans.OrthopedicVisitBean;
import edu.ncsu.csc.itrust.dao.DAOFactory;
import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator;
import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory;
/**
* @author yuxuyang
*
*/
public class OrthopedicVisitActionTest {
private DAOFactory factory = TestDAOFactory.getTestInstance();
private OrthopedicVisitAction ova;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
ova = new OrthopedicVisitAction(factory, (long)10, "1000");
TestDataGenerator gen = new TestDataGenerator();
gen.clearAllTables();
gen.standardData();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void test() throws Exception {
OrthopedicVisitBean orb = new OrthopedicVisitBean();
orb.setACLinjury((short)0);
orb.setChondromalacia((short)1);
orb.setCPC((short)-1);
orb.setRAhand((short)0);
orb.setWhiplashinjury((short)1);
orb.setMeniscusTear((short)1);
orb.setOrthopedicVisitID(1123901923);
orb.setPatientID(ova.getPid());
orb.setInjuredLimbJoint("It's funny!!!!!!!!");
orb.setMRIreport("We need help");
orb.setOrthopedicVisitDate("12/02/2012");
byte[] a = "Any String you want".getBytes();
orb.setMRI(a);
byte[] b = "Any thing you want".getBytes();
orb.setXRay(b);
ova.addBean(orb);
List<OrthopedicVisitBean> bl = ova.getAllOrthopedicVisits(1000);
assertEquals(bl.size(),1);
OrthopedicVisitBean OVB = bl.get(0);
assertEquals(OVB.getACLinjury(), orb.getACLinjury());
assertEquals(OVB.getChondromalacia(), orb.getChondromalacia());
assertEquals(OVB.getCPC(), orb.getCPC());
assertTrue(OVB.getInjuredLimbJoint().equals(orb.getInjuredLimbJoint()));
assertTrue(OVB.getMRIreport().equals(orb.getMRIreport()));
assertTrue(new String (OVB.getXRay()).equals(new String(orb.getXRay())));
assertTrue(new String (OVB.getMRI()).equals(new String(orb.getMRI())));
assertTrue(OVB.getOrthopedicVisitDateString().equals(orb.getOrthopedicVisitDateString()));
byte[] t = "Louis needs help".getBytes();
orb.setMRI(t);
ova.editBean(orb);
List<OrthopedicVisitBean> nbl = ova.getAllOrthopedicVisits(1000);
assertEquals(nbl.size(),1);
OrthopedicVisitBean nOVB = nbl.get(0);
assertTrue(new String (nOVB.getMRI()).equals(new String(t)));
assertEquals( ova.getPid(), 1000);
OrthopedicVisitBean nwOVB = ova.viewBean(1);
assertEquals(nwOVB.getACLinjury(), orb.getACLinjury());
}
}
| UTF-8 | Java | 2,751 | java | OrthopedicVisitActionTest.java | Java | [
{
"context": "ust.unit.testutils.TestDAOFactory;\n\n/**\n * @author yuxuyang\n *\n */\npublic class OrthopedicVisitActionTest {\n\t",
"end": 488,
"score": 0.9995400905609131,
"start": 480,
"tag": "USERNAME",
"value": "yuxuyang"
}
] | null | [] | /**
*
*/
package edu.ncsu.csc.itrust.unit.action;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import edu.ncsu.csc.itrust.action.OrthopedicVisitAction;
import edu.ncsu.csc.itrust.beans.OrthopedicVisitBean;
import edu.ncsu.csc.itrust.dao.DAOFactory;
import edu.ncsu.csc.itrust.unit.datagenerators.TestDataGenerator;
import edu.ncsu.csc.itrust.unit.testutils.TestDAOFactory;
/**
* @author yuxuyang
*
*/
public class OrthopedicVisitActionTest {
private DAOFactory factory = TestDAOFactory.getTestInstance();
private OrthopedicVisitAction ova;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
ova = new OrthopedicVisitAction(factory, (long)10, "1000");
TestDataGenerator gen = new TestDataGenerator();
gen.clearAllTables();
gen.standardData();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void test() throws Exception {
OrthopedicVisitBean orb = new OrthopedicVisitBean();
orb.setACLinjury((short)0);
orb.setChondromalacia((short)1);
orb.setCPC((short)-1);
orb.setRAhand((short)0);
orb.setWhiplashinjury((short)1);
orb.setMeniscusTear((short)1);
orb.setOrthopedicVisitID(1123901923);
orb.setPatientID(ova.getPid());
orb.setInjuredLimbJoint("It's funny!!!!!!!!");
orb.setMRIreport("We need help");
orb.setOrthopedicVisitDate("12/02/2012");
byte[] a = "Any String you want".getBytes();
orb.setMRI(a);
byte[] b = "Any thing you want".getBytes();
orb.setXRay(b);
ova.addBean(orb);
List<OrthopedicVisitBean> bl = ova.getAllOrthopedicVisits(1000);
assertEquals(bl.size(),1);
OrthopedicVisitBean OVB = bl.get(0);
assertEquals(OVB.getACLinjury(), orb.getACLinjury());
assertEquals(OVB.getChondromalacia(), orb.getChondromalacia());
assertEquals(OVB.getCPC(), orb.getCPC());
assertTrue(OVB.getInjuredLimbJoint().equals(orb.getInjuredLimbJoint()));
assertTrue(OVB.getMRIreport().equals(orb.getMRIreport()));
assertTrue(new String (OVB.getXRay()).equals(new String(orb.getXRay())));
assertTrue(new String (OVB.getMRI()).equals(new String(orb.getMRI())));
assertTrue(OVB.getOrthopedicVisitDateString().equals(orb.getOrthopedicVisitDateString()));
byte[] t = "Louis needs help".getBytes();
orb.setMRI(t);
ova.editBean(orb);
List<OrthopedicVisitBean> nbl = ova.getAllOrthopedicVisits(1000);
assertEquals(nbl.size(),1);
OrthopedicVisitBean nOVB = nbl.get(0);
assertTrue(new String (nOVB.getMRI()).equals(new String(t)));
assertEquals( ova.getPid(), 1000);
OrthopedicVisitBean nwOVB = ova.viewBean(1);
assertEquals(nwOVB.getACLinjury(), orb.getACLinjury());
}
}
| 2,751 | 0.728462 | 0.711378 | 91 | 29.23077 | 23.250229 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.912088 | false | false | 0 |
ba1a596e67b7a051105082c49288d443899bf87d | 29,935,922,116,676 | 4c9c50eddc7038e7aebcaf70e717056afe80d4cc | /ftp-server/src/test/java/uk/org/windswept/resultsmanager/ftp/ServerTest.java | 2243cda31ad2c1e8dae84133b57282cc658d3afe | [] | no_license | atkinssk/results-manager | https://github.com/atkinssk/results-manager | ed3dd251e02af6b6142b021f7b89b1be2d7045db | ffb4f8d87c57d2e4eaf514f383154a46c85d9747 | refs/heads/master | 2020-04-05T19:03:37.265000 | 2016-10-22T10:58:42 | 2016-10-22T10:58:42 | 68,700,507 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.org.windswept.resultsmanager.ftp;
import org.apache.commons.io.FileUtils;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.junit.Assert.assertThat;
import static uk.org.windswept.test.file.FileMatchers.exists;
import static uk.org.windswept.test.file.FileMatchers.isFile;
/**
* Created by 802998369 on 20/09/2016.
*/
public class ServerTest
{
private static final Logger LOGGER = LoggerFactory.getLogger(ServerTest.class);
public static final int PORT = 2222;
public static final File USER_HOME_DIRECTORY = FileUtils.getFile("target", "userWorkingDirectory");
private Server server;
private LoggingFtplet loggingFtplet;
private List<Authority> createAuthorities(Authority... authorities)
{
return newArrayList(authorities);
}
private UserManager createUserManager () throws IOException, FtpException
{
final File userPropertiesFile = new File("target/users.properties");
Properties userProperties = new Properties();
userProperties.store(new FileWriter(userPropertiesFile),"User Properties");
PropertiesUserManagerFactory factory = new PropertiesUserManagerFactory();
factory.setFile(userPropertiesFile);
UserManager userManager = factory.createUserManager();
BaseUser user = new BaseUser();
user.setName("test");
user.setPassword("test");
user.setHomeDirectory(USER_HOME_DIRECTORY.getPath());
user.setAuthorities(createAuthorities(new WritePermission()));
userManager.save(user);
return userManager;
}
@Before
public void startServer () throws IOException, FtpException
{
UserManager userManager = createUserManager();
loggingFtplet = new LoggingFtplet();
server = new Server().
withUserManager(userManager).
withPort(PORT).
withFtplet(loggingFtplet).
withCallbackFtplet();
server.start();
}
@Before
public void clearWorkingDirectory() throws IOException
{
if(!USER_HOME_DIRECTORY.exists())
{
LOGGER.info("Create User Home Directory {}", USER_HOME_DIRECTORY);
assertThat("Unable to create User Home Directory", USER_HOME_DIRECTORY.mkdirs(), is(true));
}
else
{
LOGGER.info("Clear User Home Directory {}", USER_HOME_DIRECTORY);
FileUtils.cleanDirectory(USER_HOME_DIRECTORY);
}
}
@After
public void stopServer ()
{
server.stop();
}
private FtpClientHelper getFtpClientHelper() throws IOException
{
return new FtpClientHelper(InetAddress.getLocalHost(), PORT, "test", "test");
}
@Test
public void shouldStartServer() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
List<String> files = client.listFileNames();
assertThat(files, empty());
}
@Test
public void shouldUploadFileToUserHomeDirectory() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
String remote = "results.html";
URL resultsFile = getClass().getClassLoader().getResource("data/results.html");
LOGGER.info("Loading results from {}", resultsFile);
assertThat(client.storeFile(resultsFile, remote), is(true));
// Should exist in target directory now
File outputFile = new File(USER_HOME_DIRECTORY, remote);
assertThat(outputFile, allOf(exists(), isFile()));
// Should be returned by the ftp server list command
List<String> filenames = client.listFileNames();
assertThat(filenames, hasItem("results.html"));
}
@Test
public void shouldUploadFileToSubDirectory() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
String remoteDir = "2016/DinghyRegatta";
String remote = remoteDir + "/results.html";
URL resultsFile = getClass().getClassLoader().getResource("data/results.html");
LOGGER.info("Loading results from {}", resultsFile);
assertThat(client.storeFile(resultsFile, remote), is(true));
// Should exist in target directory now
File outputFile = new File(USER_HOME_DIRECTORY, remote);
assertThat(outputFile, allOf(exists(), isFile()));
// Should be returned by the ftp server list command
List<String> filenames = client.listFileNames(remoteDir);
assertThat(filenames, hasItem("results.html"));
}
@Test
@Ignore("This is only for investigation")
public void shouldWaitForDisconnect() throws InterruptedException
{
LOGGER.info("Waiting for disconnect callback");
loggingFtplet.waitForDisconnect();
}
} | UTF-8 | Java | 5,658 | java | ServerTest.java | Java | [
{
"context": "User user = new BaseUser();\n user.setName(\"test\");\n user.setPassword(\"test\");\n user",
"end": 2235,
"score": 0.9991220235824585,
"start": 2231,
"tag": "USERNAME",
"value": "test"
},
{
"context": " user.setName(\"test\");\n user.setPass... | null | [] | package uk.org.windswept.resultsmanager.ftp;
import org.apache.commons.io.FileUtils;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.junit.Assert.assertThat;
import static uk.org.windswept.test.file.FileMatchers.exists;
import static uk.org.windswept.test.file.FileMatchers.isFile;
/**
* Created by 802998369 on 20/09/2016.
*/
public class ServerTest
{
private static final Logger LOGGER = LoggerFactory.getLogger(ServerTest.class);
public static final int PORT = 2222;
public static final File USER_HOME_DIRECTORY = FileUtils.getFile("target", "userWorkingDirectory");
private Server server;
private LoggingFtplet loggingFtplet;
private List<Authority> createAuthorities(Authority... authorities)
{
return newArrayList(authorities);
}
private UserManager createUserManager () throws IOException, FtpException
{
final File userPropertiesFile = new File("target/users.properties");
Properties userProperties = new Properties();
userProperties.store(new FileWriter(userPropertiesFile),"User Properties");
PropertiesUserManagerFactory factory = new PropertiesUserManagerFactory();
factory.setFile(userPropertiesFile);
UserManager userManager = factory.createUserManager();
BaseUser user = new BaseUser();
user.setName("test");
user.setPassword("<PASSWORD>");
user.setHomeDirectory(USER_HOME_DIRECTORY.getPath());
user.setAuthorities(createAuthorities(new WritePermission()));
userManager.save(user);
return userManager;
}
@Before
public void startServer () throws IOException, FtpException
{
UserManager userManager = createUserManager();
loggingFtplet = new LoggingFtplet();
server = new Server().
withUserManager(userManager).
withPort(PORT).
withFtplet(loggingFtplet).
withCallbackFtplet();
server.start();
}
@Before
public void clearWorkingDirectory() throws IOException
{
if(!USER_HOME_DIRECTORY.exists())
{
LOGGER.info("Create User Home Directory {}", USER_HOME_DIRECTORY);
assertThat("Unable to create User Home Directory", USER_HOME_DIRECTORY.mkdirs(), is(true));
}
else
{
LOGGER.info("Clear User Home Directory {}", USER_HOME_DIRECTORY);
FileUtils.cleanDirectory(USER_HOME_DIRECTORY);
}
}
@After
public void stopServer ()
{
server.stop();
}
private FtpClientHelper getFtpClientHelper() throws IOException
{
return new FtpClientHelper(InetAddress.getLocalHost(), PORT, "test", "test");
}
@Test
public void shouldStartServer() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
List<String> files = client.listFileNames();
assertThat(files, empty());
}
@Test
public void shouldUploadFileToUserHomeDirectory() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
String remote = "results.html";
URL resultsFile = getClass().getClassLoader().getResource("data/results.html");
LOGGER.info("Loading results from {}", resultsFile);
assertThat(client.storeFile(resultsFile, remote), is(true));
// Should exist in target directory now
File outputFile = new File(USER_HOME_DIRECTORY, remote);
assertThat(outputFile, allOf(exists(), isFile()));
// Should be returned by the ftp server list command
List<String> filenames = client.listFileNames();
assertThat(filenames, hasItem("results.html"));
}
@Test
public void shouldUploadFileToSubDirectory() throws Exception
{
FtpClientHelper client = getFtpClientHelper();
String remoteDir = "2016/DinghyRegatta";
String remote = remoteDir + "/results.html";
URL resultsFile = getClass().getClassLoader().getResource("data/results.html");
LOGGER.info("Loading results from {}", resultsFile);
assertThat(client.storeFile(resultsFile, remote), is(true));
// Should exist in target directory now
File outputFile = new File(USER_HOME_DIRECTORY, remote);
assertThat(outputFile, allOf(exists(), isFile()));
// Should be returned by the ftp server list command
List<String> filenames = client.listFileNames(remoteDir);
assertThat(filenames, hasItem("results.html"));
}
@Test
@Ignore("This is only for investigation")
public void shouldWaitForDisconnect() throws InterruptedException
{
LOGGER.info("Waiting for disconnect callback");
loggingFtplet.waitForDisconnect();
}
} | 5,664 | 0.693708 | 0.688936 | 168 | 32.684525 | 27.412445 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 0 |
df0ac3371039b288100f2b1b6f64ad82f92a048f | 11,252,814,353,343 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i62271.java | 4dbcd8cc7e951609eadf437e2e1d971fb718ea77 | [] | no_license | vincentclee/jvm-limits | https://github.com/vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711000 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package number_of_direct_superinterfaces;
public interface i62271 {} | UTF-8 | Java | 69 | java | i62271.java | Java | [] | null | [] | package number_of_direct_superinterfaces;
public interface i62271 {} | 69 | 0.826087 | 0.753623 | 3 | 22.333334 | 16.937796 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
d9d554f0c8e47cc15e3cdaaf258e33706c151357 | 35,596,688,950,905 | 81fbb822093374f47ea071872e34069a408210f3 | /src/main/java/uet/jcia/model/parser/HASTVisitor.java | 254c4d9eacaa46031a7e340c7d87c3ffacbb5b53 | [] | no_license | JCIA-UET/hcia-v2 | https://github.com/JCIA-UET/hcia-v2 | 3aa822d1cc4e5201b3060960922e135e4ec5399e | 78cc2c7d597edfc97a51b0a8a41f8abaecd51592 | refs/heads/master | 2020-04-10T21:57:56.756000 | 2016-11-01T18:22:08 | 2016-11-01T18:22:08 | 63,404,181 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uet.jcia.model.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.AttributeOverrides;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import uet.jcia.data.node.ColumnNode;
import uet.jcia.data.node.CompositePkNode;
import uet.jcia.data.node.MTORelationshipNode;
import uet.jcia.data.node.OTMRelationshipNode;
import uet.jcia.data.node.PrimaryKeyNode;
import uet.jcia.data.node.TableNode;
import uet.jcia.data.node.TreeNode;
import uet.jcia.utils.SqlTypeMapper;
public class HASTVisitor extends ASTVisitor {
private static final String SQL_TABLE = "Table";
private static final String SQL_COLUMN = "Column";
private static final String SQL_OTM = "One-to-Many";
private static final String SQL_MTO = "Many-to-One";
private static final String EMBEDDED_ID = "EmbeddedId";
private static final Object ATTRIBUTE_OVERRIDES = "AttributeOverrides";
private static long tempId = 0L;
private TableNode table;
private List<TreeNode> children;
/**
* mapping between className and tableNode
*/
private Map<String, TableNode> cachedTables;
public HASTVisitor() {
cachedTables = new HashMap<>();
}
public long generateTempId() {
return tempId++;
}
public TableNode getTable() {
return table;
}
public TableNode getTableNodeByClassName(String className) {
return cachedTables.get(className);
}
@Override
public boolean visit(TypeDeclaration node) {
List modifiers = node.modifiers();
String tableName = null;
String catalog = null;
String className = null;
// check if class is a hibernate Entity
boolean isEntity = false;
boolean hasTableValues = false;
List<MemberValuePair> tableValues = null;
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation ano = (Annotation) modifier;
if (ano.getTypeName().toString().equals("Entity")) {
isEntity = true;
} else if (ano.getTypeName().toString().equals("Table")
&& ano instanceof NormalAnnotation) {
hasTableValues = true;
tableValues = ((NormalAnnotation) ano).values();
}
}
}
if (!isEntity) {
table = null;
return false;
}
className = node.getName().getFullyQualifiedName();
if (isEntity && !hasTableValues) {
tableName = node.getName().getIdentifier();
} else if (isEntity && hasTableValues){
for (MemberValuePair val : tableValues) {
if (val.getName().toString().equals("name")) {
tableName = val.getValue().toString().replace("\"", "");
} else if (val.getName().toString().equals("catalog")) {
catalog = val.getValue().toString().replace("\"", "");
}
}
}
table = new TableNode();
children = new ArrayList<>();
table.setChilds(children);
table.setTableName(tableName);
table.setClassName(className);
table.setCatalog(catalog);
table.setTempId(generateTempId());
cachedTables.put(className, table);
return true;
}
@Override
public boolean visit(MethodDeclaration node) {
if (table == null) return false;
List modifiers = node.modifiers();
// get type of element
String elementType = getElementType(modifiers);
Type returnType = node.getReturnType2();
if (elementType.equals(SQL_COLUMN)) {
children.add(parseColumn(modifiers, returnType));
} else if (elementType.equals(SQL_OTM)) {
children.add(parseOtm(modifiers, returnType));
} else if (elementType.equals(SQL_MTO)) {
children.add(parseMto(modifiers, returnType));
} else if (elementType.equals(EMBEDDED_ID)) {
children.add(parseEmbeddedId(modifiers));
} else {
return false;
}
return true;
}
private TreeNode parseEmbeddedId(List modifiers) {
for (Object modifier : modifiers) {
if (modifier instanceof SingleMemberAnnotation
&& ((SingleMemberAnnotation) modifier).getTypeName().toString().equals(ATTRIBUTE_OVERRIDES)) {
SingleMemberAnnotation anno = (SingleMemberAnnotation) modifier;
if (anno.getValue() instanceof ArrayInitializer) {
ArrayInitializer attArr = (ArrayInitializer) anno.getValue();
List children = attArr.expressions();
CompositePkNode compositePk = new CompositePkNode();
for (Object child : children) {
if (child instanceof NormalAnnotation) {
ColumnNode fk = new ColumnNode();
String columnName = "";
for (Object p : ((NormalAnnotation) child).values()) {
MemberValuePair pair = (MemberValuePair) p;
if (pair.getName().toString().equals("name")) {
columnName = pair.getValue().toString().replace("\"", "");
}
}
fk.setColumnName(columnName);
compositePk.getFkList().add(fk);
}
}
return compositePk;
}
}
}
return null;
}
private MTORelationshipNode parseMto(List modifiers, Type returnType) {
MTORelationshipNode mto = new MTORelationshipNode();
mto.setType(SQL_MTO);
String referClassName = null;
List<MemberValuePair> joinColumnValues = null;
String fkColumnName = null;
// get foreign key column name
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation anno = (Annotation) modifier;
if (anno.getTypeName().toString().equals("JoinColumn")
&& anno instanceof NormalAnnotation) {
joinColumnValues = ((NormalAnnotation)anno).values();
}
}
}
for (MemberValuePair pair : joinColumnValues) {
if (pair.getName().toString().equals("name")) {
fkColumnName = pair.getValue().toString().replace("\"", "");
}
}
// refer class here
if (returnType.isSimpleType()) {
referClassName = ((SimpleType)returnType).getName().getFullyQualifiedName();
}
ColumnNode foreignKey = new ColumnNode();
foreignKey.setForeignKey(true);
foreignKey.setColumnName(fkColumnName);
TableNode referTable = new TableNode();
referTable.setClassName(referClassName);
mto.setReferTable(referTable);
mto.setForeignKey(foreignKey);
mto.setTempId(generateTempId());
return mto;
}
private OTMRelationshipNode parseOtm(List modifiers, Type returnType) {
OTMRelationshipNode otm = new OTMRelationshipNode();
otm.setType(SQL_OTM);
String referClassName = null;
// get type here
if (returnType.isParameterizedType()) {
ParameterizedType pReturnType = (ParameterizedType) returnType;
Object argument = pReturnType.typeArguments().get(0);
if (argument instanceof SimpleType) {
referClassName = ((SimpleType)argument).getName().getFullyQualifiedName();
}
}
TableNode referTable = new TableNode();
referTable.setClassName(referClassName);
otm.setReferTable(referTable);
otm.setTempId(generateTempId());
return otm;
}
private ColumnNode parseColumn(List modifiers, Type returnType) {
List<MemberValuePair> columnValues = null;
String columnName = null;
String javaType = null;
int length = 0;
boolean isPK = false;
boolean isUQ = false;
boolean isNN = false;
// get column name, length, pk, uq, nn here
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation anno = (Annotation) modifier;
if (anno.getTypeName().toString().equals("Id")) {
isPK = true;
} else if (anno.getTypeName().toString().equals("Column")
&& anno instanceof NormalAnnotation) {
columnValues = ((NormalAnnotation)anno).values();
}
}
}
for (MemberValuePair pair : columnValues) {
if (pair.getName().toString().equals("name")) {
columnName = pair.getValue().toString().replace("\"", "");
} else if (pair.getName().toString().equals("length")) {
length = Integer.parseInt(pair.getValue().toString());
} else if ((pair.getName().toString().equals("unique"))
&& pair.getValue().toString().equals("true")) {
isUQ = true;
} else if ((pair.getName().toString().equals("nullable"))
&& pair.getValue().toString().equals("false")) {
isNN = true;
}
}
// get type here
if (returnType.isPrimitiveType()) {
javaType = ((PrimitiveType)returnType).getPrimitiveTypeCode().toString();
} else if (returnType.isSimpleType()) {
javaType = ((SimpleType)returnType).getName().getFullyQualifiedName();
}
ColumnNode column = null;
if (isPK) {
column = new PrimaryKeyNode();
} else {
column = new ColumnNode();
}
column.setColumnName(columnName);
column.setJavaName(columnName);
column.setDataType(SqlTypeMapper.getHbmtoSql(javaType));
column.setLength(length);
column.setPrimaryKey(isPK);
column.setUnique(isUQ);
column.setNotNull(isNN);
column.setTempId(generateTempId());
return column;
}
/**
* Table, Column, MTO, OTM
* @return
*/
private String getElementType(List modifiers) {
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation annotation = (Annotation) modifier;
if (annotation.getTypeName().toString().equals(EMBEDDED_ID)) {
return EMBEDDED_ID;
} else if (annotation.getTypeName().toString().equals("Entity")) {
return SQL_TABLE;
} else if (annotation.getTypeName().toString().equals("Column")) {
return SQL_COLUMN;
} else if (annotation.getTypeName().toString().equals("OneToMany")) {
return SQL_OTM;
} else if (annotation.getTypeName().toString().equals("ManyToOne")) {
return SQL_MTO;
}
}
}
return "";
}
}
| UTF-8 | Java | 11,955 | java | HASTVisitor.java | Java | [] | null | [] | package uet.jcia.model.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.AttributeOverrides;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.ArrayInitializer;
import org.eclipse.jdt.core.dom.MemberValuePair;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import uet.jcia.data.node.ColumnNode;
import uet.jcia.data.node.CompositePkNode;
import uet.jcia.data.node.MTORelationshipNode;
import uet.jcia.data.node.OTMRelationshipNode;
import uet.jcia.data.node.PrimaryKeyNode;
import uet.jcia.data.node.TableNode;
import uet.jcia.data.node.TreeNode;
import uet.jcia.utils.SqlTypeMapper;
public class HASTVisitor extends ASTVisitor {
private static final String SQL_TABLE = "Table";
private static final String SQL_COLUMN = "Column";
private static final String SQL_OTM = "One-to-Many";
private static final String SQL_MTO = "Many-to-One";
private static final String EMBEDDED_ID = "EmbeddedId";
private static final Object ATTRIBUTE_OVERRIDES = "AttributeOverrides";
private static long tempId = 0L;
private TableNode table;
private List<TreeNode> children;
/**
* mapping between className and tableNode
*/
private Map<String, TableNode> cachedTables;
public HASTVisitor() {
cachedTables = new HashMap<>();
}
public long generateTempId() {
return tempId++;
}
public TableNode getTable() {
return table;
}
public TableNode getTableNodeByClassName(String className) {
return cachedTables.get(className);
}
@Override
public boolean visit(TypeDeclaration node) {
List modifiers = node.modifiers();
String tableName = null;
String catalog = null;
String className = null;
// check if class is a hibernate Entity
boolean isEntity = false;
boolean hasTableValues = false;
List<MemberValuePair> tableValues = null;
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation ano = (Annotation) modifier;
if (ano.getTypeName().toString().equals("Entity")) {
isEntity = true;
} else if (ano.getTypeName().toString().equals("Table")
&& ano instanceof NormalAnnotation) {
hasTableValues = true;
tableValues = ((NormalAnnotation) ano).values();
}
}
}
if (!isEntity) {
table = null;
return false;
}
className = node.getName().getFullyQualifiedName();
if (isEntity && !hasTableValues) {
tableName = node.getName().getIdentifier();
} else if (isEntity && hasTableValues){
for (MemberValuePair val : tableValues) {
if (val.getName().toString().equals("name")) {
tableName = val.getValue().toString().replace("\"", "");
} else if (val.getName().toString().equals("catalog")) {
catalog = val.getValue().toString().replace("\"", "");
}
}
}
table = new TableNode();
children = new ArrayList<>();
table.setChilds(children);
table.setTableName(tableName);
table.setClassName(className);
table.setCatalog(catalog);
table.setTempId(generateTempId());
cachedTables.put(className, table);
return true;
}
@Override
public boolean visit(MethodDeclaration node) {
if (table == null) return false;
List modifiers = node.modifiers();
// get type of element
String elementType = getElementType(modifiers);
Type returnType = node.getReturnType2();
if (elementType.equals(SQL_COLUMN)) {
children.add(parseColumn(modifiers, returnType));
} else if (elementType.equals(SQL_OTM)) {
children.add(parseOtm(modifiers, returnType));
} else if (elementType.equals(SQL_MTO)) {
children.add(parseMto(modifiers, returnType));
} else if (elementType.equals(EMBEDDED_ID)) {
children.add(parseEmbeddedId(modifiers));
} else {
return false;
}
return true;
}
private TreeNode parseEmbeddedId(List modifiers) {
for (Object modifier : modifiers) {
if (modifier instanceof SingleMemberAnnotation
&& ((SingleMemberAnnotation) modifier).getTypeName().toString().equals(ATTRIBUTE_OVERRIDES)) {
SingleMemberAnnotation anno = (SingleMemberAnnotation) modifier;
if (anno.getValue() instanceof ArrayInitializer) {
ArrayInitializer attArr = (ArrayInitializer) anno.getValue();
List children = attArr.expressions();
CompositePkNode compositePk = new CompositePkNode();
for (Object child : children) {
if (child instanceof NormalAnnotation) {
ColumnNode fk = new ColumnNode();
String columnName = "";
for (Object p : ((NormalAnnotation) child).values()) {
MemberValuePair pair = (MemberValuePair) p;
if (pair.getName().toString().equals("name")) {
columnName = pair.getValue().toString().replace("\"", "");
}
}
fk.setColumnName(columnName);
compositePk.getFkList().add(fk);
}
}
return compositePk;
}
}
}
return null;
}
private MTORelationshipNode parseMto(List modifiers, Type returnType) {
MTORelationshipNode mto = new MTORelationshipNode();
mto.setType(SQL_MTO);
String referClassName = null;
List<MemberValuePair> joinColumnValues = null;
String fkColumnName = null;
// get foreign key column name
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation anno = (Annotation) modifier;
if (anno.getTypeName().toString().equals("JoinColumn")
&& anno instanceof NormalAnnotation) {
joinColumnValues = ((NormalAnnotation)anno).values();
}
}
}
for (MemberValuePair pair : joinColumnValues) {
if (pair.getName().toString().equals("name")) {
fkColumnName = pair.getValue().toString().replace("\"", "");
}
}
// refer class here
if (returnType.isSimpleType()) {
referClassName = ((SimpleType)returnType).getName().getFullyQualifiedName();
}
ColumnNode foreignKey = new ColumnNode();
foreignKey.setForeignKey(true);
foreignKey.setColumnName(fkColumnName);
TableNode referTable = new TableNode();
referTable.setClassName(referClassName);
mto.setReferTable(referTable);
mto.setForeignKey(foreignKey);
mto.setTempId(generateTempId());
return mto;
}
private OTMRelationshipNode parseOtm(List modifiers, Type returnType) {
OTMRelationshipNode otm = new OTMRelationshipNode();
otm.setType(SQL_OTM);
String referClassName = null;
// get type here
if (returnType.isParameterizedType()) {
ParameterizedType pReturnType = (ParameterizedType) returnType;
Object argument = pReturnType.typeArguments().get(0);
if (argument instanceof SimpleType) {
referClassName = ((SimpleType)argument).getName().getFullyQualifiedName();
}
}
TableNode referTable = new TableNode();
referTable.setClassName(referClassName);
otm.setReferTable(referTable);
otm.setTempId(generateTempId());
return otm;
}
private ColumnNode parseColumn(List modifiers, Type returnType) {
List<MemberValuePair> columnValues = null;
String columnName = null;
String javaType = null;
int length = 0;
boolean isPK = false;
boolean isUQ = false;
boolean isNN = false;
// get column name, length, pk, uq, nn here
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation anno = (Annotation) modifier;
if (anno.getTypeName().toString().equals("Id")) {
isPK = true;
} else if (anno.getTypeName().toString().equals("Column")
&& anno instanceof NormalAnnotation) {
columnValues = ((NormalAnnotation)anno).values();
}
}
}
for (MemberValuePair pair : columnValues) {
if (pair.getName().toString().equals("name")) {
columnName = pair.getValue().toString().replace("\"", "");
} else if (pair.getName().toString().equals("length")) {
length = Integer.parseInt(pair.getValue().toString());
} else if ((pair.getName().toString().equals("unique"))
&& pair.getValue().toString().equals("true")) {
isUQ = true;
} else if ((pair.getName().toString().equals("nullable"))
&& pair.getValue().toString().equals("false")) {
isNN = true;
}
}
// get type here
if (returnType.isPrimitiveType()) {
javaType = ((PrimitiveType)returnType).getPrimitiveTypeCode().toString();
} else if (returnType.isSimpleType()) {
javaType = ((SimpleType)returnType).getName().getFullyQualifiedName();
}
ColumnNode column = null;
if (isPK) {
column = new PrimaryKeyNode();
} else {
column = new ColumnNode();
}
column.setColumnName(columnName);
column.setJavaName(columnName);
column.setDataType(SqlTypeMapper.getHbmtoSql(javaType));
column.setLength(length);
column.setPrimaryKey(isPK);
column.setUnique(isUQ);
column.setNotNull(isNN);
column.setTempId(generateTempId());
return column;
}
/**
* Table, Column, MTO, OTM
* @return
*/
private String getElementType(List modifiers) {
for (Object modifier : modifiers) {
if (modifier instanceof Annotation) {
Annotation annotation = (Annotation) modifier;
if (annotation.getTypeName().toString().equals(EMBEDDED_ID)) {
return EMBEDDED_ID;
} else if (annotation.getTypeName().toString().equals("Entity")) {
return SQL_TABLE;
} else if (annotation.getTypeName().toString().equals("Column")) {
return SQL_COLUMN;
} else if (annotation.getTypeName().toString().equals("OneToMany")) {
return SQL_OTM;
} else if (annotation.getTypeName().toString().equals("ManyToOne")) {
return SQL_MTO;
}
}
}
return "";
}
}
| 11,955 | 0.574488 | 0.574153 | 310 | 37.564518 | 23.441912 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580645 | false | false | 0 |
916074b2b22db43680409f8e0776af20c43e776a | 7,129,645,756,141 | f416ba52cd849666ffbbef3655ed885d2848e9a3 | /app/src/main/java/com/example/joanna/housepharmacy/DatabaseAdapters/DatabaseFormAdapter.java | 26b80f895866270568c4d877d86be570cbe1ea98 | [] | no_license | jpienko/HousePharmacyProject | https://github.com/jpienko/HousePharmacyProject | 7b5ecbc832cec84201c338cad8bca296bafb02d0 | e1dc8f9d5b0349810bc5f6cbd8b200ffce6a3997 | refs/heads/master | 2021-04-27T20:28:17.932000 | 2018-06-11T07:52:25 | 2018-06-11T07:52:25 | 122,378,550 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.joanna.housepharmacy.DatabaseAdapters;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.example.joanna.housepharmacy.DatabaseImplementation.DatabaseConstants;
import com.example.joanna.housepharmacy.DatabaseImplementation.DatabaseHelper;
import java.util.ArrayList;
/**
* Created by Joanna on 2018-03-05.
*/
public class DatabaseFormAdapter {
ArrayList<String> forms = new ArrayList<String>();
Context context;
SQLiteDatabase db;
DatabaseHelper dbHelper;
public DatabaseFormAdapter(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void openDB() throws SQLException {
db = dbHelper.getWritableDatabase();
}
public void closeDB() throws SQLException {
dbHelper.close();
}
public Cursor getAllForms() {
String[] columns = {DatabaseConstants.ID_FORM, DatabaseConstants.FORM_NAME};
return db.query(DatabaseConstants.FORMSTABLE, columns, null, null, null, null, null);
}
public String getFormName(long id) {
String formName = "";
Cursor cursor;
cursor = db.query(DatabaseConstants.FORMSTABLE,
new String[]{DatabaseConstants.FORM_NAME},
DatabaseConstants.ID_FORM + "=?",
new String[]{String.valueOf(id)},
null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
formName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.FORM_NAME));
}
return formName;
}
public int getFromId(String name){
int formName = 1;
Cursor cursor;
cursor = db.query(DatabaseConstants.FORMSTABLE,
new String[]{DatabaseConstants.ID_FORM},
DatabaseConstants.FORM_NAME + "=?",
new String[]{name},
null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
formName = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.ID_FORM));
}
return formName;
}
}
| UTF-8 | Java | 2,232 | java | DatabaseFormAdapter.java | Java | [
{
"context": "r;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Joanna on 2018-03-05.\n */\n\npublic class DatabaseFormAdap",
"end": 425,
"score": 0.5857914090156555,
"start": 419,
"tag": "NAME",
"value": "Joanna"
}
] | null | [] | package com.example.joanna.housepharmacy.DatabaseAdapters;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.example.joanna.housepharmacy.DatabaseImplementation.DatabaseConstants;
import com.example.joanna.housepharmacy.DatabaseImplementation.DatabaseHelper;
import java.util.ArrayList;
/**
* Created by Joanna on 2018-03-05.
*/
public class DatabaseFormAdapter {
ArrayList<String> forms = new ArrayList<String>();
Context context;
SQLiteDatabase db;
DatabaseHelper dbHelper;
public DatabaseFormAdapter(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void openDB() throws SQLException {
db = dbHelper.getWritableDatabase();
}
public void closeDB() throws SQLException {
dbHelper.close();
}
public Cursor getAllForms() {
String[] columns = {DatabaseConstants.ID_FORM, DatabaseConstants.FORM_NAME};
return db.query(DatabaseConstants.FORMSTABLE, columns, null, null, null, null, null);
}
public String getFormName(long id) {
String formName = "";
Cursor cursor;
cursor = db.query(DatabaseConstants.FORMSTABLE,
new String[]{DatabaseConstants.FORM_NAME},
DatabaseConstants.ID_FORM + "=?",
new String[]{String.valueOf(id)},
null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
formName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.FORM_NAME));
}
return formName;
}
public int getFromId(String name){
int formName = 1;
Cursor cursor;
cursor = db.query(DatabaseConstants.FORMSTABLE,
new String[]{DatabaseConstants.ID_FORM},
DatabaseConstants.FORM_NAME + "=?",
new String[]{name},
null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
formName = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.ID_FORM));
}
return formName;
}
}
| 2,232 | 0.642025 | 0.637097 | 76 | 28.328947 | 25.293741 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.644737 | false | false | 0 |
592dd4e64afa561dc4337ad5cdbcab169d6fd8bf | 1,314,260,043,394 | 43ba199977f5d4d0a7f4662b8a7c3efecedd939e | /media-company-service/src/main/java/com/imfc/media/company/MediaCompanyServiceApplication.java | 9f8e5cb2592650462aa0aaea14a7ae36b876d8bb | [] | no_license | imfc/media | https://github.com/imfc/media | aa7cfd6191e762c4c4255f5c3f1f11916fb5c51d | ae5a003003cb83b06dbb99494ce25095db4a724f | refs/heads/master | 2022-07-17T20:31:32.826000 | 2019-10-15T03:48:11 | 2019-10-15T03:48:11 | 195,631,310 | 2 | 0 | null | false | 2022-06-29T19:41:52 | 2019-07-07T09:09:51 | 2019-11-05T03:28:09 | 2022-06-29T19:41:52 | 8,948 | 0 | 0 | 6 | JavaScript | false | false | package com.imfc.media.company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MediaCompanyServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MediaCompanyServiceApplication.class, args);
}
}
| UTF-8 | Java | 353 | java | MediaCompanyServiceApplication.java | Java | [] | null | [] | package com.imfc.media.company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MediaCompanyServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MediaCompanyServiceApplication.class, args);
}
}
| 353 | 0.804533 | 0.804533 | 13 | 26.153847 | 26.515152 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 0 |
8f6007bea77826ecf9f0a9c329a0245f8d6d0e35 | 22,883,585,798,489 | e5e17dd37ad71fe77297a201ec322a923e7df033 | /src/test/model/BoardTest.java | eba269a4732d34c73ea68f5dc87f0a58839fb695 | [] | no_license | ryannli/Chess | https://github.com/ryannli/Chess | 12808aec39804c9cf8742f3bef11b460b495b462 | 4e2c401cf76a0e028eaec23a8cbd16eee19bd03a | refs/heads/master | 2020-03-12T19:08:07.600000 | 2018-04-24T01:48:32 | 2018-04-24T01:48:32 | 130,777,943 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class BoardTest {
private Board board;
@org.junit.Before
public void setUp() throws Exception {
board = new Board(8, 8);
}
@Test
public void TestSetPiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
assertEquals(board.setPiece(pawn), false);
}
@Test
public void TestGetPiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
assertEquals(board.getPiece(pawnPosition), null);
pawnPosition = new BasePiece.Position(4, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
board.setPiece(pawn);
assertEquals(board.getPiece(pawnPosition), pawn);
}
@Test
public void TestRemovePiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
assertEquals(board.removePiece(pawnPosition), false);
}
@Test
public void TestGetPlayerAllPieces() {
BasePiece.Position pawnPosition = new BasePiece.Position(6, 4);
BasePiece.Position kingPosition = new BasePiece.Position(4, 4);
BasePiece.Position queenPosition = new BasePiece.Position(2, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
BasePiece queen = new Queen(queenPosition, false);
board.setPiece(pawn);
board.setPiece(king);
List<BasePiece> pieces = new ArrayList<BasePiece>();
pieces.add(king);
pieces.add(pawn);
assertEquals(board.getPlayerAllPieces(true), pieces);
}
@Test
public void TestTryMoveIfInCheck() {
BasePiece.Position queenPosition = new BasePiece.Position(4, 6);
BasePiece.Position pawnPosition = new BasePiece.Position(4, 5);
BasePiece.Position kingPosition = new BasePiece.Position(4, 4);
BasePiece.Position bishopPosition = new BasePiece.Position(5, 5);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
BasePiece queen = new Queen(queenPosition, false);
BasePiece bishop = new Bishop(bishopPosition, false);
board.setPiece(pawn);
board.setPiece(king);
board.setPiece(queen);
board.setPiece(bishop);
assertEquals(board.tryMoveIfInCheck(pawn, new BasePiece.Position(5, 5)), true);
assertEquals(board.getPiece(new BasePiece.Position(4, 6)), queen);
assertEquals(board.getPiece(new BasePiece.Position(4, 5)), pawn);
assertEquals(board.getPiece(new BasePiece.Position(4, 4)), king);
}
@Test
public void TestMovePiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(4, 4);
BasePiece.Position kingPosition = new BasePiece.Position(3, 4);
BasePiece.Position targetPosition = new BasePiece.Position(5, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
board.setPiece(pawn);
board.setPiece(king);
assertEquals(board.movePiece(pawn, targetPosition), true);
targetPosition = new BasePiece.Position(7, 4);
assertEquals(board.movePiece(pawn, targetPosition), false);
}
@Test
public void TestGetKingNull() {
assertEquals(board.getKing(true), null);
}
@Test
public void TestInCheckMateTrue() {
BasePiece.Position queenPosition = new BasePiece.Position(2, 2);
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 0);
BasePiece.Position rookPosition2 = new BasePiece.Position(0, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece queen = new Queen(queenPosition, true);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece rook2 = new Rook(rookPosition2, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(queen);
board.setPiece(rook1);
board.setPiece(rook2);
board.setPiece(king);
assertEquals(board.inCheckmate(false), true);
}
@Test
public void TestInCheckMateFalse() {
BasePiece.Position queenPosition = new BasePiece.Position(2, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 1);
BasePiece queen = new Queen(queenPosition, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(queen);
board.setPiece(king);
assertEquals(board.inCheckmate(false), false);
}
@Test
public void TestInStaleMateTrue() {
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 1);
BasePiece.Position rookPosition2 = new BasePiece.Position(1, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece rook2 = new Rook(rookPosition2, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(rook1);
board.setPiece(rook2);
board.setPiece(king);
assertEquals(board.inStaleMate(false), true);
}
@Test
public void TestInStaleMateFalse() {
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 0);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(rook1);
board.setPiece(king);
assertEquals(board.inStaleMate(false), false);
board.removePiece(rookPosition1);
assertEquals(board.inStaleMate(false), false);
}
}
| UTF-8 | Java | 5,835 | java | BoardTest.java | Java | [] | null | [] | package model;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class BoardTest {
private Board board;
@org.junit.Before
public void setUp() throws Exception {
board = new Board(8, 8);
}
@Test
public void TestSetPiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
assertEquals(board.setPiece(pawn), false);
}
@Test
public void TestGetPiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
assertEquals(board.getPiece(pawnPosition), null);
pawnPosition = new BasePiece.Position(4, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
board.setPiece(pawn);
assertEquals(board.getPiece(pawnPosition), pawn);
}
@Test
public void TestRemovePiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(10, 4);
assertEquals(board.removePiece(pawnPosition), false);
}
@Test
public void TestGetPlayerAllPieces() {
BasePiece.Position pawnPosition = new BasePiece.Position(6, 4);
BasePiece.Position kingPosition = new BasePiece.Position(4, 4);
BasePiece.Position queenPosition = new BasePiece.Position(2, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
BasePiece queen = new Queen(queenPosition, false);
board.setPiece(pawn);
board.setPiece(king);
List<BasePiece> pieces = new ArrayList<BasePiece>();
pieces.add(king);
pieces.add(pawn);
assertEquals(board.getPlayerAllPieces(true), pieces);
}
@Test
public void TestTryMoveIfInCheck() {
BasePiece.Position queenPosition = new BasePiece.Position(4, 6);
BasePiece.Position pawnPosition = new BasePiece.Position(4, 5);
BasePiece.Position kingPosition = new BasePiece.Position(4, 4);
BasePiece.Position bishopPosition = new BasePiece.Position(5, 5);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
BasePiece queen = new Queen(queenPosition, false);
BasePiece bishop = new Bishop(bishopPosition, false);
board.setPiece(pawn);
board.setPiece(king);
board.setPiece(queen);
board.setPiece(bishop);
assertEquals(board.tryMoveIfInCheck(pawn, new BasePiece.Position(5, 5)), true);
assertEquals(board.getPiece(new BasePiece.Position(4, 6)), queen);
assertEquals(board.getPiece(new BasePiece.Position(4, 5)), pawn);
assertEquals(board.getPiece(new BasePiece.Position(4, 4)), king);
}
@Test
public void TestMovePiece() {
BasePiece.Position pawnPosition = new BasePiece.Position(4, 4);
BasePiece.Position kingPosition = new BasePiece.Position(3, 4);
BasePiece.Position targetPosition = new BasePiece.Position(5, 4);
BasePiece pawn = new Pawn(pawnPosition, true);
BasePiece king = new King(kingPosition, true);
board.setPiece(pawn);
board.setPiece(king);
assertEquals(board.movePiece(pawn, targetPosition), true);
targetPosition = new BasePiece.Position(7, 4);
assertEquals(board.movePiece(pawn, targetPosition), false);
}
@Test
public void TestGetKingNull() {
assertEquals(board.getKing(true), null);
}
@Test
public void TestInCheckMateTrue() {
BasePiece.Position queenPosition = new BasePiece.Position(2, 2);
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 0);
BasePiece.Position rookPosition2 = new BasePiece.Position(0, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece queen = new Queen(queenPosition, true);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece rook2 = new Rook(rookPosition2, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(queen);
board.setPiece(rook1);
board.setPiece(rook2);
board.setPiece(king);
assertEquals(board.inCheckmate(false), true);
}
@Test
public void TestInCheckMateFalse() {
BasePiece.Position queenPosition = new BasePiece.Position(2, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 1);
BasePiece queen = new Queen(queenPosition, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(queen);
board.setPiece(king);
assertEquals(board.inCheckmate(false), false);
}
@Test
public void TestInStaleMateTrue() {
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 1);
BasePiece.Position rookPosition2 = new BasePiece.Position(1, 2);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece rook2 = new Rook(rookPosition2, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(rook1);
board.setPiece(rook2);
board.setPiece(king);
assertEquals(board.inStaleMate(false), true);
}
@Test
public void TestInStaleMateFalse() {
BasePiece.Position rookPosition1 = new BasePiece.Position(2, 0);
BasePiece.Position kingPosition = new BasePiece.Position(0, 0);
BasePiece rook1 = new Rook(rookPosition1, true);
BasePiece king = new King(kingPosition, false);
board.setPiece(rook1);
board.setPiece(king);
assertEquals(board.inStaleMate(false), false);
board.removePiece(rookPosition1);
assertEquals(board.inStaleMate(false), false);
}
}
| 5,835 | 0.662896 | 0.648158 | 164 | 34.579269 | 26.486073 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.030488 | false | false | 0 |
336561ef296fe438e515ee36f39707dac5b33971 | 13,881,334,306,403 | 537b4242ebbd99150b490e298f4dff69eee276d0 | /humanize-emoji/src/main/java/humanize/emoji/Emoji.java | a1baa418b46f0286f2393149c34b8d70feb51060 | [
"Apache-2.0"
] | permissive | FlakyTestDetection/humanize | https://github.com/FlakyTestDetection/humanize | 0e766ce5374de713eacc71f18dccfac0d11b5f76 | 0fff62585d40080d12bcd2e5e6df2991b2658384 | refs/heads/master | 2021-01-20T05:57:11.568000 | 2017-09-11T12:36:17 | 2017-09-11T12:36:17 | 89,827,248 | 0 | 0 | null | true | 2017-04-30T03:34:01 | 2017-04-30T03:34:01 | 2017-04-28T09:00:21 | 2016-10-26T18:38:55 | 2,431 | 0 | 0 | 0 | null | null | null | package humanize.emoji;
import humanize.emoji.EmojiChar.Vendor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.CharStreams;
import com.google.common.io.LineProcessor;
/**
* Unified Emoji for Java.
*
* @see Unicode Emoji (working draft)
* http://www.unicode.org/reports/tr51/tr51-1d.html
*/
public final class Emoji
{
private static final Charset UTF8 = Charset.forName("UTF8");
private static final String DB_EMOJI_DATA = "/db/emoji-data.txt";
private static final String DB_EMOJI_SOURCES = "/db/emoji-sources.txt";
private static final List<EmojiChar> EMOJI_CHARS = new ArrayList<EmojiChar>();
private static final Map<String, EmojiChar> HEX_INDEX = new HashMap<String, EmojiChar>();
private static final Map<String, EmojiChar> RAW_INDEX = new HashMap<String, EmojiChar>();
private static final Map<VendorKey, EmojiChar> VENDORS_INDEX = new HashMap<VendorKey, EmojiChar>();
private static final Multimap<String, EmojiChar> ANNOTATIONS_INDEX = ArrayListMultimap.create();
/**
* Transforms a list of Unicode code points, as hex strings, into a proper
* encoded string.
*
* @param points
* The list of Unicode code point as a hex strings
* @return the concatenation of the proper encoded string for the given
* points
* @see Emoji#codePointToString(String)
*/
public static String codePointsToString(String... points)
{
StringBuilder ret = new StringBuilder();
for (String hexPoint : points)
{
ret.append(codePointToString(hexPoint));
}
return ret.toString();
}
/**
* Transforms an Unicode code point, given as a hex string, into a proper
* encoded string. Supplementary code points are encoded in UTF-16 as
* required by Java.
*
* @param point
* The Unicode code point as a hex string
* @return the proper encoded string reification of a given point
*/
public static String codePointToString(String point)
{
String ret;
if (Strings.isNullOrEmpty(point))
{
return point;
}
int unicodeScalar = Integer.parseInt(point, 16);
if (Character.isSupplementaryCodePoint(unicodeScalar))
{
ret = String.valueOf(Character.toChars(unicodeScalar));
} else
{
ret = String.valueOf((char) unicodeScalar);
}
return ret;
}
/**
* Finds emoji characters for the given annotations.
*
* @param annotations
* The list of annotations separated by spaces
* @return or an empty list if there is no match
*/
public static List<EmojiChar> findByAnnotations(String annotations)
{
return getInstance()._findByAnnotations(annotations);
}
/**
* Finds an emoji character by Unicode code point.
*
* @param code
* the Unicode code point
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByCodePoint(String code)
{
return getInstance()._findByCodePoint(code);
}
/**
* Finds an emoji character by hexadecimal code.
*
* @param hex
* the hexadecimal code
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByHexCode(String hex)
{
return getInstance()._findByHexCode(hex.toUpperCase());
}
/**
* Finds an emoji character by vendor code point.
*
* @param vendor
* the vendor
* @param point
* the raw character for the code point in the vendor space
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point)
{
Emoji emoji = Emoji.getInstance();
return emoji._findByVendorCodePoint(vendor, point);
}
/**
* Finds a single emoji character for the given annotations.
*
* @param annotations
* The list of annotations separated by spaces
* @return a matching emoji character or null if none found
*/
public static EmojiChar singleByAnnotations(String annotations)
{
return getInstance()._singleByAnnotations(annotations);
}
private static Emoji getInstance()
{
return LazyHolder.INSTANCE;
}
private Emoji()
{
try
{
loadData();
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
private List<EmojiChar> _findByAnnotations(String annotations)
{
Collection<EmojiChar> found = new HashSet<EmojiChar>();
Collection<String> parts = Arrays.asList(Strings.nullToEmpty(annotations).split("\\s+"));
for (String annotation : parts)
{
collectAnnotations(found, parts, annotation);
}
return found.isEmpty() ?
Collections.<EmojiChar> emptyList() : asSortedList(found);
}
private EmojiChar _findByCodePoint(String code)
{
return RAW_INDEX.get(code);
}
private EmojiChar _findByHexCode(String hex)
{
return HEX_INDEX.get(hex);
}
private EmojiChar _findByVendorCodePoint(Vendor vendor, String code)
{
return VENDORS_INDEX.get(new VendorKey(vendor, code));
}
private EmojiChar _singleByAnnotations(String annotations)
{
List<EmojiChar> found = _findByAnnotations(annotations);
return found.isEmpty() ? null : found.iterator().next();
}
private <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c)
{
List<T> list = new ArrayList<T>(c);
Collections.sort(list);
return list;
}
private void collectAnnotations(Collection<EmojiChar> found,
Collection<String> parts,
String annotation)
{
if (!ANNOTATIONS_INDEX.containsKey(annotation))
return;
Collection<EmojiChar> echars = ANNOTATIONS_INDEX.get(annotation);
for (EmojiChar echar : echars)
{
if (echar.hasAnnotations(parts))
{
found.add(echar);
}
}
}
private StreamLineProcessor emojiDataProcessor()
{
return new StreamLineProcessor()
{
@Override
protected void consumeLine(String line)
{
String[] row = line.split(";");
String code = extractCode(trim(row[0]));
String defaultStyle = trim(row[1]);
int ordering = Integer.parseInt(trim(row[2]));
List<String> annotations = extractList(trim(row[3]));
String[] rest = parseRemaining(trim(row[4]));
String sources = rest[0];
String version = rest[1];
String raw = rest[2];
String name = rest[3];
EmojiChar ec = new EmojiChar(code, defaultStyle,
ordering, annotations, sources,
version, raw, name);
EMOJI_CHARS.add(ec);
index(ec);
}
};
}
private StreamLineProcessor emojiSourcesProcessor()
{
return new StreamLineProcessor()
{
@Override
protected void consumeLine(String line)
{
String[] row = line.split(";");
String unified = trim(row[0]);
String unicode = codePointsToString(unified.split(" "));
EmojiChar echar = _findByCodePoint(unicode);
if (echar != null)
{
map(echar, Vendor.DOCOMO, row, 1);
map(echar, Vendor.KDDI, row, 2);
map(echar, Vendor.SOFT_BANK, row, 3);
}
}
private void map(EmojiChar echar, Vendor vendor, String[] row, int index)
{
if (row.length <= index)
{
return;
}
String code = trim(row[index]);
if (!Strings.isNullOrEmpty(code))
{
String raw = codePointToString(code);
echar.map(vendor, code, raw);
VENDORS_INDEX.put(new VendorKey(vendor, raw), echar);
}
}
};
}
private String extractCode(String str)
{
return str.replaceAll("U\\+", "");
}
private List<String> extractList(String list)
{
String[] tmp = list.split(",");
List<String> clean = new ArrayList<String>();
for (String s : tmp)
{
clean.add(s.trim());
}
return clean;
}
private void index(EmojiChar echar)
{
// Index by code points (raw characters)
RAW_INDEX.put(echar.getRaw(), echar);
// Index by hex code
HEX_INDEX.put(echar.getCode(), echar);
// Index by annotations
for (String annotation : echar.getAnnotations())
{
ANNOTATIONS_INDEX.put(annotation, echar);
}
}
private void load(String path, LineProcessor<Void> processor) throws IOException
{
InputStream in = Emoji.class.getResourceAsStream(path);
Preconditions.checkNotNull(in, "%s not found in the classpath!", path);
InputStreamReader isr = new InputStreamReader(in, UTF8);
BufferedReader br = new BufferedReader(isr);
CharStreams.readLines(br, processor);
}
private void loadData() throws IOException
{
load(DB_EMOJI_DATA, emojiDataProcessor());
load(DB_EMOJI_SOURCES, emojiSourcesProcessor());
}
private String[] parseRemaining(String in)
{
String[] res = new String[4];
String[] fp = in.split("#", 2);
// sources
res[0] = trim(fp[0]);
// v.g. 'V1.1 (☻) black smiling face'
Pattern expr = Pattern.compile("(V\\d+\\.\\d+)\\s\\((.+)\\)\\s(.+)");
Matcher matcher = expr.matcher(trim(fp[1]));
if (matcher.matches())
{
// version
res[1] = matcher.group(1);
// char
res[2] = matcher.group(2);
// name
res[3] = matcher.group(3);
} else
{
throw new RuntimeException("Error loading: " + in);
}
return res;
}
private String trim(String str)
{
if (Strings.isNullOrEmpty(str))
return str;
return str.replaceAll("\\s+", " ").trim();
}
private static class LazyHolder
{
private static final Emoji INSTANCE = new Emoji();
}
private abstract class StreamLineProcessor implements LineProcessor<Void>
{
@Override
public Void getResult()
{
return null;
}
public boolean processLine(String line) throws IOException
{
if (Strings.isNullOrEmpty(line) || line.indexOf('#') == 0)
{
return true;
}
consumeLine(line);
return true;
}
abstract protected void consumeLine(String line);;
}
private static class VendorKey
{
private final Vendor vendor;
private final String code;
public VendorKey(Vendor vendor, String code)
{
this.vendor = vendor;
this.code = code;
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VendorKey other = (VendorKey) obj;
return Objects.equal(vendor, other.vendor)
&& Objects.equal(code, other.code);
}
@Override
public int hashCode()
{
return Objects.hashCode(vendor, code);
}
}
}
| UTF-8 | Java | 12,764 | java | Emoji.java | Java | [] | null | [] | package humanize.emoji;
import humanize.emoji.EmojiChar.Vendor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.io.CharStreams;
import com.google.common.io.LineProcessor;
/**
* Unified Emoji for Java.
*
* @see Unicode Emoji (working draft)
* http://www.unicode.org/reports/tr51/tr51-1d.html
*/
public final class Emoji
{
private static final Charset UTF8 = Charset.forName("UTF8");
private static final String DB_EMOJI_DATA = "/db/emoji-data.txt";
private static final String DB_EMOJI_SOURCES = "/db/emoji-sources.txt";
private static final List<EmojiChar> EMOJI_CHARS = new ArrayList<EmojiChar>();
private static final Map<String, EmojiChar> HEX_INDEX = new HashMap<String, EmojiChar>();
private static final Map<String, EmojiChar> RAW_INDEX = new HashMap<String, EmojiChar>();
private static final Map<VendorKey, EmojiChar> VENDORS_INDEX = new HashMap<VendorKey, EmojiChar>();
private static final Multimap<String, EmojiChar> ANNOTATIONS_INDEX = ArrayListMultimap.create();
/**
* Transforms a list of Unicode code points, as hex strings, into a proper
* encoded string.
*
* @param points
* The list of Unicode code point as a hex strings
* @return the concatenation of the proper encoded string for the given
* points
* @see Emoji#codePointToString(String)
*/
public static String codePointsToString(String... points)
{
StringBuilder ret = new StringBuilder();
for (String hexPoint : points)
{
ret.append(codePointToString(hexPoint));
}
return ret.toString();
}
/**
* Transforms an Unicode code point, given as a hex string, into a proper
* encoded string. Supplementary code points are encoded in UTF-16 as
* required by Java.
*
* @param point
* The Unicode code point as a hex string
* @return the proper encoded string reification of a given point
*/
public static String codePointToString(String point)
{
String ret;
if (Strings.isNullOrEmpty(point))
{
return point;
}
int unicodeScalar = Integer.parseInt(point, 16);
if (Character.isSupplementaryCodePoint(unicodeScalar))
{
ret = String.valueOf(Character.toChars(unicodeScalar));
} else
{
ret = String.valueOf((char) unicodeScalar);
}
return ret;
}
/**
* Finds emoji characters for the given annotations.
*
* @param annotations
* The list of annotations separated by spaces
* @return or an empty list if there is no match
*/
public static List<EmojiChar> findByAnnotations(String annotations)
{
return getInstance()._findByAnnotations(annotations);
}
/**
* Finds an emoji character by Unicode code point.
*
* @param code
* the Unicode code point
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByCodePoint(String code)
{
return getInstance()._findByCodePoint(code);
}
/**
* Finds an emoji character by hexadecimal code.
*
* @param hex
* the hexadecimal code
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByHexCode(String hex)
{
return getInstance()._findByHexCode(hex.toUpperCase());
}
/**
* Finds an emoji character by vendor code point.
*
* @param vendor
* the vendor
* @param point
* the raw character for the code point in the vendor space
* @return the corresponding emoji character or null if not found
*/
public static EmojiChar findByVendorCodePoint(Vendor vendor, String point)
{
Emoji emoji = Emoji.getInstance();
return emoji._findByVendorCodePoint(vendor, point);
}
/**
* Finds a single emoji character for the given annotations.
*
* @param annotations
* The list of annotations separated by spaces
* @return a matching emoji character or null if none found
*/
public static EmojiChar singleByAnnotations(String annotations)
{
return getInstance()._singleByAnnotations(annotations);
}
private static Emoji getInstance()
{
return LazyHolder.INSTANCE;
}
private Emoji()
{
try
{
loadData();
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
private List<EmojiChar> _findByAnnotations(String annotations)
{
Collection<EmojiChar> found = new HashSet<EmojiChar>();
Collection<String> parts = Arrays.asList(Strings.nullToEmpty(annotations).split("\\s+"));
for (String annotation : parts)
{
collectAnnotations(found, parts, annotation);
}
return found.isEmpty() ?
Collections.<EmojiChar> emptyList() : asSortedList(found);
}
private EmojiChar _findByCodePoint(String code)
{
return RAW_INDEX.get(code);
}
private EmojiChar _findByHexCode(String hex)
{
return HEX_INDEX.get(hex);
}
private EmojiChar _findByVendorCodePoint(Vendor vendor, String code)
{
return VENDORS_INDEX.get(new VendorKey(vendor, code));
}
private EmojiChar _singleByAnnotations(String annotations)
{
List<EmojiChar> found = _findByAnnotations(annotations);
return found.isEmpty() ? null : found.iterator().next();
}
private <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c)
{
List<T> list = new ArrayList<T>(c);
Collections.sort(list);
return list;
}
private void collectAnnotations(Collection<EmojiChar> found,
Collection<String> parts,
String annotation)
{
if (!ANNOTATIONS_INDEX.containsKey(annotation))
return;
Collection<EmojiChar> echars = ANNOTATIONS_INDEX.get(annotation);
for (EmojiChar echar : echars)
{
if (echar.hasAnnotations(parts))
{
found.add(echar);
}
}
}
private StreamLineProcessor emojiDataProcessor()
{
return new StreamLineProcessor()
{
@Override
protected void consumeLine(String line)
{
String[] row = line.split(";");
String code = extractCode(trim(row[0]));
String defaultStyle = trim(row[1]);
int ordering = Integer.parseInt(trim(row[2]));
List<String> annotations = extractList(trim(row[3]));
String[] rest = parseRemaining(trim(row[4]));
String sources = rest[0];
String version = rest[1];
String raw = rest[2];
String name = rest[3];
EmojiChar ec = new EmojiChar(code, defaultStyle,
ordering, annotations, sources,
version, raw, name);
EMOJI_CHARS.add(ec);
index(ec);
}
};
}
private StreamLineProcessor emojiSourcesProcessor()
{
return new StreamLineProcessor()
{
@Override
protected void consumeLine(String line)
{
String[] row = line.split(";");
String unified = trim(row[0]);
String unicode = codePointsToString(unified.split(" "));
EmojiChar echar = _findByCodePoint(unicode);
if (echar != null)
{
map(echar, Vendor.DOCOMO, row, 1);
map(echar, Vendor.KDDI, row, 2);
map(echar, Vendor.SOFT_BANK, row, 3);
}
}
private void map(EmojiChar echar, Vendor vendor, String[] row, int index)
{
if (row.length <= index)
{
return;
}
String code = trim(row[index]);
if (!Strings.isNullOrEmpty(code))
{
String raw = codePointToString(code);
echar.map(vendor, code, raw);
VENDORS_INDEX.put(new VendorKey(vendor, raw), echar);
}
}
};
}
private String extractCode(String str)
{
return str.replaceAll("U\\+", "");
}
private List<String> extractList(String list)
{
String[] tmp = list.split(",");
List<String> clean = new ArrayList<String>();
for (String s : tmp)
{
clean.add(s.trim());
}
return clean;
}
private void index(EmojiChar echar)
{
// Index by code points (raw characters)
RAW_INDEX.put(echar.getRaw(), echar);
// Index by hex code
HEX_INDEX.put(echar.getCode(), echar);
// Index by annotations
for (String annotation : echar.getAnnotations())
{
ANNOTATIONS_INDEX.put(annotation, echar);
}
}
private void load(String path, LineProcessor<Void> processor) throws IOException
{
InputStream in = Emoji.class.getResourceAsStream(path);
Preconditions.checkNotNull(in, "%s not found in the classpath!", path);
InputStreamReader isr = new InputStreamReader(in, UTF8);
BufferedReader br = new BufferedReader(isr);
CharStreams.readLines(br, processor);
}
private void loadData() throws IOException
{
load(DB_EMOJI_DATA, emojiDataProcessor());
load(DB_EMOJI_SOURCES, emojiSourcesProcessor());
}
private String[] parseRemaining(String in)
{
String[] res = new String[4];
String[] fp = in.split("#", 2);
// sources
res[0] = trim(fp[0]);
// v.g. 'V1.1 (☻) black smiling face'
Pattern expr = Pattern.compile("(V\\d+\\.\\d+)\\s\\((.+)\\)\\s(.+)");
Matcher matcher = expr.matcher(trim(fp[1]));
if (matcher.matches())
{
// version
res[1] = matcher.group(1);
// char
res[2] = matcher.group(2);
// name
res[3] = matcher.group(3);
} else
{
throw new RuntimeException("Error loading: " + in);
}
return res;
}
private String trim(String str)
{
if (Strings.isNullOrEmpty(str))
return str;
return str.replaceAll("\\s+", " ").trim();
}
private static class LazyHolder
{
private static final Emoji INSTANCE = new Emoji();
}
private abstract class StreamLineProcessor implements LineProcessor<Void>
{
@Override
public Void getResult()
{
return null;
}
public boolean processLine(String line) throws IOException
{
if (Strings.isNullOrEmpty(line) || line.indexOf('#') == 0)
{
return true;
}
consumeLine(line);
return true;
}
abstract protected void consumeLine(String line);;
}
private static class VendorKey
{
private final Vendor vendor;
private final String code;
public VendorKey(Vendor vendor, String code)
{
this.vendor = vendor;
this.code = code;
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VendorKey other = (VendorKey) obj;
return Objects.equal(vendor, other.vendor)
&& Objects.equal(code, other.code);
}
@Override
public int hashCode()
{
return Objects.hashCode(vendor, code);
}
}
}
| 12,764 | 0.573656 | 0.5706 | 453 | 27.172186 | 24.723932 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.441501 | false | false | 0 |
cf6bc96c32e5ccbc628c8b0d71f66055179ea8b1 | 32,306,744,004,681 | 11b9cc046bff0c0d59161b30f00fa17a86e29c23 | /pedometer/src/main/java/com/wonders/xlab/pedometer/base/BaseContract.java | 7ab541dca7247581a6ee0fcc06fd1a5337455da0 | [] | no_license | Tijn1314/Pedometer | https://github.com/Tijn1314/Pedometer | c6212d8a72e55f00a6ce899510195b068f34df10 | 8561a741501009ea6b908686f43172edf3bcf79c | refs/heads/master | 2020-03-04T15:51:32.641000 | 2016-10-17T04:57:41 | 2016-10-17T04:57:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wonders.xlab.pedometer.base;
import android.support.annotation.NonNull;
/**
* Created by hua on 16/8/19.
*/
public interface BaseContract {
interface View {
void showToastMessage(String message);
}
interface Presenter {
void onDestroy();
}
interface Model {
interface Callback<T> {
void onSuccess(T t);
void onFail(@NonNull DefaultException e);
}
void onDestroy();
}
}
| UTF-8 | Java | 477 | java | BaseContract.java | Java | [
{
"context": "oid.support.annotation.NonNull;\n\n/**\n * Created by hua on 16/8/19.\n */\npublic interface BaseContract {\n ",
"end": 107,
"score": 0.9939393997192383,
"start": 104,
"tag": "USERNAME",
"value": "hua"
}
] | null | [] | package com.wonders.xlab.pedometer.base;
import android.support.annotation.NonNull;
/**
* Created by hua on 16/8/19.
*/
public interface BaseContract {
interface View {
void showToastMessage(String message);
}
interface Presenter {
void onDestroy();
}
interface Model {
interface Callback<T> {
void onSuccess(T t);
void onFail(@NonNull DefaultException e);
}
void onDestroy();
}
}
| 477 | 0.603774 | 0.593291 | 26 | 17.346153 | 16.576031 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 0 |
db4806415baba3d44c0e0372971b28d6b3bb1f40 | 10,703,058,532,169 | 3aebcd58523bf0035ee568d1565a268a8140110d | /app/src/main/java/com/example/karol/kalkulator_ip/Calculations/Calc_Cidr.java | 7c08f739639d8fba2029dad2eace5f0b285d2481 | [] | no_license | KarolSieradzki/IP_Calc | https://github.com/KarolSieradzki/IP_Calc | 212b96c5c4d98cfc22f2a27cb27f0da4e44fc0c1 | 36bc0b3dc963d1d776d46c43a14abb2b54e5afd1 | refs/heads/master | 2023-01-21T04:49:17.174000 | 2023-01-13T11:27:25 | 2023-01-13T11:27:25 | 146,426,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.karol.kalkulator_ip.Calculations;
import com.example.karol.kalkulator_ip.EditTexts.Addresses.Octet;
public class Calc_Cidr {
public String by_mask(Octet[] mask) {
int cidr = 0;
for (int i = 0; i < 4; i++) {
if (Integer.parseInt(mask[i].getDec()) == 255)
cidr += 8;
else {
for (int j = 0; j < mask[i].getBin().length(); j++) {
if (mask[i].getBin().charAt(j) == '1')
cidr++;
}
break;
}
}
return Integer.toString(cidr);
}
}
| UTF-8 | Java | 629 | java | Calc_Cidr.java | Java | [] | null | [] | package com.example.karol.kalkulator_ip.Calculations;
import com.example.karol.kalkulator_ip.EditTexts.Addresses.Octet;
public class Calc_Cidr {
public String by_mask(Octet[] mask) {
int cidr = 0;
for (int i = 0; i < 4; i++) {
if (Integer.parseInt(mask[i].getDec()) == 255)
cidr += 8;
else {
for (int j = 0; j < mask[i].getBin().length(); j++) {
if (mask[i].getBin().charAt(j) == '1')
cidr++;
}
break;
}
}
return Integer.toString(cidr);
}
}
| 629 | 0.459459 | 0.445151 | 23 | 26.347826 | 21.945801 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 0 |
7cdb7f0e17bdc9a075c87edada45227f1360b395 | 10,703,058,530,377 | 62fddfdf9c6831e49cd123ba89a702af420d4d45 | /timetable-demo-1/src/com/timetable/Department.java | 856383cc5f577c14f7ce24936e9c96910e2ecd82 | [] | no_license | lieutenant07/timetable | https://github.com/lieutenant07/timetable | 10e7fed0db511e4d457ab3467191d3296886c6e6 | b7e311bda471566c0b7c49786b7cffca40ba1bc2 | refs/heads/master | 2020-03-10T04:46:56.104000 | 2018-04-18T22:09:45 | 2018-04-18T22:09:45 | 129,201,276 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.timetable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.timetable.Employee.ShiftType;
public class Department {
private String name;
private List<Employee> dept = new ArrayList<Employee>();
private int score;
public Department(String name, List<Employee> dept) {
this.name = name;
this.dept = dept;
this.score=0; //set init score to 0;
}
public static int[] fitness(List<Employee> dept) {
int noDays;
int noNights;
int noDayoffs;
// for(Employee emp : dept) {
// for(Map.Entry<Day,ShiftType> partialTimeTable : emp.getPartialTimetable().entrySet()) {
//
// }
// }
// List<Integer> days;
//
// for(int i=1; i<dept.size(); i++) { //iterating through all employees first
// for(Map.Entry<Day,ShiftType> partialTimeTable : dept.get(i).getPartialTimetable().entrySet()) {
// if(partialTimeTable.getValue()==ShiftType.DAY) {
//
// }
// }
// }
int size=dept.get(0).getPartialTimetable().size();
int[] counter = new int[size];
ShiftType[] singleSchedule = new ShiftType[size];
for(int i=0;i<dept.size();i++) {
singleSchedule = (ShiftType[]) dept.get(i).getPartialTimetable().keySet().toArray(); //have to cast here
//,as toArray() return object type
for (int j=0;j<singleSchedule.length;j++) {
if(singleSchedule[j]==ShiftType.DAY) {
counter[j]++;
}
}
}
return counter;
}
}
| UTF-8 | Java | 1,496 | java | Department.java | Java | [] | null | [] | package com.timetable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.timetable.Employee.ShiftType;
public class Department {
private String name;
private List<Employee> dept = new ArrayList<Employee>();
private int score;
public Department(String name, List<Employee> dept) {
this.name = name;
this.dept = dept;
this.score=0; //set init score to 0;
}
public static int[] fitness(List<Employee> dept) {
int noDays;
int noNights;
int noDayoffs;
// for(Employee emp : dept) {
// for(Map.Entry<Day,ShiftType> partialTimeTable : emp.getPartialTimetable().entrySet()) {
//
// }
// }
// List<Integer> days;
//
// for(int i=1; i<dept.size(); i++) { //iterating through all employees first
// for(Map.Entry<Day,ShiftType> partialTimeTable : dept.get(i).getPartialTimetable().entrySet()) {
// if(partialTimeTable.getValue()==ShiftType.DAY) {
//
// }
// }
// }
int size=dept.get(0).getPartialTimetable().size();
int[] counter = new int[size];
ShiftType[] singleSchedule = new ShiftType[size];
for(int i=0;i<dept.size();i++) {
singleSchedule = (ShiftType[]) dept.get(i).getPartialTimetable().keySet().toArray(); //have to cast here
//,as toArray() return object type
for (int j=0;j<singleSchedule.length;j++) {
if(singleSchedule[j]==ShiftType.DAY) {
counter[j]++;
}
}
}
return counter;
}
}
| 1,496 | 0.622326 | 0.618316 | 59 | 23.355932 | 26.050644 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.559322 | false | false | 0 |
fe3fdfcc571617b0891b8a6bfb40022068eac5a3 | 23,424,751,688,063 | 9c4d6ea159977d243b71859814619c8ad51e683b | /src/main/java/com/weixin/sdk/api/MenuApi.java | b1ce55d4af180f9970cd7e94e53e908a142b84f6 | [] | no_license | liganga88/teapot | https://github.com/liganga88/teapot | 23473603033d7f6e0b5ea99d05b9b3b009a6fde3 | 66be83af9215f030be79efb64e1fa0b8ade74622 | refs/heads/master | 2020-04-07T05:24:46.942000 | 2018-05-20T08:48:07 | 2018-05-20T08:48:07 | 124,184,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.weixin.sdk.api;
import com.teapot.utils.JsonUtils;
import com.weixin.sdk.WeiXinConfig;
import com.weixin.sdk.util.HttpUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* menu api
*/
public class MenuApi {
private static String getMenu = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
private static String createMenu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
/**
* 查询自定义菜单
* @return {ApiResult}
*/
public static ApiResult getMenu() {
String jsonResult = HttpUtils.get(getMenu + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult getMenu(String token) {
String jsonResult = HttpUtils.get(getMenu + token);
return new ApiResult(jsonResult);
}
/**
* 创建自定义菜单
* @param jsonStr json字符串
* @return {ApiResult}
*/
public static ApiResult createMenu(String jsonStr) {
String jsonResult = HttpUtils.post(createMenu + AccessTokenApi.getAccessTokenStr(), jsonStr);
return new ApiResult(jsonResult);
}
public static ApiResult createMenu(String accessToken, String jsonStr) {
String jsonResult = HttpUtils.post(createMenu + accessToken, jsonStr);
return new ApiResult(jsonResult);
}
public static Result createMenu(String accessToken, Object btns) {
Map<String, String> textMap = new HashMap<String, String>();
textMap.put("access_token", accessToken);
Map<String, Object> map = new HashMap<>();
map.put("button", btns);
String result = HttpUtils.post(createMenu + accessToken, JsonUtils.objectToJson(map));
return JsonUtils.jsonToPojo(result, Result.class);
}
private static String deleteMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
/**
* 自定义菜单删除接口
* @return ApiResult
*/
public static ApiResult deleteMenu() {
String jsonResult = HttpUtils.get(deleteMenuUrl + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult deleteMenu(String accessToken) {
String jsonResult = HttpUtils.get(deleteMenuUrl + accessToken);
return new ApiResult(jsonResult);
}
private static String addConditionalUrl = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=";
/**
* 创建个性化菜单
* @param jsonStr json字符串
* @return {ApiResult}
*/
public static ApiResult addConditional(String jsonStr) {
String jsonResult = HttpUtils.post(addConditionalUrl + AccessTokenApi.getAccessTokenStr(), jsonStr);
return new ApiResult(jsonResult);
}
private static String delConditionalUrl = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=";
/**
* 删除个性化菜单
* @param menuid menuid为菜单id,可以通过自定义菜单查询接口获取。
* @return ApiResult
*/
public static ApiResult delConditional(String menuid) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("menuid", menuid);
String url = delConditionalUrl + AccessTokenApi.getAccessTokenStr();
String jsonResult = HttpUtils.post(url, JsonUtils.objectToJson(params));
return new ApiResult(jsonResult);
}
private static String tryMatchUrl = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=";
/**
* 测试个性化菜单匹配结果
* @param userId user_id可以是粉丝的OpenID,也可以是粉丝的微信号。
* @return ApiResult
*/
public static ApiResult tryMatch(String userId) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("user_id", userId);
String url = tryMatchUrl + AccessTokenApi.getAccessTokenStr();
String jsonResult = HttpUtils.post(url, JsonUtils.objectToJson(params));
return new ApiResult(jsonResult);
}
private static String getCurrentSelfMenuInfoUrl = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=";
/**
* 获取自定义菜单配置接口
* @return {ApiResult}
*/
public static ApiResult getCurrentSelfMenuInfo() {
String jsonResult = HttpUtils.get(getCurrentSelfMenuInfoUrl + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult getCurrentSelfMenuInfo(String accessToken) {
String jsonResult = HttpUtils.get(getCurrentSelfMenuInfoUrl + accessToken);
return new ApiResult(jsonResult);
}
public static void main(String[] args) {
//大明寺
AccessToken accessToken = AccessTokenApi.getAppAccessToken("wxba0a77ef0b45e8da", "2e9e978024b953b6df557af0622a59dd");
//测试平台
// AccessToken accessToken = AccessTokenApi.getAppAccessToken("wx12e9ba24f14539d5", "a4f2ea3151c86e7165ce58f217c5f7c5");
// deleteMenu(accessToken.getAccessToken());
List<Map<String, Object>> menus = new ArrayList<>();
List<Btn> carBtns1 = new ArrayList<>();
carBtns1.add(Btn.newMedia("大明简介","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newMedia("般若丈室","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newMedia("联系我们","IYd2EWf04GEjZCRElQNkL-Ep5z_xf-E-DLP4uYwCQTU"));
carBtns1.add(Btn.newMedia("大明律宗","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newView("日行一善", "http://www.1foli.com/support/getSupportedTempleDetailWx?hostid=608"));
Map<String, Object> m1 = new HashMap<>();
m1.put("name", "寺院巡礼");
m1.put("sub_button", carBtns1);
menus.add(m1);
List<Btn> carBtns2 = new ArrayList<>();
carBtns2.add(Btn.newView("鉴真文化", "http://www.1foli.com/wxTempleNews/getNewsdetail/4817/1"));
carBtns2.add(Btn.newMedia("佛学常识","p_4cjq7eL4YBwRdTCrPSXqTIhWxm9v3n8spdMIzULQs"));
carBtns2.add(Btn.newMedia("佛门故事","p_4cjq7eL4YBwRdTCrPSXqTIhWxm9v3n8spdMIzULQs"));
carBtns2.add(Btn.newMedia("皈依佛门","RE2sxz7s-MkotHHP9uB3WxSbGqI3tABDelLFbtux19k"));
carBtns2.add(Btn.newMedia("方丈微语","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
Map<String, Object> m2 = new HashMap<>();
m2.put("name", "佛教知识");
m2.put("sub_button", carBtns2);
menus.add(m2);
List<Btn> carBtns3 = new ArrayList<>();
carBtns3.add(Btn.newMedia("最新佛讯", "p_4cjq7eL4YBwRdTCrPSXrObQCdwJ_DcGeRiDErMV2c"));
carBtns3.add(Btn.newMedia("鉴真医堂", "p_4cjq7eL4YBwRdTCrPSXrObQCdwJ_DcGeRiDErMV2c"));
carBtns3.add(Btn.newMedia("大明慈善", "aY8wG9v4SdznpSlV0QT0_XZCyU5BNZH8xs1RFnFTDBc"));
carBtns3.add(Btn.newMedia("法务公告", "CgniKJXUN2ssHrmNRT7jfOQCMnTT4bd8m6811AhQ_zQ"));
carBtns3.add(Btn.newView("功德排名", "http://m.zijinwenchuang.com/customer/rank.html"));
Map<String, Object> m3 = new HashMap<>();
m3.put("name", "大明动态");
m3.put("sub_button", carBtns3);
menus.add(m3);
Map<String, Object> map = new HashMap<>();
map.put("button", menus);
System.out.println(JsonUtils.objectToJson(map));
Result result = createMenu(accessToken.getAccessToken(), menus);
System.out.println(result.getErrcode() + ", " + result.getErrmsg());
// ApiResult result = getMenu(accessToken.getAccessToken());
/*ApiResult result = getCurrentSelfMenuInfo("8_0Emnsh_f4uI3Xb8Hm60iJnYwmWeWsPgOMe8wItX6zO4PXO_Nvhuln13gfTg9s3lGaJEmO82RBCnH0pabXx0NXZfwgk8U72hgZbXtYl_mqE5FtpYXjFhtqkKnn9_VeEIUCUJEp18kQQAaJfl4HPNcAHAYGE");
System.out.println(result.toString());*/
}
}
| UTF-8 | Java | 8,122 | java | MenuApi.java | Java | [
{
"context": "/**\n * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).\n *\n * Licensed under the Apa",
"end": 42,
"score": 0.9998359084129333,
"start": 32,
"tag": "NAME",
"value": "James Zhan"
},
{
"context": "/**\n * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).\... | null | [] | /**
* Copyright (c) 2011-2014, <NAME> 詹波 (<EMAIL>).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.weixin.sdk.api;
import com.teapot.utils.JsonUtils;
import com.weixin.sdk.WeiXinConfig;
import com.weixin.sdk.util.HttpUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* menu api
*/
public class MenuApi {
private static String getMenu = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=";
private static String createMenu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
/**
* 查询自定义菜单
* @return {ApiResult}
*/
public static ApiResult getMenu() {
String jsonResult = HttpUtils.get(getMenu + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult getMenu(String token) {
String jsonResult = HttpUtils.get(getMenu + token);
return new ApiResult(jsonResult);
}
/**
* 创建自定义菜单
* @param jsonStr json字符串
* @return {ApiResult}
*/
public static ApiResult createMenu(String jsonStr) {
String jsonResult = HttpUtils.post(createMenu + AccessTokenApi.getAccessTokenStr(), jsonStr);
return new ApiResult(jsonResult);
}
public static ApiResult createMenu(String accessToken, String jsonStr) {
String jsonResult = HttpUtils.post(createMenu + accessToken, jsonStr);
return new ApiResult(jsonResult);
}
public static Result createMenu(String accessToken, Object btns) {
Map<String, String> textMap = new HashMap<String, String>();
textMap.put("access_token", accessToken);
Map<String, Object> map = new HashMap<>();
map.put("button", btns);
String result = HttpUtils.post(createMenu + accessToken, JsonUtils.objectToJson(map));
return JsonUtils.jsonToPojo(result, Result.class);
}
private static String deleteMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
/**
* 自定义菜单删除接口
* @return ApiResult
*/
public static ApiResult deleteMenu() {
String jsonResult = HttpUtils.get(deleteMenuUrl + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult deleteMenu(String accessToken) {
String jsonResult = HttpUtils.get(deleteMenuUrl + accessToken);
return new ApiResult(jsonResult);
}
private static String addConditionalUrl = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=";
/**
* 创建个性化菜单
* @param jsonStr json字符串
* @return {ApiResult}
*/
public static ApiResult addConditional(String jsonStr) {
String jsonResult = HttpUtils.post(addConditionalUrl + AccessTokenApi.getAccessTokenStr(), jsonStr);
return new ApiResult(jsonResult);
}
private static String delConditionalUrl = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=";
/**
* 删除个性化菜单
* @param menuid menuid为菜单id,可以通过自定义菜单查询接口获取。
* @return ApiResult
*/
public static ApiResult delConditional(String menuid) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("menuid", menuid);
String url = delConditionalUrl + AccessTokenApi.getAccessTokenStr();
String jsonResult = HttpUtils.post(url, JsonUtils.objectToJson(params));
return new ApiResult(jsonResult);
}
private static String tryMatchUrl = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=";
/**
* 测试个性化菜单匹配结果
* @param userId user_id可以是粉丝的OpenID,也可以是粉丝的微信号。
* @return ApiResult
*/
public static ApiResult tryMatch(String userId) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("user_id", userId);
String url = tryMatchUrl + AccessTokenApi.getAccessTokenStr();
String jsonResult = HttpUtils.post(url, JsonUtils.objectToJson(params));
return new ApiResult(jsonResult);
}
private static String getCurrentSelfMenuInfoUrl = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=";
/**
* 获取自定义菜单配置接口
* @return {ApiResult}
*/
public static ApiResult getCurrentSelfMenuInfo() {
String jsonResult = HttpUtils.get(getCurrentSelfMenuInfoUrl + AccessTokenApi.getAccessTokenStr());
return new ApiResult(jsonResult);
}
public static ApiResult getCurrentSelfMenuInfo(String accessToken) {
String jsonResult = HttpUtils.get(getCurrentSelfMenuInfoUrl + accessToken);
return new ApiResult(jsonResult);
}
public static void main(String[] args) {
//大明寺
AccessToken accessToken = AccessTokenApi.getAppAccessToken("<PASSWORD>", "<PASSWORD>");
//测试平台
// AccessToken accessToken = AccessTokenApi.getAppAccessToken("<PASSWORD>", "<PASSWORD>");
// deleteMenu(accessToken.getAccessToken());
List<Map<String, Object>> menus = new ArrayList<>();
List<Btn> carBtns1 = new ArrayList<>();
carBtns1.add(Btn.newMedia("大明简介","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newMedia("般若丈室","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newMedia("联系我们","IYd2EWf04GEjZCRElQNkL-Ep5z_xf-E-DLP4uYwCQTU"));
carBtns1.add(Btn.newMedia("大明律宗","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6BfCAqYseZRzk"));
carBtns1.add(Btn.newView("日行一善", "http://www.1foli.com/support/getSupportedTempleDetailWx?hostid=608"));
Map<String, Object> m1 = new HashMap<>();
m1.put("name", "寺院巡礼");
m1.put("sub_button", carBtns1);
menus.add(m1);
List<Btn> carBtns2 = new ArrayList<>();
carBtns2.add(Btn.newView("鉴真文化", "http://www.1foli.com/wxTempleNews/getNewsdetail/4817/1"));
carBtns2.add(Btn.newMedia("佛学常识","p_<KEY>"));
carBtns2.add(Btn.newMedia("佛门故事","p_4cjq7eL4YBwRdTCrPSXqTIhWxm9v3n8spdMIzULQs"));
carBtns2.add(Btn.newMedia("皈依佛门","RE2sxz7s-MkotHHP9uB3WxSbGqI3tABDelLFbtux19k"));
carBtns2.add(Btn.newMedia("方丈微语","p_4cjq7eL4YBwRdTCrPSXoHtJDwK3H6<KEY>"));
Map<String, Object> m2 = new HashMap<>();
m2.put("name", "佛教知识");
m2.put("sub_button", carBtns2);
menus.add(m2);
List<Btn> carBtns3 = new ArrayList<>();
carBtns3.add(Btn.newMedia("最新佛讯", "p_4cjq7eL4YBwRdTCrPSXrObQCdwJ_DcGeRiDErMV2c"));
carBtns3.add(Btn.newMedia("鉴真医堂", "p_4cjq7eL4YBwRdTCrPSXrObQCdwJ_DcGeRiDErMV2c"));
carBtns3.add(Btn.newMedia("大明慈善", "aY8wG9v4SdznpSlV0QT0_XZCyU5BNZH8xs1RFnFTDBc"));
carBtns3.add(Btn.newMedia("法务公告", "CgniKJXUN2ssHrmNRT7jfOQCMnTT4bd8m6811AhQ_zQ"));
carBtns3.add(Btn.newView("功德排名", "http://m.zijinwenchuang.com/customer/rank.html"));
Map<String, Object> m3 = new HashMap<>();
m3.put("name", "大明动态");
m3.put("sub_button", carBtns3);
menus.add(m3);
Map<String, Object> map = new HashMap<>();
map.put("button", menus);
System.out.println(JsonUtils.objectToJson(map));
Result result = createMenu(accessToken.getAccessToken(), menus);
System.out.println(result.getErrcode() + ", " + result.getErrmsg());
// ApiResult result = getMenu(accessToken.getAccessToken());
/*ApiResult result = getCurrentSelfMenuInfo("<KEY>");
System.out.println(result.toString());*/
}
}
| 7,857 | 0.681713 | 0.654759 | 194 | 38.958763 | 37.135284 | 212 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747423 | false | false | 0 |
5e30262853a10fae54c66bc64e0320fadb6babf0 | 996,432,428,036 | eeaf575311f5fe6bd6f3909c43b85fd108886480 | /smartwf-health-man/src/main/java/com/smartwf/hm/modules/admin/service/IotRealTimeDataService.java | 8afaf3b3f327a51669e6f27c86bed84850b08e16 | [] | no_license | wanwuchunsheng/smartwf | https://github.com/wanwuchunsheng/smartwf | 889e7fd5cf7905335e22c96b5cc6d12bb3dae9f3 | 3011606fa5142786e9fdfbdf8669bb072ceb6cdc | refs/heads/master | 2022-07-31T03:49:38.216000 | 2021-04-23T05:18:10 | 2021-04-23T05:18:10 | 221,856,992 | 0 | 4 | null | false | 2022-06-29T17:46:50 | 2019-11-15T06:15:38 | 2021-04-23T05:18:20 | 2022-06-29T17:46:49 | 2,960 | 0 | 3 | 3 | Java | false | false | package com.smartwf.hm.modules.admin.service;
public interface IotRealTimeDataService {
/**
* 说明:底层实时数据
*
*
* @author WCH
* @datetime 2020-12-23 13:15:48
*
* */
void saveIotRealTimeData(String string);
}
| UTF-8 | Java | 244 | java | IotRealTimeDataService.java | Java | [
{
"context": "ervice {\n\n\t/**\n\t * 说明:底层实时数据\n\t * \n\t * \n\t * @author WCH\n\t * @datetime 2020-12-23 13:15:48\n\t * \n\t * */\n\tvo",
"end": 134,
"score": 0.9992865324020386,
"start": 131,
"tag": "USERNAME",
"value": "WCH"
}
] | null | [] | package com.smartwf.hm.modules.admin.service;
public interface IotRealTimeDataService {
/**
* 说明:底层实时数据
*
*
* @author WCH
* @datetime 2020-12-23 13:15:48
*
* */
void saveIotRealTimeData(String string);
}
| 244 | 0.659292 | 0.597345 | 15 | 14.066667 | 16.335918 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 0 |
936bcc5d0104145fd28d13ba50099eadb0aa4fe2 | 23,390,391,944,378 | e6650815bd64d76d5749058a3f6f8af94267baa6 | /src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSImage.java | 7045ef7a4f0e07acdc8634991dd60a88140223f5 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | ymmah/hadoop-20 | https://github.com/ymmah/hadoop-20 | 1763fd3b2ac41e3b59dd4d6cc9f47a04f38193bf | 8987caf62c9f0b87bc9767c5510146c83f205285 | refs/heads/master | 2020-03-27T13:50:43.264000 | 2018-08-29T17:10:21 | 2018-08-29T17:10:21 | 146,631,291 | 0 | 0 | Apache-2.0 | true | 2018-08-29T16:55:33 | 2018-08-29T16:55:33 | 2018-08-29T12:04:21 | 2014-10-10T18:40:53 | 56,550 | 0 | 0 | 0 | null | false | null | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.protocol.LayoutVersion;
import org.apache.hadoop.hdfs.protocol.LayoutVersion.Feature;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.Transition;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.common.Storage.FormatConfirmable;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirType;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.common.Storage.StorageState;
import org.apache.hadoop.hdfs.server.common.StorageInfo;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeDirType;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.StorageLocationType;
import org.apache.hadoop.hdfs.server.namenode.ValidateNamespaceDirPolicy.NNStorageLocation;
import org.apache.hadoop.hdfs.server.namenode.metrics.NameNodeMetrics;
import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog;
import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest;
import org.apache.hadoop.hdfs.util.InjectionEvent;
import org.apache.hadoop.hdfs.util.MD5FileUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.util.FlushableLogger;
import org.apache.hadoop.util.InjectionEventI;
import org.apache.hadoop.util.InjectionHandler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* FSImage handles checkpointing and logging of the namespace edits.
*
*/
public class FSImage {
static final Log LOG = LogFactory.getLog(FSImage.class.getName());
// immediate flush logger
private static final Log FLOG = FlushableLogger.getLogger(LOG);
NNStorage storage;
Configuration conf;
private NNStorageRetentionManager archivalManager;
private final SaveNamespaceContext saveNamespaceContext
= new SaveNamespaceContext();
protected FSNamesystem namesystem = null;
FSEditLog editLog = null;
ImageSet imageSet = null;
private boolean isUpgradeFinalized = false;
private NameNodeMetrics metrics = NameNode.getNameNodeMetrics();
// intermediate buffer size for image saving and loading
public static int LOAD_SAVE_BUFFER_SIZE = 4 * 1024 * 1024; // 4MB
// chunk size for copying out or into the intermediate buffer
public static int LOAD_SAVE_CHUNK_SIZE = 512 * 1024; // 512KB
/**
* Constructor
* @param conf Configuration
*/
FSImage(Configuration conf) throws IOException {
storage = new NNStorage(new StorageInfo());
this.editLog = new FSEditLog(conf, this, storage,
NNStorageConfiguration.getNamespaceDirs(conf),
NNStorageConfiguration.getNamespaceEditsDirs(conf), null);
this.imageSet = new ImageSet(this, null, null, metrics);
setFSNamesystem(null);
this.conf = conf;
archivalManager = new NNStorageRetentionManager(conf, storage, editLog);
}
/**
*/
FSImage(Configuration conf, Collection<URI> fsDirs,
Collection<URI> fsEditsDirs, Map<URI, NNStorageLocation> locationMap)
throws IOException {
this.conf = conf;
storage = new NNStorage(conf, fsDirs, fsEditsDirs, locationMap);
this.editLog = new FSEditLog(conf, this, storage, fsDirs, fsEditsDirs,
locationMap);
this.imageSet = new ImageSet(this, fsDirs, fsEditsDirs, metrics);
archivalManager = new NNStorageRetentionManager(conf, storage, editLog);
}
public boolean failOnTxIdMismatch() {
if (namesystem == null) {
return true;
} else {
return namesystem.failOnTxIdMismatch();
}
}
protected FSNamesystem getFSNamesystem() {
return namesystem;
}
protected void setFSNamesystem(FSNamesystem ns) {
namesystem = ns;
}
public long getLastAppliedTxId() {
return editLog.getLastWrittenTxId();
}
List<StorageDirectory> getRemovedStorageDirs() {
return storage.getRemovedStorageDirs();
}
/**
* Get the MD5 digest of the current image
* @return the MD5 digest of the current image
*/
MD5Hash getImageDigest(long txid) throws IOException {
return storage.getCheckpointImageDigest(txid);
}
void setImageDigest(long txid, MD5Hash imageDigest) throws IOException {
this.storage.setCheckpointImageDigest(txid, imageDigest);
}
private void throwIOException(String msg) throws IOException {
LOG.error(msg);
throw new IOException(msg);
}
private void updateRemoteStates(
Map<ImageManager, RemoteStorageState> remoteImageStates,
Map<JournalManager, RemoteStorageState> remoteJournalStates,
List<ImageManager> nonFileImageManagers,
List<JournalManager> nonFileJournalManagers)
throws IOException {
// / analyze non file storage location
// List non-file storage
FLOG.info("Startup: non-file image managers:");
for (ImageManager im : nonFileImageManagers) {
RemoteStorageState st = im.analyzeImageStorage();
FLOG.info("-> Image Manager: " + im + " state: " + st.getStorageState());
if (st.getStorageState() == StorageState.INCONSISTENT) {
throwIOException("Image manager has inconsistent state: " + im
+ ", state: " + st.getStorageState());
}
remoteImageStates.put(im, st);
}
FLOG.info("Startup: non-file journal managers:");
for (JournalManager jm : nonFileJournalManagers) {
RemoteStorageState st = jm.analyzeJournalStorage();
FLOG.info("-> Journal Manager: " + jm + " state: " + st.getStorageState());
if (st.getStorageState() == StorageState.INCONSISTENT) {
throwIOException("Journal manager has inconsistent state: " + jm
+ ", state: " + st.getStorageState());
}
remoteJournalStates.put(jm, st);
}
}
/**
* Analyze storage directories.
* Recover from previous transitions if required.
* Perform fs state transition if necessary depending on the namespace info.
* Read storage info.
*
* @throws IOException
* @return true if the image needs to be saved or false otherwise
*/
public boolean recoverTransitionRead(StartupOption startOpt)
throws IOException {
FLOG.info("Startup: recovering namenode storage");
assert startOpt != StartupOption.FORMAT :
"NameNode formatting should be performed before reading the image";
Collection<File> imageDirs = storage.getImageDirectories();
// none of the data dirs exist
if(imageDirs.size() == 0 && startOpt != StartupOption.IMPORT)
throw new IOException(
"All specified directories are not accessible or do not exist.");
editLog.checkJournals();
storage.setUpgradeManager(namesystem.upgradeManager);
Map<ImageManager, RemoteStorageState> remoteImageStates = Maps.newHashMap();
Map<JournalManager, RemoteStorageState> remoteJournalStates = Maps.newHashMap();
List<ImageManager> nonFileImageManagers = getNonFileImageManagers();
List<JournalManager> nonFileJournalManagers = getNonFileJournalManagers();
updateRemoteStates(remoteImageStates, remoteJournalStates,
nonFileImageManagers, nonFileJournalManagers);
// number of non-file storage locations
int nonFileStorageLocations = nonFileImageManagers.size()
+ nonFileJournalManagers.size();
FLOG.info("Startup: checking storage directory state.");
// 1. For each data directory calculate its state and
// check whether all is consistent before transitioning.
Map<StorageDirectory, StorageState> dataDirStates =
new HashMap<StorageDirectory, StorageState>();
boolean isFormatted = recoverStorageDirs(startOpt, dataDirStates);
// Recover the non-file storage locations.
editLog.transitionNonFileJournals(null, false,
Transition.RECOVER, startOpt);
imageSet.transitionNonFileImages(null, false, Transition.RECOVER,
startOpt);
if (!isFormatted && startOpt != StartupOption.ROLLBACK
&& startOpt != StartupOption.IMPORT) {
for(Entry<StorageDirectory, StorageState> e : dataDirStates.entrySet()) {
LOG.info("State : " + e.getKey().getCurrentDir() + " state: " +e.getValue());
}
throw new IOException("NameNode is not formatted." + dataDirStates);
}
int layoutVersion = storage.getLayoutVersion();
if (layoutVersion < Storage.LAST_PRE_UPGRADE_LAYOUT_VERSION) {
NNStorage.checkVersionUpgradable(storage.getLayoutVersion());
}
if (startOpt != StartupOption.UPGRADE
&& layoutVersion < Storage.LAST_PRE_UPGRADE_LAYOUT_VERSION
&& layoutVersion != FSConstants.LAYOUT_VERSION) {
throw new IOException(
"\nFile system image contains an old layout version "
+ storage.getLayoutVersion() + ".\nAn upgrade to version "
+ FSConstants.LAYOUT_VERSION + " is required.\n"
+ "Please restart NameNode with -upgrade option.");
}
editLog.updateNamespaceInfo(storage);
// check whether distributed upgrade is required and/or should be continued
storage.verifyDistributedUpgradeProgress(startOpt);
FLOG.info("Startup: formatting unformatted directories.");
// 2. Format unformatted dirs.
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
StorageState curState = dataDirStates.get(sd);
switch(curState) {
case NON_EXISTENT:
throw new IOException(StorageState.NON_EXISTENT +
" state cannot be here");
case NOT_FORMATTED:
LOG.info("Storage directory " + sd.getRoot() + " is not formatted.");
if (!sd.isEmpty()) {
LOG.error("Storage directory " + sd.getRoot()
+ " is not empty, and will not be formatted! Exiting.");
throw new IOException(
"Storage directory " + sd.getRoot() + " is not empty!");
}
LOG.info("Formatting ...");
sd.clearDirectory(); // create empty currrent dir
break;
default:
break;
}
}
// check non-file images
for (Entry<ImageManager, RemoteStorageState> e : remoteImageStates
.entrySet()) {
checkAllowedNonFileState(e.getValue().getStorageState(), e.getKey());
}
// check non-file journals
for (Entry<JournalManager, RemoteStorageState> e : remoteJournalStates
.entrySet()) {
checkAllowedNonFileState(e.getValue().getStorageState(), e.getKey());
}
FLOG.info("Startup: Transitions.");
// 3. Do transitions
switch(startOpt) {
case UPGRADE:
doUpgrade();
return false; // upgrade saved image already
case IMPORT:
doImportCheckpoint();
if (nonFileStorageLocations > 0) {
throwIOException("Import not supported for non-file storage");
}
return false; // import checkpoint saved image already
case ROLLBACK:
doRollback(remoteImageStates, remoteJournalStates);
// Update the states since the remote states have changed after rollback.
updateRemoteStates(remoteImageStates, remoteJournalStates,
nonFileImageManagers, nonFileJournalManagers);
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_ROLLBACK_DONE);
break;
case REGULAR:
// just load the image
}
if (inUpgradeStatus()) {
namesystem.setUpgradeStartTime(FSNamesystem.now());
}
// final consistency check for non-file images and journals
// read version file first
FSImageStorageInspector inspector = storage.readAndInspectDirs();
FLOG.info("Startup: starting with storage info: " + storage.toColonSeparatedString());
// format unformatted journals and images
// check if the formatted ones are consistent with local storage
for (Entry<ImageManager, RemoteStorageState> e : remoteImageStates
.entrySet()) {
if (e.getValue().getStorageState() != StorageState.NORMAL) {
LOG.info("Formatting remote image: " + e.getKey());
e.getKey().transitionImage(storage, Transition.FORMAT, null);
} else {
checkConsistency(e.getValue().getStorageInfo(), storage, true, e.getKey());
}
}
for (Entry<JournalManager, RemoteStorageState> e : remoteJournalStates
.entrySet()) {
if (e.getValue().getStorageState() != StorageState.NORMAL) {
LOG.info("Formatting remote journal: " + e.getKey());
e.getKey().transitionJournal(storage, Transition.FORMAT, null);
} else {
checkConsistency(e.getValue().getStorageInfo(), storage, true, e.getKey());
}
}
// load the image
return loadFSImage(inspector);
}
/**
* Check if the remote image/journal storage info is the same as ours
*/
private void checkConsistency(StorageInfo remote, StorageInfo local,
boolean image, Object name) throws IOException {
if (!remote.equals(local)) {
throwIOException("Remote " + (image ? "image" : "edits")
+ " storage is different than local. Local: ("
+ local.toColonSeparatedString() + "), remote: " + name.toString()
+ " (" + remote.toColonSeparatedString() + ")");
}
}
/**
* Check if remote image/journal storage is in allowed state.
*/
private void checkAllowedNonFileState(StorageState curState, Object name)
throws IOException {
switch (curState) {
case NON_EXISTENT:
case NOT_FORMATTED:
case NORMAL:
break;
default:
throwIOException("ImageManager bad state: " + curState + " for: "
+ name.toString());
}
}
/**
* @return true if Nn is under upgrade.
*/
private boolean inUpgradeStatus() {
for (Iterator <StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
File preDir = sd.getPreviousDir();
if (preDir.exists()) {
return true;
}
}
return false;
}
/**
* For each storage directory, performs recovery of incomplete transitions
* (eg. upgrade, rollback, checkpoint) and inserts the directory's storage
* state into the dataDirStates map.
* @param dataDirStates output of storage directory states
* @return true if there is at least one valid formatted storage directory
*/
private boolean recoverStorageDirs(StartupOption startOpt,
Map<StorageDirectory, StorageState> dataDirStates) throws IOException {
boolean isFormatted = false;
for (Iterator<StorageDirectory> it =
storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
StorageState curState;
try {
curState = sd.analyzeStorage(startOpt);
isFormatted |= NNStorage.recoverDirectory(sd, startOpt, curState, true);
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
dataDirStates.put(sd,curState);
}
return isFormatted;
}
private void doUpgrade() throws IOException {
namesystem.setUpgradeStartTime(FSNamesystem.now());
if(storage.getDistributedUpgradeState()) {
// only distributed upgrade need to continue
// don't do version upgrade
FSImageStorageInspector inspector = storage.readAndInspectDirs();
this.loadFSImage(inspector);
storage.initializeDistributedUpgrade();
return;
}
// Upgrade is allowed only if there are
// no previous fs states in any of the directories
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
if (sd.getPreviousDir().exists())
throw new InconsistentFSStateException(sd.getRoot(),
"previous fs state should not exist during upgrade. "
+ "Finalize or rollback first.");
}
FSImageStorageInspector inspector = storage.readAndInspectDirs();
// load the latest image
this.loadFSImage(inspector);
// clear the digest for the loaded image, it might change during upgrade
this.storage.clearCheckpointImageDigest(storage
.getMostRecentCheckpointTxId());
// Do upgrade for each directory
long oldCTime = storage.getCTime();
this.storage.cTime = FSNamesystem.now(); // generate new cTime for the state
int oldLV = storage.getLayoutVersion();
this.storage.layoutVersion = FSConstants.LAYOUT_VERSION;
assert !editLog.isOpen() : "Edits log must not be open.";
List<StorageDirectory> errorSDs =
Collections.synchronizedList(new ArrayList<StorageDirectory>());
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
LOG.info("Starting upgrade of image directory " + sd.getRoot()
+ ".\n old LV = " + oldLV
+ "; old CTime = " + oldCTime
+ ".\n new LV = " + storage.getLayoutVersion()
+ "; new CTime = " + storage.getCTime());
try {
Storage.upgradeDirectory(sd);
} catch (Exception e) {
LOG.error("Failed to move aside pre-upgrade storage " +
"in image directory " + sd.getRoot(), e);
errorSDs.add(sd);
continue;
}
}
// Upgrade non-file directories.
imageSet.transitionNonFileImages(storage, false, Transition.UPGRADE,
null);
editLog.transitionNonFileJournals(storage, false,
Transition.UPGRADE, null);
storage.reportErrorsOnDirectories(errorSDs, this);
errorSDs.clear();
InjectionHandler
.processEventIO(InjectionEvent.FSIMAGE_UPGRADE_BEFORE_SAVE_IMAGE);
saveFSImageInAllDirs(editLog.getLastWrittenTxId(), false);
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
try {
Storage.completeUpgrade(sd);
} catch (IOException ioe) {
LOG.error("Unable to rename temp to previous for " + sd.getRoot(), ioe);
errorSDs.add(sd);
continue;
}
isUpgradeFinalized = false;
LOG.info("Upgrade of " + sd.getRoot() + " is complete.");
}
// Complete the upgrade for non-file directories.
imageSet.transitionNonFileImages(storage, false,
Transition.COMPLETE_UPGRADE, null);
editLog.transitionNonFileJournals(storage, false,
Transition.COMPLETE_UPGRADE, null);
storage.reportErrorsOnDirectories(errorSDs, this);
storage.initializeDistributedUpgrade();
}
private void doRollback(
Map<ImageManager, RemoteStorageState> remoteImageStates,
Map<JournalManager, RemoteStorageState> remoteJournalStates)
throws IOException {
// Rollback is allowed only if there is
// a previous fs states in at least one of the storage directories.
// Directories that don't have previous state do not rollback
boolean canRollback = false;
FSImage prevState = new FSImage(conf);
prevState.storage.layoutVersion = FSConstants.LAYOUT_VERSION;
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
canRollback = NNStorage.canRollBack(sd, prevState.storage);
}
// Check non-file managers.
for (RemoteStorageState s : remoteImageStates.values()) {
StorageState state = s.getStorageState();
if (state == StorageState.UPGRADE_DONE) {
canRollback = true;
}
}
// Check non-file managers.
for (RemoteStorageState s : remoteJournalStates.values()) {
StorageState state = s.getStorageState();
if (state == StorageState.UPGRADE_DONE) {
canRollback = true;
}
}
if (!canRollback)
throw new IOException("Cannot rollback. None of the storage "
+ "directories contain previous fs state.");
// Now that we know all directories are going to be consistent
// Do rollback for each directory containing previous state
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
NNStorage.doRollBack(sd, prevState.storage);
}
// Rollback non-file storage locations.
editLog.transitionNonFileJournals(storage, false, Transition.ROLLBACK,
null);
imageSet.transitionNonFileImages(storage, false, Transition.ROLLBACK, null);
isUpgradeFinalized = true;
// check whether name-node can start in regular mode
storage.verifyDistributedUpgradeProgress(StartupOption.REGULAR);
}
private void doFinalize(StorageDirectory sd) throws IOException {
NNStorage.finalize(sd, storage.getLayoutVersion(), storage.getCTime());
isUpgradeFinalized = true;
}
/**
* Load image from a checkpoint directory and save it into the current one.
* @throws IOException
*/
/**
* Load image from a checkpoint directory and save it into the current one.
* @param target the NameSystem to import into
* @throws IOException
*/
void doImportCheckpoint() throws IOException {
Collection<URI> checkpointDirs =
NNStorageConfiguration.getCheckpointDirs(conf, null);
Collection<URI> checkpointEditsDirs =
NNStorageConfiguration.getCheckpointEditsDirs(conf, null);
if (checkpointDirs == null || checkpointDirs.isEmpty()) {
throw new IOException("Cannot import image from a checkpoint. "
+ "\"dfs.namenode.checkpoint.dir\" is not set." );
}
if (checkpointEditsDirs == null || checkpointEditsDirs.isEmpty()) {
throw new IOException("Cannot import image from a checkpoint. "
+ "\"dfs.namenode.checkpoint.dir\" is not set." );
}
// replace real image with the checkpoint image
FSImage realImage = namesystem.getFSImage();
assert realImage == this;
FSImage ckptImage = new FSImage(conf,
checkpointDirs, checkpointEditsDirs, null);
ckptImage.setFSNamesystem(namesystem);
namesystem.dir.fsImage = ckptImage;
// load from the checkpoint dirs
try {
ckptImage.recoverTransitionRead(StartupOption.REGULAR);
} finally {
ckptImage.close();
}
// return back the real image
realImage.storage.setStorageInfo(ckptImage.storage);
realImage.getEditLog().setLastWrittenTxId(ckptImage.getEditLog().getLastWrittenTxId() + 1);
namesystem.dir.fsImage = realImage;
// and save it but keep the same checkpointTime
// parameters
saveNamespace();
}
public void finalizeUpgrade() throws IOException {
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
doFinalize(it.next());
}
// finalize non-file storage locations.
editLog.transitionNonFileJournals(null, false, Transition.FINALIZE, null);
imageSet.transitionNonFileImages(null, false, Transition.FINALIZE, null);
isUpgradeFinalized = true;
namesystem.setUpgradeStartTime(0);
}
boolean isUpgradeFinalized() {
return isUpgradeFinalized;
}
public FSEditLog getEditLog() {
return editLog;
}
public List<ImageManager> getImageManagers() {
return imageSet.getImageManagers();
}
void openEditLog() throws IOException {
if (editLog == null) {
throw new IOException("EditLog must be initialized");
}
if (!editLog.isOpen()) {
editLog.open();
storage
.writeTransactionIdFileToStorage(editLog.getCurSegmentTxId(), this);
}
};
/**
* Choose latest image from one of the directories,
* load it and merge with the edits from that directory.
*
* @return whether the image should be saved
* @throws IOException
*/
boolean loadFSImage(FSImageStorageInspector inspector) throws IOException {
ImageInputStream iis = null;
isUpgradeFinalized = inspector.isUpgradeFinalized();
FSImageStorageInspector.FSImageFile imageFile = inspector.getLatestImage();
boolean needToSave = inspector.needToSave();
FSImageStorageInspector.FSImageFile nonFileImage = imageSet
.getLatestImageFromNonFileImageManagers();
boolean loadingNonFileImage = false;
// image stored in non-file storage is newer, we obtain the input stream here
// recover unclosed streams, so the journals storing image are initialized
editLog.recoverUnclosedStreams();
long imageCheckpointTxId;
if (nonFileImage != null
&& (nonFileImage.getCheckpointTxId() > imageFile.getCheckpointTxId() || conf
.getBoolean("dfs.force.remote.image", false))) {
// this will contain the digest
LOG.info("Non-file image is newer/forced.");
iis = nonFileImage.getImageManager().getImageInputStream(
nonFileImage.getCheckpointTxId());
imageCheckpointTxId = nonFileImage.getCheckpointTxId();
loadingNonFileImage = true;
} else {
// the md5 digest will be set later
iis = new ImageInputStream(imageFile.getCheckpointTxId(),
new FileInputStream(imageFile.getFile()), null, imageFile.getFile()
.getAbsolutePath(), imageFile.getFile().length());
imageCheckpointTxId = imageFile.getCheckpointTxId();
loadingNonFileImage = false;
}
Collection<EditLogInputStream> editStreams = new ArrayList<EditLogInputStream>();
// if the recovery failed for any journals, just abort the startup.
if (editLog.getNumberOfAvailableJournals() != editLog.getNumberOfJournals()) {
LOG.fatal("Unable to recover unclosed segments for all journals.");
throw new IOException(
"Unable to recover unclosed segments for all journals.");
}
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
FLOG.info("Load Image: checkpoint txid: " + imageCheckpointTxId
+ " max seen: " + inspector.getMaxSeenTxId());
needToSave |= editLog.selectInputStreams(editStreams,
imageCheckpointTxId + 1, inspector.getMaxSeenTxId(),
editLog.getNumberOfJournals());
} else {
FSImagePreTransactionalStorageInspector.getEditLogStreams(editStreams,
storage, conf);
}
FLOG.info("Load Image: planning to load image :\n" + iis);
for (EditLogInputStream l : editStreams) {
FLOG.info("Load Image: planning to load edit stream: " + l);
}
try {
if (!loadingNonFileImage) {
StorageDirectory sdForProperties = imageFile.sd;
sdForProperties.read();
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
// For txid-based layout, we should have a .md5 file
// next to the image file
loadFSImage(iis, imageFile.getFile());
} else if (LayoutVersion.supports(Feature.FSIMAGE_CHECKSUM,
getLayoutVersion())) {
// In 0.22, we have the checksum stored in the VERSION file.
String md5 = storage
.getDeprecatedProperty(NNStorage.MESSAGE_DIGEST_PROPERTY);
if (md5 == null) {
throw new InconsistentFSStateException(sdForProperties.getRoot(),
"Message digest property " + NNStorage.MESSAGE_DIGEST_PROPERTY
+ " not set for storage directory "
+ sdForProperties.getRoot());
}
iis.setImageDigest(new MD5Hash(md5));
loadFSImage(iis);
} else {
// We don't have any record of the md5sum
loadFSImage(iis);
}
} else {
if (!LayoutVersion.supports(Feature.TXID_BASED_LAYOUT,
getLayoutVersion())) {
throwIOException("Inconsistency: Loading remote image, but the layout does not support txids: "
+ getLayoutVersion());
}
// loading non-file
loadFSImage(iis);
}
} catch (IOException ioe) {
FSEditLog.closeAllStreams(editStreams);
throw new IOException("Failed to load image from " +
(loadingNonFileImage ? nonFileImage : imageFile), ioe);
}
editLog.setLastWrittenTxId(storage.getMostRecentCheckpointTxId());
long numLoaded = loadEdits(editStreams);
needToSave |= needsResaveBasedOnStaleCheckpoint(loadingNonFileImage ? null
: imageFile.getFile(), numLoaded);
return needToSave;
}
/**
* @param imageFile
* the image file that was loaded (if remote location was loaded that
* this is null)
* @param numEditsLoaded
* the number of edits loaded from edits logs
* @return true if the NameNode should automatically save the namespace when
* it is started, due to the latest checkpoint being too old.
*/
private boolean needsResaveBasedOnStaleCheckpoint(File imageFile,
long numEditsLoaded) {
final long checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
final long checkpointTxnCount = NNStorageConfiguration.getCheckpointTxnCount(conf);
long checkpointAge = System.currentTimeMillis()
- (imageFile == null ? Long.MAX_VALUE : imageFile.lastModified());
boolean needToSave = (checkpointAge > checkpointPeriod * 1000)
|| (numEditsLoaded > checkpointTxnCount);
LOG.info("Load Image: Need to save based on stale checkpoint: "
+ needToSave);
return needToSave;
}
/**
* Load the image namespace from the given image file, verifying it against
* the MD5 sum stored in its associated .md5 file.
*/
protected void loadFSImage(ImageInputStream iis, File imageFile) throws IOException {
MD5Hash expectedMD5 = MD5FileUtils.readStoredMd5ForFile(imageFile);
if (expectedMD5 == null) {
throw new IOException("No MD5 file found corresponding to image file "
+ imageFile);
}
iis.setImageDigest(expectedMD5);
loadFSImage(iis);
}
boolean loadFSImage(ImageInputStream iis) throws IOException {
assert iis != null : "input stream is null";
FSImageFormat.Loader loader = new FSImageFormat.Loader(
namesystem.getConf(), namesystem, storage);
loader.load(iis, null);
saveNamespaceContext.set(null, loader.getLoadedImageTxId());
// Check that the image digest we loaded matches up with what
// we expected
MD5Hash readImageMd5 = loader.getLoadedImageMd5();
MD5Hash expectedMd5 = iis.getDigest();
if (expectedMd5 != null && !expectedMd5.equals(readImageMd5)) {
throw new IOException("Image file " + iis
+ " is corrupt with MD5 checksum of " + readImageMd5
+ " but expecting " + expectedMd5);
}
this.setImageDigest(loader.getLoadedImageTxId(), readImageMd5); // set this fsimage's checksum
storage.setMostRecentCheckpointTxId(loader.getLoadedImageTxId());
return loader.getNeedToSave();
}
/**
* Return string representing the parent of the given path.
*/
String getParent(String path) {
return path.substring(0, path.lastIndexOf(Path.SEPARATOR));
}
byte[][] getParent(byte[][] path) {
byte[][] result = new byte[path.length - 1][];
for (int i = 0; i < result.length; i++) {
result[i] = new byte[path[i].length];
System.arraycopy(path[i], 0, result[i], 0, path[i].length);
}
return result;
}
/**
* Load the specified list of edit files into the image.
* @return the txid of the current transaction (next to be loaded
*/
protected long loadEdits(Iterable<EditLogInputStream> editStreams)
throws IOException {
long lastAppliedTxId = storage.getMostRecentCheckpointTxId();
int numLoaded = 0;
FSEditLogLoader loader = new FSEditLogLoader(namesystem);
// Load latest edits
for (EditLogInputStream editIn : editStreams) {
FLOG.info("Load Image: Reading edits: " + editIn + " last applied txid#: "
+ lastAppliedTxId);
numLoaded += loader.loadFSEdits(editIn, lastAppliedTxId);
lastAppliedTxId = loader.getLastAppliedTxId();
}
editLog.setLastWrittenTxId(lastAppliedTxId);
FLOG.info("Load Image: Number of edit transactions loaded: "
+ numLoaded + " last applied txid: " + lastAppliedTxId);
// update the counts
namesystem.dir.updateCountForINodeWithQuota();
return numLoaded;
}
// for snapshot
void saveFSImage(String dest, DataOutputStream fstream) throws IOException {
saveNamespaceContext.set(namesystem, editLog.getLastWrittenTxId());
FSImageFormat.Saver saver = new FSImageFormat.Saver(saveNamespaceContext);
FSImageCompression compression = FSImageCompression.createCompression(
namesystem.getConf(), false);
saver
.save(new FileOutputStream(new File(dest)), compression, fstream, dest);
}
/**
* Save the contents of the FS image to the file.
*/
void saveFSImage(SaveNamespaceContext context, ImageManager im, boolean forceUncompressed)
throws IOException {
long txid = context.getTxId();
OutputStream os = im.getCheckpointOutputStream(txid);
FSImageFormat.Saver saver = new FSImageFormat.Saver(context);
FSImageCompression compression = FSImageCompression.createCompression(conf, forceUncompressed);
saver.save(os, compression, null, im.toString());
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_SAVED_IMAGE, txid);
storage.setCheckpointImageDigest(txid, saver.getSavedDigest());
}
private class FSImageSaver implements Runnable {
private SaveNamespaceContext context;
private ImageManager im;
private boolean forceUncompressed;
FSImageSaver(SaveNamespaceContext ctx, ImageManager im, boolean forceUncompressed) {
this.context = ctx;
this.im = im;
this.forceUncompressed = forceUncompressed;
}
public String toString() {
return "FSImage saver for " + im.toString() + " for txid : "
+ context.getTxId();
}
public void run() {
try {
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVER_THREAD);
LOG.info(this.toString() + " -- starting");
saveFSImage(context, im, forceUncompressed);
im.setImageDisabled(false);
} catch (SaveNamespaceCancelledException ex) {
LOG.warn("FSImageSaver: - cancelling operation");
} catch (IOException ex) {
LOG.error("Unable to write image: " + this.toString(), ex);
context
.reportErrorOnStorageDirectory((im instanceof FileImageManager) ? ((FileJournalManager) im)
.getStorageDirectory() : null);
im.setImageDisabled(true);
}
}
}
/**
* Save the contents of the FS image
* and create empty edits.
*/
public void saveNamespace() throws IOException {
saveNamespace(false);
}
/**
* Save the contents of the FS image to a new image file in each of the
* current storage directories.
*/
public synchronized void saveNamespace(boolean forUncompressed)
throws IOException {
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVE_NAMESPACE);
if (editLog == null) {
throw new IOException("editLog must be initialized");
}
storage.attemptRestoreRemovedStorage();
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVE_NAMESPACE);
boolean editLogWasOpen = editLog.isOpen();
if (editLogWasOpen) {
editLog.endCurrentLogSegment(true);
}
long imageTxId = editLog.getLastWrittenTxId();
try {
// for testing only - we will wait until interruption comes
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_CREATING_SAVER_THREADS);
saveFSImageInAllDirs(imageTxId, forUncompressed);
storage.writeAll();
} finally {
if (editLogWasOpen) {
editLog.startLogSegment(imageTxId + 1, true);
// Take this opportunity to note the current transaction.
// Even if the namespace save was cancelled, this marker
// is only used to determine what transaction ID is required
// for startup. So, it doesn't hurt to update it unnecessarily.
storage.writeTransactionIdFileToStorage(imageTxId + 1, this);
}
saveNamespaceContext.clear();
}
}
protected synchronized void saveFSImageInAllDirs(long txid, boolean forceUncompressed)
throws IOException {
if (storage.getNumStorageDirs(NameNodeDirType.IMAGE) == 0) {
throw new IOException("No image directories available!");
}
saveNamespaceContext.set(namesystem, txid);
List<Thread> saveThreads = new ArrayList<Thread>();
// save images into current
for (ImageManager im : imageSet.getImageManagers()) {
FSImageSaver saver = new FSImageSaver(saveNamespaceContext, im,
forceUncompressed);
Thread saveThread = new Thread(saver, saver.toString());
saveThreads.add(saveThread);
saveThread.start();
}
waitForThreads(saveThreads);
saveThreads.clear();
storage.reportErrorsOnDirectories(saveNamespaceContext.getErrorSDs(), this);
// check if we have any image managers left
imageSet.checkImageManagers();
if (saveNamespaceContext.isCancelled()) {
deleteCheckpoint(saveNamespaceContext.getTxId());
saveNamespaceContext.checkCancelled();
}
// tell all image managers to store md5
imageSet.saveDigestAndRenameCheckpointImage(txid,
storage.getCheckpointImageDigest(txid));
storage.setMostRecentCheckpointTxId(txid);
// Since we now have a new checkpoint, we can clean up some
// old edit logs and checkpoints.
purgeOldStorage();
}
private void waitForThreads(List<Thread> threads) {
for (Thread thread : threads) {
while (thread.isAlive()) {
try {
thread.join();
} catch (InterruptedException iex) {
LOG.error("Caught exception while waiting for thread " +
thread.getName() + " to finish. Retrying join");
}
}
}
}
public void format() throws IOException {
storage.format();
LOG.info("Format non-file journal managers");
editLog.transitionNonFileJournals(storage, false,
Transition.FORMAT, null);
LOG.info("Format non-file image managers");
transitionNonFileImages(storage, false, Transition.FORMAT);
// take over as the writer
editLog.recoverUnclosedStreams();
saveFSImageInAllDirs(-1, false);
}
void transitionNonFileImages(StorageInfo nsInfo, boolean checkEmpty,
Transition transition)
throws IOException {
imageSet.transitionNonFileImages(storage, checkEmpty,
transition, null);
}
/**
* Get the list of non-file journal managers.
*/
List<JournalManager> getNonFileJournalManagers() {
return editLog.getNonFileJournalManagers();
}
/**
* Get the list of non-file image managers.
*/
List<ImageManager> getNonFileImageManagers() {
return imageSet.getNonFileImageManagers();
}
/**
* Check whether the storage directories and non-file journals exist.
* If running in interactive mode, will prompt the user for each
* directory to allow them to format anyway. Otherwise, returns
* false, unless 'force' is specified.
*
* @param interactive prompt the user when a dir exists
* @return true if formatting should proceed
* @throws IOException if some storage cannot be accessed
*/
boolean confirmFormat(boolean force, boolean interactive) throws IOException {
List<FormatConfirmable> confirms = Lists.newArrayList();
for (StorageDirectory sd : storage.dirIterable(null)) {
confirms.add(sd);
}
confirms.addAll(editLog.getFormatConfirmables());
return Storage.confirmFormat(confirms, force, interactive);
}
/**
* Deletes the checkpoint file in every storage directory,
* since the checkpoint was cancelled. Attepmts to remove
* image/md5/ckptimage files.
*/
void deleteCheckpoint(long txId) throws IOException {
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
// image file
File imageFile = NNStorage.getImageFile(sd, txId);
if (imageFile.delete())
LOG.info("Delete checkpoint: deleted: " + imageFile);
// md5 file
File imageFileMD5 = MD5FileUtils.getDigestFileForFile(imageFile);
if (imageFileMD5.delete())
LOG.info("Delete checkpoint: deleted: " + imageFileMD5);
// image ckpt file
File imageCkptFile = NNStorage.getCheckpointImageFile(sd, txId);
if (imageCkptFile.delete())
LOG.info("Delete checkpoint: deleted: " + imageCkptFile);
}
}
CheckpointSignature rollEditLog() throws IOException {
getEditLog().rollEditLog();
// clear up image manager states
imageSet.restoreImageManagers();
// Record this log segment ID in all of the storage directories, so
// we won't miss this log segment on a restart if the edits directories
// go missing.
storage.writeTransactionIdFileToStorage(getEditLog().getCurSegmentTxId(),
this);
return new CheckpointSignature(this);
}
/**
* End checkpoint.
* Validate the current storage info with the given signature.
*
* @param sig to validate the current storage info against
* @throws IOException if the checkpoint fields are inconsistent
*/
void rollFSImage(CheckpointSignature sig) throws IOException {
long start = System.nanoTime();
sig.validateStorageInfo(this.storage);
saveDigestAndRenameCheckpointImage(sig.mostRecentCheckpointTxId,
sig.imageDigest);
long rollTime = DFSUtil.getElapsedTimeMicroSeconds(start);
if (metrics != null) {
metrics.rollFsImageTime.inc(rollTime);
}
}
synchronized void checkpointUploadDone(long txid, MD5Hash checkpointImageMd5)
throws IOException {
storage.checkpointUploadDone(txid, checkpointImageMd5);
}
/**
* This is called by the 2NN after having downloaded an image, and by
* the NN after having received a new image from the 2NN. It
* renames the image from fsimage_N.ckpt to fsimage_N and also
* saves the related .md5 file into place.
*/
synchronized void saveDigestAndRenameCheckpointImage(
long txid, MD5Hash digest) throws IOException {
if (!digest.equals(storage.getCheckpointImageDigest(txid))) {
throw new IOException(
"Checkpoint image is corrupt: expecting an MD5 checksum of" +
digest + " but is " + storage.getCheckpointImageDigest(txid));
}
imageSet.saveDigestAndRenameCheckpointImage(txid, digest);
// So long as this is the newest image available,
// advertise it as such to other checkpointers
// from now on
storage.setMostRecentCheckpointTxId(txid);
}
/**
* Purge any files in the storage directories that are no longer
* necessary.
*/
public synchronized void purgeOldStorage() {
try {
archivalManager.purgeOldStorage();
} catch (Exception e) {
LOG.warn("Unable to purge old storage", e);
}
}
void reportErrorsOnImageManager(StorageDirectory badSD) {
if (imageSet != null) {
imageSet.reportErrorsOnImageManager(badSD);
}
}
void checkImageManagers() throws IOException {
if (imageSet != null) {
imageSet.checkImageManagers();
}
}
void updateImageMetrics() {
if (imageSet != null) {
imageSet.updateImageMetrics();
}
}
void close() throws IOException {
if(editLog != null)
editLog.close();
storage.unlockAll();
}
/**
* Return the name of the latest image file.
* @param type which image should be preferred.
*/
File getFsImageName(StorageLocationType type) {
return storage.getFsImageName(type, storage.getMostRecentCheckpointTxId());
}
/**
* Returns the txid of the last checkpoint
*/
public long getLastCheckpointTxId() {
return storage.getMostRecentCheckpointTxId();
}
/**
* Retrieve checkpoint dirs from configuration.
*
* @param conf the Configuration
* @param defaultValue a default value for the attribute, if null
* @return a Collection of URIs representing the values in
* dfs.namenode.checkpoint.dir configuration property
*/
static Collection<File> getCheckpointDirs(Configuration conf,
String defaultName) {
Collection<String> dirNames = conf.getStringCollection("fs.checkpoint.dir");
if (dirNames.size() == 0 && defaultName != null) {
dirNames.add(defaultName);
}
Collection<File> dirs = new ArrayList<File>(dirNames.size());
for (String name : dirNames) {
dirs.add(new File(name));
}
return dirs;
}
static Collection<File> getCheckpointEditsDirs(Configuration conf,
String defaultName) {
Collection<String> dirNames = conf
.getStringCollection("fs.checkpoint.edits.dir");
if (dirNames.size() == 0 && defaultName != null) {
dirNames.add(defaultName);
}
Collection<File> dirs = new ArrayList<File>(dirNames.size());
for (String name : dirNames) {
dirs.add(new File(name));
}
return dirs;
}
public int getLayoutVersion() {
return storage.getLayoutVersion();
}
public int getNamespaceID() {
return storage.getNamespaceID();
}
public void cancelSaveNamespace(String reason) {
saveNamespaceContext.cancel(reason);
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_CANCEL_REQUEST_RECEIVED);
}
public void clearCancelSaveNamespace() {
saveNamespaceContext.clear();
}
protected long getImageTxId() {
return saveNamespaceContext.getTxId();
}
public Iterator<StorageDirectory> dirIterator(StorageDirType dirType) {
return storage.dirIterator(dirType);
}
public Iterator<StorageDirectory> dirIterator() {
return storage.dirIterator();
}
static void rollForwardByApplyingLogs(
RemoteEditLogManifest manifest,
FSImage dstImage) throws IOException {
NNStorage dstStorage = dstImage.storage;
List<EditLogInputStream> editsStreams = new ArrayList<EditLogInputStream>();
for (RemoteEditLog log : manifest.getLogs()) {
if (log.inProgress())
break;
File f = dstStorage.findFinalizedEditsFile(
log.getStartTxId(), log.getEndTxId());
if (log.getStartTxId() > dstImage.getLastAppliedTxId()) {
editsStreams.add(new EditLogFileInputStream(f, log.getStartTxId(),
log.getEndTxId(), false));
}
}
dstImage.loadEdits(editsStreams);
}
/**
* Get a list of output streams for writing chekpoint images.
*/
public List<OutputStream> getCheckpointImageOutputStreams(long imageTxId)
throws IOException {
return imageSet.getCheckpointImageOutputStreams(imageTxId);
}
}
| UTF-8 | Java | 48,439 | java | FSImage.java | Java | [] | null | [] | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.FSConstants;
import org.apache.hadoop.hdfs.protocol.LayoutVersion;
import org.apache.hadoop.hdfs.protocol.LayoutVersion.Feature;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.Transition;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.common.Storage.FormatConfirmable;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirType;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.common.Storage.StorageState;
import org.apache.hadoop.hdfs.server.common.StorageInfo;
import org.apache.hadoop.hdfs.server.common.HdfsConstants.StartupOption;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeDirType;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.StorageLocationType;
import org.apache.hadoop.hdfs.server.namenode.ValidateNamespaceDirPolicy.NNStorageLocation;
import org.apache.hadoop.hdfs.server.namenode.metrics.NameNodeMetrics;
import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog;
import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest;
import org.apache.hadoop.hdfs.util.InjectionEvent;
import org.apache.hadoop.hdfs.util.MD5FileUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.util.FlushableLogger;
import org.apache.hadoop.util.InjectionEventI;
import org.apache.hadoop.util.InjectionHandler;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* FSImage handles checkpointing and logging of the namespace edits.
*
*/
public class FSImage {
static final Log LOG = LogFactory.getLog(FSImage.class.getName());
// immediate flush logger
private static final Log FLOG = FlushableLogger.getLogger(LOG);
NNStorage storage;
Configuration conf;
private NNStorageRetentionManager archivalManager;
private final SaveNamespaceContext saveNamespaceContext
= new SaveNamespaceContext();
protected FSNamesystem namesystem = null;
FSEditLog editLog = null;
ImageSet imageSet = null;
private boolean isUpgradeFinalized = false;
private NameNodeMetrics metrics = NameNode.getNameNodeMetrics();
// intermediate buffer size for image saving and loading
public static int LOAD_SAVE_BUFFER_SIZE = 4 * 1024 * 1024; // 4MB
// chunk size for copying out or into the intermediate buffer
public static int LOAD_SAVE_CHUNK_SIZE = 512 * 1024; // 512KB
/**
* Constructor
* @param conf Configuration
*/
FSImage(Configuration conf) throws IOException {
storage = new NNStorage(new StorageInfo());
this.editLog = new FSEditLog(conf, this, storage,
NNStorageConfiguration.getNamespaceDirs(conf),
NNStorageConfiguration.getNamespaceEditsDirs(conf), null);
this.imageSet = new ImageSet(this, null, null, metrics);
setFSNamesystem(null);
this.conf = conf;
archivalManager = new NNStorageRetentionManager(conf, storage, editLog);
}
/**
*/
FSImage(Configuration conf, Collection<URI> fsDirs,
Collection<URI> fsEditsDirs, Map<URI, NNStorageLocation> locationMap)
throws IOException {
this.conf = conf;
storage = new NNStorage(conf, fsDirs, fsEditsDirs, locationMap);
this.editLog = new FSEditLog(conf, this, storage, fsDirs, fsEditsDirs,
locationMap);
this.imageSet = new ImageSet(this, fsDirs, fsEditsDirs, metrics);
archivalManager = new NNStorageRetentionManager(conf, storage, editLog);
}
public boolean failOnTxIdMismatch() {
if (namesystem == null) {
return true;
} else {
return namesystem.failOnTxIdMismatch();
}
}
protected FSNamesystem getFSNamesystem() {
return namesystem;
}
protected void setFSNamesystem(FSNamesystem ns) {
namesystem = ns;
}
public long getLastAppliedTxId() {
return editLog.getLastWrittenTxId();
}
List<StorageDirectory> getRemovedStorageDirs() {
return storage.getRemovedStorageDirs();
}
/**
* Get the MD5 digest of the current image
* @return the MD5 digest of the current image
*/
MD5Hash getImageDigest(long txid) throws IOException {
return storage.getCheckpointImageDigest(txid);
}
void setImageDigest(long txid, MD5Hash imageDigest) throws IOException {
this.storage.setCheckpointImageDigest(txid, imageDigest);
}
private void throwIOException(String msg) throws IOException {
LOG.error(msg);
throw new IOException(msg);
}
private void updateRemoteStates(
Map<ImageManager, RemoteStorageState> remoteImageStates,
Map<JournalManager, RemoteStorageState> remoteJournalStates,
List<ImageManager> nonFileImageManagers,
List<JournalManager> nonFileJournalManagers)
throws IOException {
// / analyze non file storage location
// List non-file storage
FLOG.info("Startup: non-file image managers:");
for (ImageManager im : nonFileImageManagers) {
RemoteStorageState st = im.analyzeImageStorage();
FLOG.info("-> Image Manager: " + im + " state: " + st.getStorageState());
if (st.getStorageState() == StorageState.INCONSISTENT) {
throwIOException("Image manager has inconsistent state: " + im
+ ", state: " + st.getStorageState());
}
remoteImageStates.put(im, st);
}
FLOG.info("Startup: non-file journal managers:");
for (JournalManager jm : nonFileJournalManagers) {
RemoteStorageState st = jm.analyzeJournalStorage();
FLOG.info("-> Journal Manager: " + jm + " state: " + st.getStorageState());
if (st.getStorageState() == StorageState.INCONSISTENT) {
throwIOException("Journal manager has inconsistent state: " + jm
+ ", state: " + st.getStorageState());
}
remoteJournalStates.put(jm, st);
}
}
/**
* Analyze storage directories.
* Recover from previous transitions if required.
* Perform fs state transition if necessary depending on the namespace info.
* Read storage info.
*
* @throws IOException
* @return true if the image needs to be saved or false otherwise
*/
public boolean recoverTransitionRead(StartupOption startOpt)
throws IOException {
FLOG.info("Startup: recovering namenode storage");
assert startOpt != StartupOption.FORMAT :
"NameNode formatting should be performed before reading the image";
Collection<File> imageDirs = storage.getImageDirectories();
// none of the data dirs exist
if(imageDirs.size() == 0 && startOpt != StartupOption.IMPORT)
throw new IOException(
"All specified directories are not accessible or do not exist.");
editLog.checkJournals();
storage.setUpgradeManager(namesystem.upgradeManager);
Map<ImageManager, RemoteStorageState> remoteImageStates = Maps.newHashMap();
Map<JournalManager, RemoteStorageState> remoteJournalStates = Maps.newHashMap();
List<ImageManager> nonFileImageManagers = getNonFileImageManagers();
List<JournalManager> nonFileJournalManagers = getNonFileJournalManagers();
updateRemoteStates(remoteImageStates, remoteJournalStates,
nonFileImageManagers, nonFileJournalManagers);
// number of non-file storage locations
int nonFileStorageLocations = nonFileImageManagers.size()
+ nonFileJournalManagers.size();
FLOG.info("Startup: checking storage directory state.");
// 1. For each data directory calculate its state and
// check whether all is consistent before transitioning.
Map<StorageDirectory, StorageState> dataDirStates =
new HashMap<StorageDirectory, StorageState>();
boolean isFormatted = recoverStorageDirs(startOpt, dataDirStates);
// Recover the non-file storage locations.
editLog.transitionNonFileJournals(null, false,
Transition.RECOVER, startOpt);
imageSet.transitionNonFileImages(null, false, Transition.RECOVER,
startOpt);
if (!isFormatted && startOpt != StartupOption.ROLLBACK
&& startOpt != StartupOption.IMPORT) {
for(Entry<StorageDirectory, StorageState> e : dataDirStates.entrySet()) {
LOG.info("State : " + e.getKey().getCurrentDir() + " state: " +e.getValue());
}
throw new IOException("NameNode is not formatted." + dataDirStates);
}
int layoutVersion = storage.getLayoutVersion();
if (layoutVersion < Storage.LAST_PRE_UPGRADE_LAYOUT_VERSION) {
NNStorage.checkVersionUpgradable(storage.getLayoutVersion());
}
if (startOpt != StartupOption.UPGRADE
&& layoutVersion < Storage.LAST_PRE_UPGRADE_LAYOUT_VERSION
&& layoutVersion != FSConstants.LAYOUT_VERSION) {
throw new IOException(
"\nFile system image contains an old layout version "
+ storage.getLayoutVersion() + ".\nAn upgrade to version "
+ FSConstants.LAYOUT_VERSION + " is required.\n"
+ "Please restart NameNode with -upgrade option.");
}
editLog.updateNamespaceInfo(storage);
// check whether distributed upgrade is required and/or should be continued
storage.verifyDistributedUpgradeProgress(startOpt);
FLOG.info("Startup: formatting unformatted directories.");
// 2. Format unformatted dirs.
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
StorageState curState = dataDirStates.get(sd);
switch(curState) {
case NON_EXISTENT:
throw new IOException(StorageState.NON_EXISTENT +
" state cannot be here");
case NOT_FORMATTED:
LOG.info("Storage directory " + sd.getRoot() + " is not formatted.");
if (!sd.isEmpty()) {
LOG.error("Storage directory " + sd.getRoot()
+ " is not empty, and will not be formatted! Exiting.");
throw new IOException(
"Storage directory " + sd.getRoot() + " is not empty!");
}
LOG.info("Formatting ...");
sd.clearDirectory(); // create empty currrent dir
break;
default:
break;
}
}
// check non-file images
for (Entry<ImageManager, RemoteStorageState> e : remoteImageStates
.entrySet()) {
checkAllowedNonFileState(e.getValue().getStorageState(), e.getKey());
}
// check non-file journals
for (Entry<JournalManager, RemoteStorageState> e : remoteJournalStates
.entrySet()) {
checkAllowedNonFileState(e.getValue().getStorageState(), e.getKey());
}
FLOG.info("Startup: Transitions.");
// 3. Do transitions
switch(startOpt) {
case UPGRADE:
doUpgrade();
return false; // upgrade saved image already
case IMPORT:
doImportCheckpoint();
if (nonFileStorageLocations > 0) {
throwIOException("Import not supported for non-file storage");
}
return false; // import checkpoint saved image already
case ROLLBACK:
doRollback(remoteImageStates, remoteJournalStates);
// Update the states since the remote states have changed after rollback.
updateRemoteStates(remoteImageStates, remoteJournalStates,
nonFileImageManagers, nonFileJournalManagers);
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_ROLLBACK_DONE);
break;
case REGULAR:
// just load the image
}
if (inUpgradeStatus()) {
namesystem.setUpgradeStartTime(FSNamesystem.now());
}
// final consistency check for non-file images and journals
// read version file first
FSImageStorageInspector inspector = storage.readAndInspectDirs();
FLOG.info("Startup: starting with storage info: " + storage.toColonSeparatedString());
// format unformatted journals and images
// check if the formatted ones are consistent with local storage
for (Entry<ImageManager, RemoteStorageState> e : remoteImageStates
.entrySet()) {
if (e.getValue().getStorageState() != StorageState.NORMAL) {
LOG.info("Formatting remote image: " + e.getKey());
e.getKey().transitionImage(storage, Transition.FORMAT, null);
} else {
checkConsistency(e.getValue().getStorageInfo(), storage, true, e.getKey());
}
}
for (Entry<JournalManager, RemoteStorageState> e : remoteJournalStates
.entrySet()) {
if (e.getValue().getStorageState() != StorageState.NORMAL) {
LOG.info("Formatting remote journal: " + e.getKey());
e.getKey().transitionJournal(storage, Transition.FORMAT, null);
} else {
checkConsistency(e.getValue().getStorageInfo(), storage, true, e.getKey());
}
}
// load the image
return loadFSImage(inspector);
}
/**
* Check if the remote image/journal storage info is the same as ours
*/
private void checkConsistency(StorageInfo remote, StorageInfo local,
boolean image, Object name) throws IOException {
if (!remote.equals(local)) {
throwIOException("Remote " + (image ? "image" : "edits")
+ " storage is different than local. Local: ("
+ local.toColonSeparatedString() + "), remote: " + name.toString()
+ " (" + remote.toColonSeparatedString() + ")");
}
}
/**
* Check if remote image/journal storage is in allowed state.
*/
private void checkAllowedNonFileState(StorageState curState, Object name)
throws IOException {
switch (curState) {
case NON_EXISTENT:
case NOT_FORMATTED:
case NORMAL:
break;
default:
throwIOException("ImageManager bad state: " + curState + " for: "
+ name.toString());
}
}
/**
* @return true if Nn is under upgrade.
*/
private boolean inUpgradeStatus() {
for (Iterator <StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
File preDir = sd.getPreviousDir();
if (preDir.exists()) {
return true;
}
}
return false;
}
/**
* For each storage directory, performs recovery of incomplete transitions
* (eg. upgrade, rollback, checkpoint) and inserts the directory's storage
* state into the dataDirStates map.
* @param dataDirStates output of storage directory states
* @return true if there is at least one valid formatted storage directory
*/
private boolean recoverStorageDirs(StartupOption startOpt,
Map<StorageDirectory, StorageState> dataDirStates) throws IOException {
boolean isFormatted = false;
for (Iterator<StorageDirectory> it =
storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
StorageState curState;
try {
curState = sd.analyzeStorage(startOpt);
isFormatted |= NNStorage.recoverDirectory(sd, startOpt, curState, true);
} catch (IOException ioe) {
sd.unlock();
throw ioe;
}
dataDirStates.put(sd,curState);
}
return isFormatted;
}
private void doUpgrade() throws IOException {
namesystem.setUpgradeStartTime(FSNamesystem.now());
if(storage.getDistributedUpgradeState()) {
// only distributed upgrade need to continue
// don't do version upgrade
FSImageStorageInspector inspector = storage.readAndInspectDirs();
this.loadFSImage(inspector);
storage.initializeDistributedUpgrade();
return;
}
// Upgrade is allowed only if there are
// no previous fs states in any of the directories
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
if (sd.getPreviousDir().exists())
throw new InconsistentFSStateException(sd.getRoot(),
"previous fs state should not exist during upgrade. "
+ "Finalize or rollback first.");
}
FSImageStorageInspector inspector = storage.readAndInspectDirs();
// load the latest image
this.loadFSImage(inspector);
// clear the digest for the loaded image, it might change during upgrade
this.storage.clearCheckpointImageDigest(storage
.getMostRecentCheckpointTxId());
// Do upgrade for each directory
long oldCTime = storage.getCTime();
this.storage.cTime = FSNamesystem.now(); // generate new cTime for the state
int oldLV = storage.getLayoutVersion();
this.storage.layoutVersion = FSConstants.LAYOUT_VERSION;
assert !editLog.isOpen() : "Edits log must not be open.";
List<StorageDirectory> errorSDs =
Collections.synchronizedList(new ArrayList<StorageDirectory>());
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
LOG.info("Starting upgrade of image directory " + sd.getRoot()
+ ".\n old LV = " + oldLV
+ "; old CTime = " + oldCTime
+ ".\n new LV = " + storage.getLayoutVersion()
+ "; new CTime = " + storage.getCTime());
try {
Storage.upgradeDirectory(sd);
} catch (Exception e) {
LOG.error("Failed to move aside pre-upgrade storage " +
"in image directory " + sd.getRoot(), e);
errorSDs.add(sd);
continue;
}
}
// Upgrade non-file directories.
imageSet.transitionNonFileImages(storage, false, Transition.UPGRADE,
null);
editLog.transitionNonFileJournals(storage, false,
Transition.UPGRADE, null);
storage.reportErrorsOnDirectories(errorSDs, this);
errorSDs.clear();
InjectionHandler
.processEventIO(InjectionEvent.FSIMAGE_UPGRADE_BEFORE_SAVE_IMAGE);
saveFSImageInAllDirs(editLog.getLastWrittenTxId(), false);
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
try {
Storage.completeUpgrade(sd);
} catch (IOException ioe) {
LOG.error("Unable to rename temp to previous for " + sd.getRoot(), ioe);
errorSDs.add(sd);
continue;
}
isUpgradeFinalized = false;
LOG.info("Upgrade of " + sd.getRoot() + " is complete.");
}
// Complete the upgrade for non-file directories.
imageSet.transitionNonFileImages(storage, false,
Transition.COMPLETE_UPGRADE, null);
editLog.transitionNonFileJournals(storage, false,
Transition.COMPLETE_UPGRADE, null);
storage.reportErrorsOnDirectories(errorSDs, this);
storage.initializeDistributedUpgrade();
}
private void doRollback(
Map<ImageManager, RemoteStorageState> remoteImageStates,
Map<JournalManager, RemoteStorageState> remoteJournalStates)
throws IOException {
// Rollback is allowed only if there is
// a previous fs states in at least one of the storage directories.
// Directories that don't have previous state do not rollback
boolean canRollback = false;
FSImage prevState = new FSImage(conf);
prevState.storage.layoutVersion = FSConstants.LAYOUT_VERSION;
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
canRollback = NNStorage.canRollBack(sd, prevState.storage);
}
// Check non-file managers.
for (RemoteStorageState s : remoteImageStates.values()) {
StorageState state = s.getStorageState();
if (state == StorageState.UPGRADE_DONE) {
canRollback = true;
}
}
// Check non-file managers.
for (RemoteStorageState s : remoteJournalStates.values()) {
StorageState state = s.getStorageState();
if (state == StorageState.UPGRADE_DONE) {
canRollback = true;
}
}
if (!canRollback)
throw new IOException("Cannot rollback. None of the storage "
+ "directories contain previous fs state.");
// Now that we know all directories are going to be consistent
// Do rollback for each directory containing previous state
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
NNStorage.doRollBack(sd, prevState.storage);
}
// Rollback non-file storage locations.
editLog.transitionNonFileJournals(storage, false, Transition.ROLLBACK,
null);
imageSet.transitionNonFileImages(storage, false, Transition.ROLLBACK, null);
isUpgradeFinalized = true;
// check whether name-node can start in regular mode
storage.verifyDistributedUpgradeProgress(StartupOption.REGULAR);
}
private void doFinalize(StorageDirectory sd) throws IOException {
NNStorage.finalize(sd, storage.getLayoutVersion(), storage.getCTime());
isUpgradeFinalized = true;
}
/**
* Load image from a checkpoint directory and save it into the current one.
* @throws IOException
*/
/**
* Load image from a checkpoint directory and save it into the current one.
* @param target the NameSystem to import into
* @throws IOException
*/
void doImportCheckpoint() throws IOException {
Collection<URI> checkpointDirs =
NNStorageConfiguration.getCheckpointDirs(conf, null);
Collection<URI> checkpointEditsDirs =
NNStorageConfiguration.getCheckpointEditsDirs(conf, null);
if (checkpointDirs == null || checkpointDirs.isEmpty()) {
throw new IOException("Cannot import image from a checkpoint. "
+ "\"dfs.namenode.checkpoint.dir\" is not set." );
}
if (checkpointEditsDirs == null || checkpointEditsDirs.isEmpty()) {
throw new IOException("Cannot import image from a checkpoint. "
+ "\"dfs.namenode.checkpoint.dir\" is not set." );
}
// replace real image with the checkpoint image
FSImage realImage = namesystem.getFSImage();
assert realImage == this;
FSImage ckptImage = new FSImage(conf,
checkpointDirs, checkpointEditsDirs, null);
ckptImage.setFSNamesystem(namesystem);
namesystem.dir.fsImage = ckptImage;
// load from the checkpoint dirs
try {
ckptImage.recoverTransitionRead(StartupOption.REGULAR);
} finally {
ckptImage.close();
}
// return back the real image
realImage.storage.setStorageInfo(ckptImage.storage);
realImage.getEditLog().setLastWrittenTxId(ckptImage.getEditLog().getLastWrittenTxId() + 1);
namesystem.dir.fsImage = realImage;
// and save it but keep the same checkpointTime
// parameters
saveNamespace();
}
public void finalizeUpgrade() throws IOException {
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
doFinalize(it.next());
}
// finalize non-file storage locations.
editLog.transitionNonFileJournals(null, false, Transition.FINALIZE, null);
imageSet.transitionNonFileImages(null, false, Transition.FINALIZE, null);
isUpgradeFinalized = true;
namesystem.setUpgradeStartTime(0);
}
boolean isUpgradeFinalized() {
return isUpgradeFinalized;
}
public FSEditLog getEditLog() {
return editLog;
}
public List<ImageManager> getImageManagers() {
return imageSet.getImageManagers();
}
void openEditLog() throws IOException {
if (editLog == null) {
throw new IOException("EditLog must be initialized");
}
if (!editLog.isOpen()) {
editLog.open();
storage
.writeTransactionIdFileToStorage(editLog.getCurSegmentTxId(), this);
}
};
/**
* Choose latest image from one of the directories,
* load it and merge with the edits from that directory.
*
* @return whether the image should be saved
* @throws IOException
*/
boolean loadFSImage(FSImageStorageInspector inspector) throws IOException {
ImageInputStream iis = null;
isUpgradeFinalized = inspector.isUpgradeFinalized();
FSImageStorageInspector.FSImageFile imageFile = inspector.getLatestImage();
boolean needToSave = inspector.needToSave();
FSImageStorageInspector.FSImageFile nonFileImage = imageSet
.getLatestImageFromNonFileImageManagers();
boolean loadingNonFileImage = false;
// image stored in non-file storage is newer, we obtain the input stream here
// recover unclosed streams, so the journals storing image are initialized
editLog.recoverUnclosedStreams();
long imageCheckpointTxId;
if (nonFileImage != null
&& (nonFileImage.getCheckpointTxId() > imageFile.getCheckpointTxId() || conf
.getBoolean("dfs.force.remote.image", false))) {
// this will contain the digest
LOG.info("Non-file image is newer/forced.");
iis = nonFileImage.getImageManager().getImageInputStream(
nonFileImage.getCheckpointTxId());
imageCheckpointTxId = nonFileImage.getCheckpointTxId();
loadingNonFileImage = true;
} else {
// the md5 digest will be set later
iis = new ImageInputStream(imageFile.getCheckpointTxId(),
new FileInputStream(imageFile.getFile()), null, imageFile.getFile()
.getAbsolutePath(), imageFile.getFile().length());
imageCheckpointTxId = imageFile.getCheckpointTxId();
loadingNonFileImage = false;
}
Collection<EditLogInputStream> editStreams = new ArrayList<EditLogInputStream>();
// if the recovery failed for any journals, just abort the startup.
if (editLog.getNumberOfAvailableJournals() != editLog.getNumberOfJournals()) {
LOG.fatal("Unable to recover unclosed segments for all journals.");
throw new IOException(
"Unable to recover unclosed segments for all journals.");
}
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
FLOG.info("Load Image: checkpoint txid: " + imageCheckpointTxId
+ " max seen: " + inspector.getMaxSeenTxId());
needToSave |= editLog.selectInputStreams(editStreams,
imageCheckpointTxId + 1, inspector.getMaxSeenTxId(),
editLog.getNumberOfJournals());
} else {
FSImagePreTransactionalStorageInspector.getEditLogStreams(editStreams,
storage, conf);
}
FLOG.info("Load Image: planning to load image :\n" + iis);
for (EditLogInputStream l : editStreams) {
FLOG.info("Load Image: planning to load edit stream: " + l);
}
try {
if (!loadingNonFileImage) {
StorageDirectory sdForProperties = imageFile.sd;
sdForProperties.read();
if (LayoutVersion.supports(Feature.TXID_BASED_LAYOUT, getLayoutVersion())) {
// For txid-based layout, we should have a .md5 file
// next to the image file
loadFSImage(iis, imageFile.getFile());
} else if (LayoutVersion.supports(Feature.FSIMAGE_CHECKSUM,
getLayoutVersion())) {
// In 0.22, we have the checksum stored in the VERSION file.
String md5 = storage
.getDeprecatedProperty(NNStorage.MESSAGE_DIGEST_PROPERTY);
if (md5 == null) {
throw new InconsistentFSStateException(sdForProperties.getRoot(),
"Message digest property " + NNStorage.MESSAGE_DIGEST_PROPERTY
+ " not set for storage directory "
+ sdForProperties.getRoot());
}
iis.setImageDigest(new MD5Hash(md5));
loadFSImage(iis);
} else {
// We don't have any record of the md5sum
loadFSImage(iis);
}
} else {
if (!LayoutVersion.supports(Feature.TXID_BASED_LAYOUT,
getLayoutVersion())) {
throwIOException("Inconsistency: Loading remote image, but the layout does not support txids: "
+ getLayoutVersion());
}
// loading non-file
loadFSImage(iis);
}
} catch (IOException ioe) {
FSEditLog.closeAllStreams(editStreams);
throw new IOException("Failed to load image from " +
(loadingNonFileImage ? nonFileImage : imageFile), ioe);
}
editLog.setLastWrittenTxId(storage.getMostRecentCheckpointTxId());
long numLoaded = loadEdits(editStreams);
needToSave |= needsResaveBasedOnStaleCheckpoint(loadingNonFileImage ? null
: imageFile.getFile(), numLoaded);
return needToSave;
}
/**
* @param imageFile
* the image file that was loaded (if remote location was loaded that
* this is null)
* @param numEditsLoaded
* the number of edits loaded from edits logs
* @return true if the NameNode should automatically save the namespace when
* it is started, due to the latest checkpoint being too old.
*/
private boolean needsResaveBasedOnStaleCheckpoint(File imageFile,
long numEditsLoaded) {
final long checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
final long checkpointTxnCount = NNStorageConfiguration.getCheckpointTxnCount(conf);
long checkpointAge = System.currentTimeMillis()
- (imageFile == null ? Long.MAX_VALUE : imageFile.lastModified());
boolean needToSave = (checkpointAge > checkpointPeriod * 1000)
|| (numEditsLoaded > checkpointTxnCount);
LOG.info("Load Image: Need to save based on stale checkpoint: "
+ needToSave);
return needToSave;
}
/**
* Load the image namespace from the given image file, verifying it against
* the MD5 sum stored in its associated .md5 file.
*/
protected void loadFSImage(ImageInputStream iis, File imageFile) throws IOException {
MD5Hash expectedMD5 = MD5FileUtils.readStoredMd5ForFile(imageFile);
if (expectedMD5 == null) {
throw new IOException("No MD5 file found corresponding to image file "
+ imageFile);
}
iis.setImageDigest(expectedMD5);
loadFSImage(iis);
}
boolean loadFSImage(ImageInputStream iis) throws IOException {
assert iis != null : "input stream is null";
FSImageFormat.Loader loader = new FSImageFormat.Loader(
namesystem.getConf(), namesystem, storage);
loader.load(iis, null);
saveNamespaceContext.set(null, loader.getLoadedImageTxId());
// Check that the image digest we loaded matches up with what
// we expected
MD5Hash readImageMd5 = loader.getLoadedImageMd5();
MD5Hash expectedMd5 = iis.getDigest();
if (expectedMd5 != null && !expectedMd5.equals(readImageMd5)) {
throw new IOException("Image file " + iis
+ " is corrupt with MD5 checksum of " + readImageMd5
+ " but expecting " + expectedMd5);
}
this.setImageDigest(loader.getLoadedImageTxId(), readImageMd5); // set this fsimage's checksum
storage.setMostRecentCheckpointTxId(loader.getLoadedImageTxId());
return loader.getNeedToSave();
}
/**
* Return string representing the parent of the given path.
*/
String getParent(String path) {
return path.substring(0, path.lastIndexOf(Path.SEPARATOR));
}
byte[][] getParent(byte[][] path) {
byte[][] result = new byte[path.length - 1][];
for (int i = 0; i < result.length; i++) {
result[i] = new byte[path[i].length];
System.arraycopy(path[i], 0, result[i], 0, path[i].length);
}
return result;
}
/**
* Load the specified list of edit files into the image.
* @return the txid of the current transaction (next to be loaded
*/
protected long loadEdits(Iterable<EditLogInputStream> editStreams)
throws IOException {
long lastAppliedTxId = storage.getMostRecentCheckpointTxId();
int numLoaded = 0;
FSEditLogLoader loader = new FSEditLogLoader(namesystem);
// Load latest edits
for (EditLogInputStream editIn : editStreams) {
FLOG.info("Load Image: Reading edits: " + editIn + " last applied txid#: "
+ lastAppliedTxId);
numLoaded += loader.loadFSEdits(editIn, lastAppliedTxId);
lastAppliedTxId = loader.getLastAppliedTxId();
}
editLog.setLastWrittenTxId(lastAppliedTxId);
FLOG.info("Load Image: Number of edit transactions loaded: "
+ numLoaded + " last applied txid: " + lastAppliedTxId);
// update the counts
namesystem.dir.updateCountForINodeWithQuota();
return numLoaded;
}
// for snapshot
void saveFSImage(String dest, DataOutputStream fstream) throws IOException {
saveNamespaceContext.set(namesystem, editLog.getLastWrittenTxId());
FSImageFormat.Saver saver = new FSImageFormat.Saver(saveNamespaceContext);
FSImageCompression compression = FSImageCompression.createCompression(
namesystem.getConf(), false);
saver
.save(new FileOutputStream(new File(dest)), compression, fstream, dest);
}
/**
* Save the contents of the FS image to the file.
*/
void saveFSImage(SaveNamespaceContext context, ImageManager im, boolean forceUncompressed)
throws IOException {
long txid = context.getTxId();
OutputStream os = im.getCheckpointOutputStream(txid);
FSImageFormat.Saver saver = new FSImageFormat.Saver(context);
FSImageCompression compression = FSImageCompression.createCompression(conf, forceUncompressed);
saver.save(os, compression, null, im.toString());
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_SAVED_IMAGE, txid);
storage.setCheckpointImageDigest(txid, saver.getSavedDigest());
}
private class FSImageSaver implements Runnable {
private SaveNamespaceContext context;
private ImageManager im;
private boolean forceUncompressed;
FSImageSaver(SaveNamespaceContext ctx, ImageManager im, boolean forceUncompressed) {
this.context = ctx;
this.im = im;
this.forceUncompressed = forceUncompressed;
}
public String toString() {
return "FSImage saver for " + im.toString() + " for txid : "
+ context.getTxId();
}
public void run() {
try {
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVER_THREAD);
LOG.info(this.toString() + " -- starting");
saveFSImage(context, im, forceUncompressed);
im.setImageDisabled(false);
} catch (SaveNamespaceCancelledException ex) {
LOG.warn("FSImageSaver: - cancelling operation");
} catch (IOException ex) {
LOG.error("Unable to write image: " + this.toString(), ex);
context
.reportErrorOnStorageDirectory((im instanceof FileImageManager) ? ((FileJournalManager) im)
.getStorageDirectory() : null);
im.setImageDisabled(true);
}
}
}
/**
* Save the contents of the FS image
* and create empty edits.
*/
public void saveNamespace() throws IOException {
saveNamespace(false);
}
/**
* Save the contents of the FS image to a new image file in each of the
* current storage directories.
*/
public synchronized void saveNamespace(boolean forUncompressed)
throws IOException {
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVE_NAMESPACE);
if (editLog == null) {
throw new IOException("editLog must be initialized");
}
storage.attemptRestoreRemovedStorage();
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_STARTING_SAVE_NAMESPACE);
boolean editLogWasOpen = editLog.isOpen();
if (editLogWasOpen) {
editLog.endCurrentLogSegment(true);
}
long imageTxId = editLog.getLastWrittenTxId();
try {
// for testing only - we will wait until interruption comes
InjectionHandler
.processEvent(InjectionEvent.FSIMAGE_CREATING_SAVER_THREADS);
saveFSImageInAllDirs(imageTxId, forUncompressed);
storage.writeAll();
} finally {
if (editLogWasOpen) {
editLog.startLogSegment(imageTxId + 1, true);
// Take this opportunity to note the current transaction.
// Even if the namespace save was cancelled, this marker
// is only used to determine what transaction ID is required
// for startup. So, it doesn't hurt to update it unnecessarily.
storage.writeTransactionIdFileToStorage(imageTxId + 1, this);
}
saveNamespaceContext.clear();
}
}
protected synchronized void saveFSImageInAllDirs(long txid, boolean forceUncompressed)
throws IOException {
if (storage.getNumStorageDirs(NameNodeDirType.IMAGE) == 0) {
throw new IOException("No image directories available!");
}
saveNamespaceContext.set(namesystem, txid);
List<Thread> saveThreads = new ArrayList<Thread>();
// save images into current
for (ImageManager im : imageSet.getImageManagers()) {
FSImageSaver saver = new FSImageSaver(saveNamespaceContext, im,
forceUncompressed);
Thread saveThread = new Thread(saver, saver.toString());
saveThreads.add(saveThread);
saveThread.start();
}
waitForThreads(saveThreads);
saveThreads.clear();
storage.reportErrorsOnDirectories(saveNamespaceContext.getErrorSDs(), this);
// check if we have any image managers left
imageSet.checkImageManagers();
if (saveNamespaceContext.isCancelled()) {
deleteCheckpoint(saveNamespaceContext.getTxId());
saveNamespaceContext.checkCancelled();
}
// tell all image managers to store md5
imageSet.saveDigestAndRenameCheckpointImage(txid,
storage.getCheckpointImageDigest(txid));
storage.setMostRecentCheckpointTxId(txid);
// Since we now have a new checkpoint, we can clean up some
// old edit logs and checkpoints.
purgeOldStorage();
}
private void waitForThreads(List<Thread> threads) {
for (Thread thread : threads) {
while (thread.isAlive()) {
try {
thread.join();
} catch (InterruptedException iex) {
LOG.error("Caught exception while waiting for thread " +
thread.getName() + " to finish. Retrying join");
}
}
}
}
public void format() throws IOException {
storage.format();
LOG.info("Format non-file journal managers");
editLog.transitionNonFileJournals(storage, false,
Transition.FORMAT, null);
LOG.info("Format non-file image managers");
transitionNonFileImages(storage, false, Transition.FORMAT);
// take over as the writer
editLog.recoverUnclosedStreams();
saveFSImageInAllDirs(-1, false);
}
void transitionNonFileImages(StorageInfo nsInfo, boolean checkEmpty,
Transition transition)
throws IOException {
imageSet.transitionNonFileImages(storage, checkEmpty,
transition, null);
}
/**
* Get the list of non-file journal managers.
*/
List<JournalManager> getNonFileJournalManagers() {
return editLog.getNonFileJournalManagers();
}
/**
* Get the list of non-file image managers.
*/
List<ImageManager> getNonFileImageManagers() {
return imageSet.getNonFileImageManagers();
}
/**
* Check whether the storage directories and non-file journals exist.
* If running in interactive mode, will prompt the user for each
* directory to allow them to format anyway. Otherwise, returns
* false, unless 'force' is specified.
*
* @param interactive prompt the user when a dir exists
* @return true if formatting should proceed
* @throws IOException if some storage cannot be accessed
*/
boolean confirmFormat(boolean force, boolean interactive) throws IOException {
List<FormatConfirmable> confirms = Lists.newArrayList();
for (StorageDirectory sd : storage.dirIterable(null)) {
confirms.add(sd);
}
confirms.addAll(editLog.getFormatConfirmables());
return Storage.confirmFormat(confirms, force, interactive);
}
/**
* Deletes the checkpoint file in every storage directory,
* since the checkpoint was cancelled. Attepmts to remove
* image/md5/ckptimage files.
*/
void deleteCheckpoint(long txId) throws IOException {
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
// image file
File imageFile = NNStorage.getImageFile(sd, txId);
if (imageFile.delete())
LOG.info("Delete checkpoint: deleted: " + imageFile);
// md5 file
File imageFileMD5 = MD5FileUtils.getDigestFileForFile(imageFile);
if (imageFileMD5.delete())
LOG.info("Delete checkpoint: deleted: " + imageFileMD5);
// image ckpt file
File imageCkptFile = NNStorage.getCheckpointImageFile(sd, txId);
if (imageCkptFile.delete())
LOG.info("Delete checkpoint: deleted: " + imageCkptFile);
}
}
CheckpointSignature rollEditLog() throws IOException {
getEditLog().rollEditLog();
// clear up image manager states
imageSet.restoreImageManagers();
// Record this log segment ID in all of the storage directories, so
// we won't miss this log segment on a restart if the edits directories
// go missing.
storage.writeTransactionIdFileToStorage(getEditLog().getCurSegmentTxId(),
this);
return new CheckpointSignature(this);
}
/**
* End checkpoint.
* Validate the current storage info with the given signature.
*
* @param sig to validate the current storage info against
* @throws IOException if the checkpoint fields are inconsistent
*/
void rollFSImage(CheckpointSignature sig) throws IOException {
long start = System.nanoTime();
sig.validateStorageInfo(this.storage);
saveDigestAndRenameCheckpointImage(sig.mostRecentCheckpointTxId,
sig.imageDigest);
long rollTime = DFSUtil.getElapsedTimeMicroSeconds(start);
if (metrics != null) {
metrics.rollFsImageTime.inc(rollTime);
}
}
synchronized void checkpointUploadDone(long txid, MD5Hash checkpointImageMd5)
throws IOException {
storage.checkpointUploadDone(txid, checkpointImageMd5);
}
/**
* This is called by the 2NN after having downloaded an image, and by
* the NN after having received a new image from the 2NN. It
* renames the image from fsimage_N.ckpt to fsimage_N and also
* saves the related .md5 file into place.
*/
synchronized void saveDigestAndRenameCheckpointImage(
long txid, MD5Hash digest) throws IOException {
if (!digest.equals(storage.getCheckpointImageDigest(txid))) {
throw new IOException(
"Checkpoint image is corrupt: expecting an MD5 checksum of" +
digest + " but is " + storage.getCheckpointImageDigest(txid));
}
imageSet.saveDigestAndRenameCheckpointImage(txid, digest);
// So long as this is the newest image available,
// advertise it as such to other checkpointers
// from now on
storage.setMostRecentCheckpointTxId(txid);
}
/**
* Purge any files in the storage directories that are no longer
* necessary.
*/
public synchronized void purgeOldStorage() {
try {
archivalManager.purgeOldStorage();
} catch (Exception e) {
LOG.warn("Unable to purge old storage", e);
}
}
void reportErrorsOnImageManager(StorageDirectory badSD) {
if (imageSet != null) {
imageSet.reportErrorsOnImageManager(badSD);
}
}
void checkImageManagers() throws IOException {
if (imageSet != null) {
imageSet.checkImageManagers();
}
}
void updateImageMetrics() {
if (imageSet != null) {
imageSet.updateImageMetrics();
}
}
void close() throws IOException {
if(editLog != null)
editLog.close();
storage.unlockAll();
}
/**
* Return the name of the latest image file.
* @param type which image should be preferred.
*/
File getFsImageName(StorageLocationType type) {
return storage.getFsImageName(type, storage.getMostRecentCheckpointTxId());
}
/**
* Returns the txid of the last checkpoint
*/
public long getLastCheckpointTxId() {
return storage.getMostRecentCheckpointTxId();
}
/**
* Retrieve checkpoint dirs from configuration.
*
* @param conf the Configuration
* @param defaultValue a default value for the attribute, if null
* @return a Collection of URIs representing the values in
* dfs.namenode.checkpoint.dir configuration property
*/
static Collection<File> getCheckpointDirs(Configuration conf,
String defaultName) {
Collection<String> dirNames = conf.getStringCollection("fs.checkpoint.dir");
if (dirNames.size() == 0 && defaultName != null) {
dirNames.add(defaultName);
}
Collection<File> dirs = new ArrayList<File>(dirNames.size());
for (String name : dirNames) {
dirs.add(new File(name));
}
return dirs;
}
static Collection<File> getCheckpointEditsDirs(Configuration conf,
String defaultName) {
Collection<String> dirNames = conf
.getStringCollection("fs.checkpoint.edits.dir");
if (dirNames.size() == 0 && defaultName != null) {
dirNames.add(defaultName);
}
Collection<File> dirs = new ArrayList<File>(dirNames.size());
for (String name : dirNames) {
dirs.add(new File(name));
}
return dirs;
}
public int getLayoutVersion() {
return storage.getLayoutVersion();
}
public int getNamespaceID() {
return storage.getNamespaceID();
}
public void cancelSaveNamespace(String reason) {
saveNamespaceContext.cancel(reason);
InjectionHandler.processEvent(InjectionEvent.FSIMAGE_CANCEL_REQUEST_RECEIVED);
}
public void clearCancelSaveNamespace() {
saveNamespaceContext.clear();
}
protected long getImageTxId() {
return saveNamespaceContext.getTxId();
}
public Iterator<StorageDirectory> dirIterator(StorageDirType dirType) {
return storage.dirIterator(dirType);
}
public Iterator<StorageDirectory> dirIterator() {
return storage.dirIterator();
}
static void rollForwardByApplyingLogs(
RemoteEditLogManifest manifest,
FSImage dstImage) throws IOException {
NNStorage dstStorage = dstImage.storage;
List<EditLogInputStream> editsStreams = new ArrayList<EditLogInputStream>();
for (RemoteEditLog log : manifest.getLogs()) {
if (log.inProgress())
break;
File f = dstStorage.findFinalizedEditsFile(
log.getStartTxId(), log.getEndTxId());
if (log.getStartTxId() > dstImage.getLastAppliedTxId()) {
editsStreams.add(new EditLogFileInputStream(f, log.getStartTxId(),
log.getEndTxId(), false));
}
}
dstImage.loadEdits(editsStreams);
}
/**
* Get a list of output streams for writing chekpoint images.
*/
public List<OutputStream> getCheckpointImageOutputStreams(long imageTxId)
throws IOException {
return imageSet.getCheckpointImageOutputStreams(imageTxId);
}
}
| 48,439 | 0.68288 | 0.680732 | 1,348 | 34.933975 | 26.494598 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54451 | false | false | 0 |
f5f8f05f050b21b95648500adafec3988f6ae03d | 4,337,916,996,974 | aaf176be0e888f8e3749d512cacfc036706d5cbe | /src/main/java/controller/Start.java | 537178f1652f4efdede16e471d28fbc13890743a | [] | no_license | arcohen/swingy | https://github.com/arcohen/swingy | f592d987abe20b155744beeee55ca766c67b312f | 345766c64b3b31731446abc9daee078a180a47f1 | refs/heads/master | 2020-07-04T06:00:25.785000 | 2019-11-08T22:19:36 | 2019-11-08T22:19:36 | 198,815,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import model.Hero;
import model.SavedHeroes;
import utilities.ParseInput;
import view.*;
public class Start {
UserOutput o = new UserOutput();
ParseInput input = new ParseInput();
public Start() throws IOException, ClassNotFoundException {
File savedHeroesFile = new File("../../../GameSettings/savedHeroes.txt");
SavedHeroes savedHeroes;
if (savedHeroesFile.exists()) {
try {
FileInputStream fileInputStream = new FileInputStream(savedHeroesFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
savedHeroes = (SavedHeroes) objectInputStream.readObject();
objectInputStream.close();
}
catch (Exception e) {
savedHeroes = new SavedHeroes();
System.out.println(e.getMessage());
}
if (savedHeroes.getHeroes().isEmpty())
{
newCharacter(savedHeroes);
}
else {
o.output("Would you like to (1) create a new hero or (2) load a saved hero");
int inputInt = input.intRange(1, 2);
if (inputInt == 1)
newCharacter(savedHeroes);
else
loadSavedCharacter(savedHeroes);
}
}
else {
o.output("No saved heroes found.");
o.delay(500);
savedHeroes = new SavedHeroes();
try {
FileOutputStream fileOutputStream = new FileOutputStream(savedHeroesFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(savedHeroes);
objectOutputStream.flush();
objectOutputStream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
newCharacter(savedHeroes);
}
}
private void newCharacter(SavedHeroes savedHeroes) {
o.output("You will now create a new hero..\n");
new createHero(savedHeroes);
}
private void loadSavedCharacter(SavedHeroes savedHeroes) {
new SavedHeroesView(savedHeroes);
Hero hero = savedHeroes.getHero(input.intRange(1, savedHeroes.getHeroes().size()) - 1);
hero.setSavedHeroes(savedHeroes);
new Level().start(hero);
}
} | UTF-8 | Java | 2,720 | java | Start.java | Java | [] | null | [] | package controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import model.Hero;
import model.SavedHeroes;
import utilities.ParseInput;
import view.*;
public class Start {
UserOutput o = new UserOutput();
ParseInput input = new ParseInput();
public Start() throws IOException, ClassNotFoundException {
File savedHeroesFile = new File("../../../GameSettings/savedHeroes.txt");
SavedHeroes savedHeroes;
if (savedHeroesFile.exists()) {
try {
FileInputStream fileInputStream = new FileInputStream(savedHeroesFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
savedHeroes = (SavedHeroes) objectInputStream.readObject();
objectInputStream.close();
}
catch (Exception e) {
savedHeroes = new SavedHeroes();
System.out.println(e.getMessage());
}
if (savedHeroes.getHeroes().isEmpty())
{
newCharacter(savedHeroes);
}
else {
o.output("Would you like to (1) create a new hero or (2) load a saved hero");
int inputInt = input.intRange(1, 2);
if (inputInt == 1)
newCharacter(savedHeroes);
else
loadSavedCharacter(savedHeroes);
}
}
else {
o.output("No saved heroes found.");
o.delay(500);
savedHeroes = new SavedHeroes();
try {
FileOutputStream fileOutputStream = new FileOutputStream(savedHeroesFile);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(savedHeroes);
objectOutputStream.flush();
objectOutputStream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
newCharacter(savedHeroes);
}
}
private void newCharacter(SavedHeroes savedHeroes) {
o.output("You will now create a new hero..\n");
new createHero(savedHeroes);
}
private void loadSavedCharacter(SavedHeroes savedHeroes) {
new SavedHeroesView(savedHeroes);
Hero hero = savedHeroes.getHero(input.intRange(1, savedHeroes.getHeroes().size()) - 1);
hero.setSavedHeroes(savedHeroes);
new Level().start(hero);
}
} | 2,720 | 0.580882 | 0.577206 | 87 | 30.275862 | 25.887774 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517241 | false | false | 0 |
0e066d520849444873be73d6e27f79ff47e602b2 | 15,616,501,157,313 | c6e023bcc1115b0aa92c5a2b658e97d9cdf29789 | /src/uk/co/adilparvez/markovchainsimulator/InvalidTransitionsException.java | cec32e301419f903fca87f4328a6b4d3fbb5d0aa | [] | no_license | AdilParvez/Markov-Chain-Simulator | https://github.com/AdilParvez/Markov-Chain-Simulator | bca57a171ce3537caa5900f82afdad67c084b2df | 455055982ab6100dd25480e1479af007474268fb | refs/heads/master | 2016-09-07T02:59:54.617000 | 2014-07-04T15:02:37 | 2014-07-04T15:02:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.co.adilparvez.markovchainsimulator;
@SuppressWarnings("serial")
public class InvalidTransitionsException extends Exception {
public InvalidTransitionsException(String msg) {
super(msg);
}
}
| UTF-8 | Java | 209 | java | InvalidTransitionsException.java | Java | [
{
"context": "package uk.co.adilparvez.markovchainsimulator;\n\n@SuppressWarnings(\"serial\"",
"end": 24,
"score": 0.8884304761886597,
"start": 14,
"tag": "USERNAME",
"value": "adilparvez"
}
] | null | [] | package uk.co.adilparvez.markovchainsimulator;
@SuppressWarnings("serial")
public class InvalidTransitionsException extends Exception {
public InvalidTransitionsException(String msg) {
super(msg);
}
}
| 209 | 0.799043 | 0.799043 | 10 | 19.9 | 22.496445 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 0 |
d070c93bea17f87f26660594bdd27ecbf7ee8ced | 8,753,143,366,930 | 2d124631d525cff9a5b1eb889654eac07c27d136 | /app/src/main/java/com/example/hemantj/tictacgame/SelectionActivity.java | 9d095b659b657ee59a852371a5852c752927b58f | [] | no_license | hjoshi123/TicTacFirebase | https://github.com/hjoshi123/TicTacFirebase | 65e8fc7e5ab59d09902b829c4e7c300670ee0065 | 06130ca48dd6b5b157286bbecee95028d2425a9e | refs/heads/master | 2019-04-28T10:53:50.211000 | 2017-06-27T15:20:30 | 2017-06-27T15:20:30 | 94,019,309 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.hemantj.tictacgame;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class SelectionActivity extends AppCompatActivity {
private Button btn1;
private Button btn2;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
btn1 = (Button) findViewById(R.id.against_friend);
btn2 = (Button) findViewById(R.id.against_cpu);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SelectionActivity.this,UsersActivity.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SelectionActivity.this,GameActivity.class);
intent.putExtra("play",2);
startActivity(intent);
}
});
}
}
| UTF-8 | Java | 1,442 | java | SelectionActivity.java | Java | [
{
"context": "package com.example.hemantj.tictacgame;\n\nimport android.content.Intent;\nimpor",
"end": 27,
"score": 0.997310221195221,
"start": 20,
"tag": "USERNAME",
"value": "hemantj"
}
] | null | [] | package com.example.hemantj.tictacgame;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class SelectionActivity extends AppCompatActivity {
private Button btn1;
private Button btn2;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
btn1 = (Button) findViewById(R.id.against_friend);
btn2 = (Button) findViewById(R.id.against_cpu);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SelectionActivity.this,UsersActivity.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SelectionActivity.this,GameActivity.class);
intent.putExtra("play",2);
startActivity(intent);
}
});
}
}
| 1,442 | 0.670596 | 0.665049 | 43 | 32.534885 | 24.18182 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604651 | false | false | 0 |
2d7588d5f1b9940d0886d6f05acadf0e7d659d41 | 16,106,127,389,851 | 7cb2e66960ee7fc2cf9d4e636b202cc899a02146 | /src/cn/itcast/scm/action/GoodsAction.java | 40922a988185bd260962f5248bca1eb0851bec72 | [] | no_license | lyc88/ssm | https://github.com/lyc88/ssm | 9efa33d0d4887ada1fee7d8a19456da3667bdb02 | de0997920f0557318bb93c1f6939895d0f6db318 | refs/heads/master | 2021-01-20T20:28:16.893000 | 2016-07-11T15:42:29 | 2016-07-11T15:42:29 | 63,080,770 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.itcast.scm.action;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.itcast.scm.entity.Goods;
import cn.itcast.scm.entity.Page;
import cn.itcast.scm.entity.Supplier;
import cn.itcast.scm.service.GoodsService;
import cn.itcast.scm.service.SupplierService;
@Controller
@RequestMapping("/goods")
public class GoodsAction extends BaseAction {
@Resource
private GoodsService goodsService;
//通过关键字分页查询
@RequestMapping("/selectPageUseDyc")
@ResponseBody //如果返回json格式,需要这个注解,这里用来测试环境
public Object selectPageUseDyc(Page<Goods> page,Goods goods){
page.setParamEntity(goods);
System.out.println("----page:"+page);
Page p = goodsService.selectPageUseDyc(page);
//supplier.setSupName("supName1");
/*Map<String, Object> map =new HashMap<String, Object>();
map.put("total",p.getTotalRecord());
map.put("rows",p.getList());*/
return p.getPageMap();
}
}
| UTF-8 | Java | 1,254 | java | GoodsAction.java | Java | [] | null | [] | package cn.itcast.scm.action;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.itcast.scm.entity.Goods;
import cn.itcast.scm.entity.Page;
import cn.itcast.scm.entity.Supplier;
import cn.itcast.scm.service.GoodsService;
import cn.itcast.scm.service.SupplierService;
@Controller
@RequestMapping("/goods")
public class GoodsAction extends BaseAction {
@Resource
private GoodsService goodsService;
//通过关键字分页查询
@RequestMapping("/selectPageUseDyc")
@ResponseBody //如果返回json格式,需要这个注解,这里用来测试环境
public Object selectPageUseDyc(Page<Goods> page,Goods goods){
page.setParamEntity(goods);
System.out.println("----page:"+page);
Page p = goodsService.selectPageUseDyc(page);
//supplier.setSupName("supName1");
/*Map<String, Object> map =new HashMap<String, Object>();
map.put("total",p.getTotalRecord());
map.put("rows",p.getList());*/
return p.getPageMap();
}
}
| 1,254 | 0.744966 | 0.744128 | 42 | 26.380953 | 20.009464 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 0 |
b998bd4b15ae9a190fe773b31f2875cd670382ed | 3,367,254,396,369 | 3b059d8a20a64bf1f17b76f67a0b21fc48ebb146 | /app/src/main/java/com/conta/saci/conta/ws/DirectPurchaseService.java | cb74cf236e2f73846de85f976a04bd968716f7f7 | [] | no_license | joaolbl/Conta | https://github.com/joaolbl/Conta | cb349b77458e202473e2df028f2fc1ec4722d149 | c24ebabbb2e5d1196c1516582fa1b8530e14e0e5 | refs/heads/master | 2021-01-23T05:56:30.226000 | 2017-06-06T19:37:46 | 2017-06-06T19:37:46 | 93,002,669 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.conta.saci.conta.ws;
import android.content.Context;
import android.os.AsyncTask;
import com.conta.saci.conta.R;
import com.conta.saci.conta.entity.Person;
import java.io.DataOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by JZLA on 06/06/2017.
*/
public class DirectPurchaseService {
private Context context;
DirectPurchaseService(Context context) {
this.context = context;
}
public void saveDirectPurchase(Person buyer, Person requester, BigDecimal price, String comment, Date purchaseDate, String item) {
//Convert date to correct format;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String purchaseDateString = sdf.format(purchaseDate);
//Call web service
AsyncTask<String, Void, Void> addDirectPurchase = new AddDirectPurchase();
addDirectPurchase.execute(buyer.getId().toString(),
requester.getId().toString(),
price.toString(),
comment,
purchaseDateString,
item);
}
/**
* Call the web service that adds a new direct purchase for the user calling it and the requester. The order of the parameters passed in the execute method must be:
* buyerId
* requesterId
* purchaseValue
* comment
* purchaseDate
* item
*/
class AddDirectPurchase extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String urlString = context.getString(R.string.direct_purchase_ws_url_add);
try {
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//get parameters
String buyerId = params[0];
String requesterId = params[1];
String price = params[2];
String comment = params[3];
String purchaseDate = params[4];
String item = params[5];
String wsParams = "buyerId=" + buyerId;
wsParams += "&requesterId=" + requesterId;
wsParams += "&purchaseValue=" + price;
wsParams += "&comment=" + comment;
wsParams += "&purchaseDate=" + purchaseDate;
wsParams += "&item=" + item;
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(wsParams);
dos.flush();
dos.close();
if (connection.getResponseCode() != 200) {
throw new Exception("The web service call was unsuccessful. The returned code was: " + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("There has been a problem while calling the web service", e);
}
return null;
}
}
}
| UTF-8 | Java | 3,245 | java | DirectPurchaseService.java | Java | [
{
"context": ".net.ssl.HttpsURLConnection;\r\n\r\n/**\r\n * Created by JZLA on 06/06/2017.\r\n */\r\n\r\npublic class DirectPurchas",
"end": 394,
"score": 0.9997286796569824,
"start": 390,
"tag": "USERNAME",
"value": "JZLA"
}
] | null | [] | package com.conta.saci.conta.ws;
import android.content.Context;
import android.os.AsyncTask;
import com.conta.saci.conta.R;
import com.conta.saci.conta.entity.Person;
import java.io.DataOutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by JZLA on 06/06/2017.
*/
public class DirectPurchaseService {
private Context context;
DirectPurchaseService(Context context) {
this.context = context;
}
public void saveDirectPurchase(Person buyer, Person requester, BigDecimal price, String comment, Date purchaseDate, String item) {
//Convert date to correct format;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String purchaseDateString = sdf.format(purchaseDate);
//Call web service
AsyncTask<String, Void, Void> addDirectPurchase = new AddDirectPurchase();
addDirectPurchase.execute(buyer.getId().toString(),
requester.getId().toString(),
price.toString(),
comment,
purchaseDateString,
item);
}
/**
* Call the web service that adds a new direct purchase for the user calling it and the requester. The order of the parameters passed in the execute method must be:
* buyerId
* requesterId
* purchaseValue
* comment
* purchaseDate
* item
*/
class AddDirectPurchase extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String urlString = context.getString(R.string.direct_purchase_ws_url_add);
try {
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
//get parameters
String buyerId = params[0];
String requesterId = params[1];
String price = params[2];
String comment = params[3];
String purchaseDate = params[4];
String item = params[5];
String wsParams = "buyerId=" + buyerId;
wsParams += "&requesterId=" + requesterId;
wsParams += "&purchaseValue=" + price;
wsParams += "&comment=" + comment;
wsParams += "&purchaseDate=" + purchaseDate;
wsParams += "&item=" + item;
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(wsParams);
dos.flush();
dos.close();
if (connection.getResponseCode() != 200) {
throw new Exception("The web service call was unsuccessful. The returned code was: " + connection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("There has been a problem while calling the web service", e);
}
return null;
}
}
}
| 3,245 | 0.577812 | 0.572573 | 96 | 31.802084 | 31.867439 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 0 |
dc2e370381525f1251a2c34ada58d3544da5d492 | 16,801,912,080,392 | 1e50ce4cf47bdd96e0a62264e22d7e78807dbb7e | /skylib-java/lib-gui-java8/src/main/java/ch/scaille/gui/swing/AbstractJTablePopup.java | 6ed05451a29717ef048aa1d3c3cb7c3f8ddf49a4 | [
"BSD-4.3TAHOE",
"BSD-3-Clause"
] | permissive | sebastiencaille/sky-lib | https://github.com/sebastiencaille/sky-lib | a56b11908c8b1aca2d6eaff2d41de7abea083538 | b72501f8884b06d18a3002402a125bd566772a51 | refs/heads/master | 2023-08-17T01:14:57.750000 | 2023-08-05T19:20:46 | 2023-08-05T19:20:46 | 15,059,127 | 0 | 0 | BSD-3-Clause | false | 2023-04-04T19:22:53 | 2013-12-09T21:09:58 | 2022-01-09T13:30:45 | 2023-04-04T19:22:52 | 8,598 | 0 | 0 | 0 | Java | false | false | /*******************************************************************************
* Copyright (c) 2017 Sebastien Caille.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above Copyrightnotice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Sebastien Caille. The name of Sebastien Caille may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
******************************************************************************/
package ch.scaille.gui.swing;
import java.awt.Point;
import java.util.Collection;
import javax.swing.JTable;
import ch.scaille.gui.mvc.properties.ObjectProperty;
import ch.scaille.gui.swing.model.ListModelTableModel;
/**
* Popup on JTable with a ListModelTableModel
* <p>
* Provides object at the line the popup was opened.
*
* @author Sebastien Caille
*
* @param <T>
*/
public abstract class AbstractJTablePopup<T> extends AbstractPopup<T> {
private final JTable table;
private final ListModelTableModel<T, ?> model;
private final ObjectProperty<? extends Collection<T>> selections;
protected AbstractJTablePopup(final JTable table, final ListModelTableModel<T, ?> model,
final ObjectProperty<T> lastSelected, final ObjectProperty<? extends Collection<T>> selections) {
super(lastSelected);
this.table = table;
this.model = model;
this.selections = selections;
}
@Override
protected T getValueForPopup(final Point p) {
final T objectToSelect = model.getObjectAtRow(table.rowAtPoint(p));
if (objectToSelect != null) {
boolean selected = selections != null && selections.getValue() != null
&& selections.getValue().contains(objectToSelect);
selected |= lastSelected != null && lastSelected.getValue() == objectToSelect;
if (!selected) {
final int index = model.getRowOf(objectToSelect);
table.getSelectionModel().setSelectionInterval(index, index);
}
}
return objectToSelect;
}
}
| UTF-8 | Java | 2,391 | java | AbstractJTablePopup.java | Java | [
{
"context": "****************************\n * Copyright (c) 2017 Sebastien Caille.\n * All rights reserved.\n * \n * Redistribution ",
"end": 119,
"score": 0.9998962879180908,
"start": 103,
"tag": "NAME",
"value": "Sebastien Caille"
},
{
"context": "acknowledge that the software w... | null | [] | /*******************************************************************************
* Copyright (c) 2017 <NAME>.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above Copyrightnotice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by <NAME>. The name of Sebastien Caille may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
******************************************************************************/
package ch.scaille.gui.swing;
import java.awt.Point;
import java.util.Collection;
import javax.swing.JTable;
import ch.scaille.gui.mvc.properties.ObjectProperty;
import ch.scaille.gui.swing.model.ListModelTableModel;
/**
* Popup on JTable with a ListModelTableModel
* <p>
* Provides object at the line the popup was opened.
*
* @author <NAME>
*
* @param <T>
*/
public abstract class AbstractJTablePopup<T> extends AbstractPopup<T> {
private final JTable table;
private final ListModelTableModel<T, ?> model;
private final ObjectProperty<? extends Collection<T>> selections;
protected AbstractJTablePopup(final JTable table, final ListModelTableModel<T, ?> model,
final ObjectProperty<T> lastSelected, final ObjectProperty<? extends Collection<T>> selections) {
super(lastSelected);
this.table = table;
this.model = model;
this.selections = selections;
}
@Override
protected T getValueForPopup(final Point p) {
final T objectToSelect = model.getObjectAtRow(table.rowAtPoint(p));
if (objectToSelect != null) {
boolean selected = selections != null && selections.getValue() != null
&& selections.getValue().contains(objectToSelect);
selected |= lastSelected != null && lastSelected.getValue() == objectToSelect;
if (!selected) {
final int index = model.getRowOf(objectToSelect);
table.getSelectionModel().setSelectionInterval(index, index);
}
}
return objectToSelect;
}
}
| 2,361 | 0.70138 | 0.699707 | 65 | 35.784615 | 30.393063 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.276923 | false | false | 0 |
ae4aaa5214efcba95a6e35684cf99e9629bb8f41 | 14,181,982,047,438 | 6a9dc4554a945d1fc9304693d2ea14c41ace8833 | /src/org/cris/clip/dto/WageReportDTO.java | d4a676bafc3b421b93fd155b2c69697cf45b5cf8 | [
"MIT"
] | permissive | deepbanerji/Shramik_Kalyan_Portal | https://github.com/deepbanerji/Shramik_Kalyan_Portal | 0358fee55dec45b9eed358fe2ee11a9bc338cd2c | 80d4d36469b1b1b836316e18be874f8eca20f2da | refs/heads/master | 2020-04-07T08:10:45.731000 | 2018-11-19T10:40:16 | 2018-11-19T10:40:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.cris.clip.dto;
public class WageReportDTO
{
String name;
String desg;
String employType;
String skillType;
String adharNo;
String panNO;
String id;
String woid;
String contId;
String workmanId;
String month;
String year;
int attendance;
int wageRate;
int others;
int deduct;
int netAmount;
int otWage;
int pf;
int bonus;
int pension;
String workstartdt;
String bankDeposiDt;
String pfDepositDt;
String contName;
String woName;
int wagerecovery;
String firmName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesg() {
return desg;
}
public void setDesg(String desg) {
this.desg = desg;
}
public String getEmployType() {
return employType;
}
public void setEmployType(String employType) {
this.employType = employType;
}
public String getSkillType() {
return skillType;
}
public void setSkillType(String skillType) {
this.skillType = skillType;
}
public String getAdharNo() {
return adharNo;
}
public void setAdharNo(String adharNo) {
this.adharNo = adharNo;
}
public String getPanNO() {
return panNO;
}
public void setPanNO(String panNO) {
this.panNO = panNO;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getWoid() {
return woid;
}
public void setWoid(String woid) {
this.woid = woid;
}
public String getContId() {
return contId;
}
public void setContId(String contId) {
this.contId = contId;
}
public String getWorkmanId() {
return workmanId;
}
public void setWorkmanId(String workmanId) {
this.workmanId = workmanId;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public int getAttendance() {
return attendance;
}
public void setAttendance(int attendance) {
this.attendance = attendance;
}
public int getWageRate() {
return wageRate;
}
public void setWageRate(int wageRate) {
this.wageRate = wageRate;
}
public int getOthers() {
return others;
}
public void setOthers(int others) {
this.others = others;
}
public int getDeduct() {
return deduct;
}
public void setDeduct(int deduct) {
this.deduct = deduct;
}
public int getNetAmount() {
return netAmount;
}
public void setNetAmount(int netAmount) {
this.netAmount = netAmount;
}
public int getOtWage() {
return otWage;
}
public void setOtWage(int otWage) {
this.otWage = otWage;
}
public int getPf() {
return pf;
}
public void setPf(int pf) {
this.pf = pf;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
public int getPension() {
return pension;
}
public void setPension(int pension) {
this.pension = pension;
}
public String getWorkstartdt() {
return workstartdt;
}
public void setWorkstartdt(String workstartdt) {
this.workstartdt = workstartdt;
}
public String getBankDeposiDt() {
return bankDeposiDt;
}
public void setBankDeposiDt(String bankDeposiDt) {
this.bankDeposiDt = bankDeposiDt;
}
public String getPfDepositDt() {
return pfDepositDt;
}
public void setPfDepositDt(String pfDepositDt) {
this.pfDepositDt = pfDepositDt;
}
public String getContName() {
return contName;
}
public void setContName(String contName) {
this.contName = contName;
}
public String getWoName() {
return woName;
}
public void setWoName(String woName) {
this.woName = woName;
}
public int getWagerecovery() {
return wagerecovery;
}
public void setWagerecovery(int wagerecovery) {
this.wagerecovery = wagerecovery;
}
public String getFirmName() {
return firmName;
}
public void setFirmName(String firmName) {
this.firmName = firmName;
}
}
| UTF-8 | Java | 4,079 | java | WageReportDTO.java | Java | [] | null | [] | package org.cris.clip.dto;
public class WageReportDTO
{
String name;
String desg;
String employType;
String skillType;
String adharNo;
String panNO;
String id;
String woid;
String contId;
String workmanId;
String month;
String year;
int attendance;
int wageRate;
int others;
int deduct;
int netAmount;
int otWage;
int pf;
int bonus;
int pension;
String workstartdt;
String bankDeposiDt;
String pfDepositDt;
String contName;
String woName;
int wagerecovery;
String firmName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesg() {
return desg;
}
public void setDesg(String desg) {
this.desg = desg;
}
public String getEmployType() {
return employType;
}
public void setEmployType(String employType) {
this.employType = employType;
}
public String getSkillType() {
return skillType;
}
public void setSkillType(String skillType) {
this.skillType = skillType;
}
public String getAdharNo() {
return adharNo;
}
public void setAdharNo(String adharNo) {
this.adharNo = adharNo;
}
public String getPanNO() {
return panNO;
}
public void setPanNO(String panNO) {
this.panNO = panNO;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getWoid() {
return woid;
}
public void setWoid(String woid) {
this.woid = woid;
}
public String getContId() {
return contId;
}
public void setContId(String contId) {
this.contId = contId;
}
public String getWorkmanId() {
return workmanId;
}
public void setWorkmanId(String workmanId) {
this.workmanId = workmanId;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public int getAttendance() {
return attendance;
}
public void setAttendance(int attendance) {
this.attendance = attendance;
}
public int getWageRate() {
return wageRate;
}
public void setWageRate(int wageRate) {
this.wageRate = wageRate;
}
public int getOthers() {
return others;
}
public void setOthers(int others) {
this.others = others;
}
public int getDeduct() {
return deduct;
}
public void setDeduct(int deduct) {
this.deduct = deduct;
}
public int getNetAmount() {
return netAmount;
}
public void setNetAmount(int netAmount) {
this.netAmount = netAmount;
}
public int getOtWage() {
return otWage;
}
public void setOtWage(int otWage) {
this.otWage = otWage;
}
public int getPf() {
return pf;
}
public void setPf(int pf) {
this.pf = pf;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
public int getPension() {
return pension;
}
public void setPension(int pension) {
this.pension = pension;
}
public String getWorkstartdt() {
return workstartdt;
}
public void setWorkstartdt(String workstartdt) {
this.workstartdt = workstartdt;
}
public String getBankDeposiDt() {
return bankDeposiDt;
}
public void setBankDeposiDt(String bankDeposiDt) {
this.bankDeposiDt = bankDeposiDt;
}
public String getPfDepositDt() {
return pfDepositDt;
}
public void setPfDepositDt(String pfDepositDt) {
this.pfDepositDt = pfDepositDt;
}
public String getContName() {
return contName;
}
public void setContName(String contName) {
this.contName = contName;
}
public String getWoName() {
return woName;
}
public void setWoName(String woName) {
this.woName = woName;
}
public int getWagerecovery() {
return wagerecovery;
}
public void setWagerecovery(int wagerecovery) {
this.wagerecovery = wagerecovery;
}
public String getFirmName() {
return firmName;
}
public void setFirmName(String firmName) {
this.firmName = firmName;
}
}
| 4,079 | 0.668546 | 0.668546 | 205 | 17.89756 | 13.411835 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.663415 | false | false | 0 |
f1b01c239e9b0cd045e639aae7cb186ba20aa24e | 37,314,675,893,633 | ef7523c4092f5b2ccacef3cc244d1e2665acbdf5 | /application-framework/spring-boot/src/main/java/org/mac/explorations/framework/springboot/autoconfigure/service/SimpleEchoService.java | b03f0e0bee1429c5762457917b2521d3c24972a1 | [] | no_license | stinymac/explorations | https://github.com/stinymac/explorations | 90acdde5a6796a14a9abee649bf2d1b5b2b56169 | 959579603de26c8315813f799c7fda8a0d4b770f | refs/heads/master | 2020-07-22T03:26:40.844000 | 2020-06-13T07:39:08 | 2020-06-13T07:39:08 | 207,059,540 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* ( (
* )\ ) ( )\ ) ) (
* ( ( (()/( ))\( ((_| /( /(( ))\
* )\ )\ ((_))((_)\ _ )(_)|_))\ /((_)
* ((_|(_) _| (_))((_) ((_)__)((_|_))
* / _/ _ \/ _` / -_|_-< / _` \ V // -_)
* \__\___/\__,_\___/__/_\__,_|\_/ \___|
*
* 东隅已逝,桑榆非晚。(The time has passed,it is not too late.)
* 虽不能至,心向往之。(Although I can't, my heart is longing for it.)
*
*/
package org.mac.explorations.framework.springboot.autoconfigure.service;
/**
* @auther mac
* @date 2020-01-31 18:48
*/
public class SimpleEchoService {
public String echo(String content) {
return "-> : "+ content;
}
}
| UTF-8 | Java | 675 | java | SimpleEchoService.java | Java | [
{
"context": ".springboot.autoconfigure.service;\n\n/**\n * @auther mac\n * @date 2020-01-31 18:48\n */\npublic class Simple",
"end": 488,
"score": 0.9884246587753296,
"start": 485,
"tag": "USERNAME",
"value": "mac"
}
] | null | [] | /*
* ( (
* )\ ) ( )\ ) ) (
* ( ( (()/( ))\( ((_| /( /(( ))\
* )\ )\ ((_))((_)\ _ )(_)|_))\ /((_)
* ((_|(_) _| (_))((_) ((_)__)((_|_))
* / _/ _ \/ _` / -_|_-< / _` \ V // -_)
* \__\___/\__,_\___/__/_\__,_|\_/ \___|
*
* 东隅已逝,桑榆非晚。(The time has passed,it is not too late.)
* 虽不能至,心向往之。(Although I can't, my heart is longing for it.)
*
*/
package org.mac.explorations.framework.springboot.autoconfigure.service;
/**
* @auther mac
* @date 2020-01-31 18:48
*/
public class SimpleEchoService {
public String echo(String content) {
return "-> : "+ content;
}
}
| 675 | 0.377953 | 0.359055 | 26 | 23.423077 | 21.262413 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 0 |
0094b644249361110e16f288e9f1b472df5530d0 | 34,291,018,935,908 | e31e6de6ec1587d4e94d0ef3a17e3ac4d0df3ff9 | /src/plugins/SGPlugin/analyzer/statTable/StatTable.java | 0d3040ad05a708c6f3049d1e536d1e740c1ac7b6 | [] | no_license | drilett/SunFish | https://github.com/drilett/SunFish | a588d238c0f21dbf241e95897d86180206b01c35 | ea895dc49568f0ee1fbb005b7d641258b41bb133 | refs/heads/master | 2021-01-22T08:32:35.817000 | 2011-10-25T13:55:49 | 2011-10-25T13:55:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package plugins.SGPlugin.analyzer.statTable;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import plugins.SGPlugin.sgStatistics.*;
import sun.swing.table.DefaultTableCellHeaderRenderer;
import topLevelGUI.SunFishFrame;
import element.sequence.*;
import guiWidgets.StringUtilities;
/**
* A table that houses seq stats as rows and sequencegroups or partitions as columns. StatTables are currently
* only used in the SequenceGroupSummary to display various sg. statistics associated with one or more sequence groups.
* @author brendan
*
*/
public class StatTable extends JPanel {
JScrollPane scrollPane;
JTable table;
StatTableModel tableModel;
List<SequenceGroup> currentSGs = new ArrayList<SequenceGroup>(10);
List<StatTableColumn> statColumns = new ArrayList<StatTableColumn>();
List<SGCalculator> currentStats = new ArrayList<SGCalculator>(10);
static Font rowHeaderFont = new Font("Sans", Font.PLAIN, 11);
static Font colHeaderFont = new Font("Sans", Font.PLAIN, 11);
static Font valFont = new Font("Sans", Font.PLAIN, 11);
static Color textShadowColor = new Color(0.9f, 0.9f, 0.9f, 0.3f);
static Color stripeColor = new Color(56, 56, 56, 20);
StatTableRowHeader rowHeader;
HeaderRenderer headerRenderer = new HeaderRenderer();
CellRenderer cellRenderer = new CellRenderer();
JPopupMenu popup;
Point popupPosition;
public StatTable() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setBackground(Color.white);
table = new JTable();
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
tableModel = new StatTableModel();
table.setModel(tableModel);
table.setOpaque(false);
table.setFont(valFont);
table.setDefaultRenderer(Object.class, cellRenderer);
table.setDefaultRenderer(String.class, cellRenderer);
table.setRowHeight(20);
scrollPane = new JScrollPane(table);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
JPanel leftPanel = new JPanel();
leftPanel.setOpaque(false);
leftPanel.setMaximumSize(new Dimension(10, Integer.MAX_VALUE));
this.add(leftPanel);
this.add(scrollPane);
scrollPane.setPreferredSize(new Dimension(200, 200));
this.add(Box.createGlue());
rowHeader = new StatTableRowHeader(table, 150);
rowHeader.setShowHorizontalLines(false);
rowHeader.setFont(rowHeaderFont);
scrollPane.setRowHeaderView(rowHeader);
scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
scrollPane.setBorder(BorderFactory.createEmptyBorder());
table.setBorder(BorderFactory.createEmptyBorder());
//Construct popup
popup = new JPopupMenu();
popup.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY) );
popup.setBackground(new Color(100,100,100) );
JMenuItem popupRemove = new JMenuItem("Remove column");
popupRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeColumnFromPopup();
}
});
popup.add(popupRemove);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.isPopupTrigger() || (SunFishFrame.getSunFishFrame().onAMac() && evt.isControlDown()) || (evt.getButton()==MouseEvent.BUTTON3)) {
popupPosition = evt.getPoint();
popup.show(table, evt.getX(), evt.getY());
}
}
});
}
/**
* Returns the column index underneath the given point
* @param p
* @return
*/
private int getColumnForPoint(Point p) {
//System.out.println("Point x: " + p.x + " column 0 width: " + table.getColumn( sgColumnNames.get(0)).getWidth());
int x = p.x;
if (x < table.getColumn( statColumns.get(0).getName()).getWidth())
return 0;
for(int i=1; i<table.getColumnCount(); i++) {
//System.out.println("Column " + i + " width: " + table.getColumn( sgColumnNames.get(i)).getWidth());
x -= table.getColumn( statColumns.get(i-1).getName()).getWidth();
if (x < table.getColumn(statColumns.get(i).getName()).getWidth())
return i;
}
System.out.println("Could not find column for point: " + p.x);
return -1;
}
/**
* Removes a column from the table based on the position of the popup.
*/
protected void removeColumnFromPopup() {
int column = getColumnForPoint(popupPosition);
if (column>-1) {
//System.out.println("Point: " + popupPosition.getX() + " column index: " + column + " name: " + sgColumnNames.get(column));
removeColumn(statColumns.get(column).getName());
}
}
private void emitAll() {
System.out.println("Table columns " + table.getColumnCount() + " stat columns: " + statColumns.size() );
for(int i=0; i<statColumns.size(); i++) {
System.out.println(i + " : " + statColumns.get(i).getName() );
}
System.out.println();
}
/**
* Return the index of the StatColumn with the given name
* @param sg
* @return
*/
private int columnForName(String columnName) {
for(int i=0; i<statColumns.size(); i++) {
if (statColumns.get(i).getName().equals(columnName)) {
return i;
}
}
return -1;
}
/**
* Return the index of the StatColumn that refers to the given SequenceGroup
* @param sg
* @return
*/
// private int columnForSG(SequenceGroup sg) {
// for(int i=0; i<statColumns.size(); i++) {
// if (statColumns.get(i).getSG()==sg) {
// return i;
// }
// }
// return -1;
// }
/**
* Remove the column with the given name.
* @param columnName
*/
protected void removeColumn(String columnName) {
int index = columnForName(columnName);
if (index == -1) {
SunFishFrame.getSunFishFrame().getLogger().info("Could not remove StatTableColumn with name: " + columnName + ", no column with that name");
return;
}
statColumns.get(index).clearListeners();
statColumns.remove(index);
layoutColumns();
// System.out.println("State after removal, column count: " + tableModel.getColumnCount() );
// emitAll();
table.repaint();
}
// public List<SequenceGroup> getSequenceGroups() {
// return currentSGs;
// }
/**
* Add a new sequence group to be displayed as a column of this table. The header of the column is
* set to whatever 'name' is, and the width of the column is based on the width of the string
* @param sg
* @param name
*/
public void addSequenceGroup(SequenceGroup sg, String name) {
currentSGs.add(sg);
StatTableColumn newCol = new StatTableColumn(this, sg, name, currentStats);
statColumns.add(newCol);
//System.out.println(" \n Adding group : " + name + " column count before add : " + tableModel.getColumnCount());
layoutColumns();
//emitAll();
}
/**
* Add a new stat column with the same sequence group as col, but tracking the given partition index
* @param col
* @param newPartitionNumber
*/
public void handlePartitionAdd(StatTableColumn col, int newPartitionNumber) {
//First see if there's already a column with the same sg and partition number
for(StatTableColumn tCol : statColumns) {
if (tCol.getSG()==col.getSG() && tCol.getPartitionIndex()==newPartitionNumber) {
return;
}
}
//There's not a column tracking the new partition, so add one
SequenceGroup sg = col.getSG();
StatTableColumn newCol = new StatTableColumn(this, sg, col.getName() + " Par. " + partitionLetters[newPartitionNumber], currentStats, newPartitionNumber);
statColumns.add(newCol);
layoutColumns();
}
public void handlePartitionRemoved(StatTableColumn col) {
//See if there are any columns whose partition index does not match a partition in
//the sequence group
SequenceGroup sg = col.getSG();
List<StatTableColumn> colsToRemove = new ArrayList<StatTableColumn>();
for(StatTableColumn tCol : statColumns) {
if (tCol.getSG()==sg) {
if (sg.getPartitionSiteCount(tCol.getPartitionIndex() )==0) {
colsToRemove.add(tCol);
}
}
}
for(int i=0; i<colsToRemove.size(); i++)
statColumns.remove(colsToRemove.get(i));
layoutColumns();
}
/**
* This is called after any change to the stat columns. We refresh the model we new data to reflect any
* changes that may have occurred.
*/
private void layoutColumns() {
int totWidth = rowHeader.getWidth();
tableModel = new StatTableModel();
//System.out.println("Regenerating all columns...");
//Add a new column onto the end of each row
for(int j=0; j<statColumns.size(); j++) {
Object[] values = statColumns.get(j).getValues();
tableModel.addColumn(statColumns.get(j).getName(), values);
System.out.println("Added column " + j + " with name: " + statColumns.get(j).getName());
}
table.setModel( tableModel);
FontMetrics fm = table.getFontMetrics(colHeaderFont);
for(int i=0; i<tableModel.getColumnCount(); i++) {
String colName = statColumns.get(i).getName();
table.getColumnModel().getColumn( i ).setHeaderRenderer(new HeaderRenderer());
table.getColumnModel().getColumn( i ).setCellRenderer(new CellRenderer());
int colWidth = fm.stringWidth( colName )+10;
colWidth = Math.min(200, colWidth);
table.getColumnModel().getColumn( i ).setMinWidth(colWidth);
table.getColumnModel().getColumn( i ).setPreferredWidth(colWidth);
table.getColumnModel().getColumn( i ).setMaxWidth(Integer.MAX_VALUE);
table.getColumnModel().getColumn( i ).setResizable(true);
totWidth += colWidth;
//System.out.println("Setting header width for col " + colName + " to : " + colWidth);
}
scrollPane.setPreferredSize(new Dimension(totWidth, scrollPane.getHeight() ));
scrollPane.getViewport().setPreferredSize(new Dimension(totWidth, scrollPane.getHeight() ));
table.doLayout();
this.revalidate();
if (table.getWidth()>scrollPane.getWidth())
scrollPane.getHorizontalScrollBar().setVisible(true);
else
scrollPane.getHorizontalScrollBar().setVisible(false);
table.repaint();
System.out.println("Added " + statColumns.size() + " groups, table column count: " + table.getColumnModel().getColumnCount());
}
/**
* Adds a new statistic as a row
* @param statwww
*/
public void addStatistic(SGCalculator stat) {
currentStats.add(stat);
for(StatTableColumn statCol : statColumns)
statCol.addStatistic(stat);
rowHeader.addName(stat.getName());
layoutColumns();
}
/**
* Returns a list of the SG calculators currently used by this stat table
* @return
*/
public List<SGCalculator> getCalculators() {
return currentStats;
}
/**
* Removes this sequence group from the table. At least one column is removed from the
* table when this happens.
* @param sg
*/
public void removeSequenceGroup(SequenceGroup sg) {
int index = -1;
for(int i=0; i<statColumns.size(); i++) {
if (statColumns.get(i).getSG() == sg) {
index = i;
break;
}
}
statColumns.get(index).clearListeners();
statColumns.remove(index);
layoutColumns();
repaint();
}
/**
* Removes this statistic from the table. One row is removed from the table when
* this happens.
* @param stat
*/
// public void removeStatistic(SeqStatistic stat) {
//
// }
/**
* Remove all listeners from all the sequence groups
*/
public void clearAllListeners() {
for(StatTableColumn col : statColumns)
col.clearListeners();
}
/**
* A custom.. or not, table model. We may customize this someday.
* @author brendan
*
*/
class StatTableModel extends DefaultTableModel {
public boolean isCellEditable(int row, int col) {
return false;
}
}
/**
* Handles the drawing of the column headers
* @author brendan
*
*/
class HeaderRenderer extends JLabel implements TableCellRenderer {
int drawCloseBoxForColumn = -1;
int column = 0;
public HeaderRenderer() {
setBackground(Color.white);
this.setHorizontalTextPosition(JLabel.CENTER);
setFont(colHeaderFont);
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (statColumns.size()<2)
setText("");
else
setText(value.toString());
this.column = column;
return this;
}
public void paintComponent(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
g.setFont(colHeaderFont);
int textWidth = g.getFontMetrics().stringWidth(getText());
g.drawString(getText(), 3, getFont().getSize());
if (drawCloseBoxForColumn == column) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(2.2f));
int xPos = 3+g2d.getFontMetrics().stringWidth(getText());
if (xPos > getWidth()-10)
xPos = getWidth()-10;
int rectSize = 8;
g2d.drawLine(xPos, 1, xPos+rectSize, rectSize);
g2d.drawLine(xPos, rectSize, xPos+rectSize, 1);
}
}
}
/**
* Handles the drawing of individual values in the table
* @author brendan
*
*/
class CellRenderer extends DefaultTableCellRenderer {
int row;
public CellRenderer() {
setBackground(Color.white);
this.setHorizontalTextPosition(RIGHT);
setFont(valFont);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.row = row;
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
public void paintComponent(Graphics g) {
if (row%2==0)
g.setColor(getBackground());
else
g.setColor(stripeColor);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
g.setFont(getFont());
int height = g.getFontMetrics().getHeight();
int width = g.getFontMetrics().stringWidth(getText());
g.drawString(getText(), Math.max(2, 40-width/2), getHeight()/2+height/2-2);
g.setColor(textShadowColor);
g.drawString(getText(), Math.max(2, 40-width/2)+1, getHeight()/2+height/2-1);
}
}
private char[] partitionLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'};
}
| UTF-8 | Java | 15,319 | java | StatTable.java | Java | [
{
"context": "iated with one or more sequence groups.\n * @author brendan\n *\n */\npublic class StatTable extends JPane",
"end": 1424,
"score": 0.7756306529045105,
"start": 1423,
"tag": "USERNAME",
"value": "b"
},
{
"context": "ted with one or more sequence groups.\n * @author brend... | null | [] | package plugins.SGPlugin.analyzer.statTable;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import plugins.SGPlugin.sgStatistics.*;
import sun.swing.table.DefaultTableCellHeaderRenderer;
import topLevelGUI.SunFishFrame;
import element.sequence.*;
import guiWidgets.StringUtilities;
/**
* A table that houses seq stats as rows and sequencegroups or partitions as columns. StatTables are currently
* only used in the SequenceGroupSummary to display various sg. statistics associated with one or more sequence groups.
* @author brendan
*
*/
public class StatTable extends JPanel {
JScrollPane scrollPane;
JTable table;
StatTableModel tableModel;
List<SequenceGroup> currentSGs = new ArrayList<SequenceGroup>(10);
List<StatTableColumn> statColumns = new ArrayList<StatTableColumn>();
List<SGCalculator> currentStats = new ArrayList<SGCalculator>(10);
static Font rowHeaderFont = new Font("Sans", Font.PLAIN, 11);
static Font colHeaderFont = new Font("Sans", Font.PLAIN, 11);
static Font valFont = new Font("Sans", Font.PLAIN, 11);
static Color textShadowColor = new Color(0.9f, 0.9f, 0.9f, 0.3f);
static Color stripeColor = new Color(56, 56, 56, 20);
StatTableRowHeader rowHeader;
HeaderRenderer headerRenderer = new HeaderRenderer();
CellRenderer cellRenderer = new CellRenderer();
JPopupMenu popup;
Point popupPosition;
public StatTable() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setBackground(Color.white);
table = new JTable();
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
tableModel = new StatTableModel();
table.setModel(tableModel);
table.setOpaque(false);
table.setFont(valFont);
table.setDefaultRenderer(Object.class, cellRenderer);
table.setDefaultRenderer(String.class, cellRenderer);
table.setRowHeight(20);
scrollPane = new JScrollPane(table);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
JPanel leftPanel = new JPanel();
leftPanel.setOpaque(false);
leftPanel.setMaximumSize(new Dimension(10, Integer.MAX_VALUE));
this.add(leftPanel);
this.add(scrollPane);
scrollPane.setPreferredSize(new Dimension(200, 200));
this.add(Box.createGlue());
rowHeader = new StatTableRowHeader(table, 150);
rowHeader.setShowHorizontalLines(false);
rowHeader.setFont(rowHeaderFont);
scrollPane.setRowHeaderView(rowHeader);
scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
scrollPane.setBorder(BorderFactory.createEmptyBorder());
table.setBorder(BorderFactory.createEmptyBorder());
//Construct popup
popup = new JPopupMenu();
popup.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY) );
popup.setBackground(new Color(100,100,100) );
JMenuItem popupRemove = new JMenuItem("Remove column");
popupRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeColumnFromPopup();
}
});
popup.add(popupRemove);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.isPopupTrigger() || (SunFishFrame.getSunFishFrame().onAMac() && evt.isControlDown()) || (evt.getButton()==MouseEvent.BUTTON3)) {
popupPosition = evt.getPoint();
popup.show(table, evt.getX(), evt.getY());
}
}
});
}
/**
* Returns the column index underneath the given point
* @param p
* @return
*/
private int getColumnForPoint(Point p) {
//System.out.println("Point x: " + p.x + " column 0 width: " + table.getColumn( sgColumnNames.get(0)).getWidth());
int x = p.x;
if (x < table.getColumn( statColumns.get(0).getName()).getWidth())
return 0;
for(int i=1; i<table.getColumnCount(); i++) {
//System.out.println("Column " + i + " width: " + table.getColumn( sgColumnNames.get(i)).getWidth());
x -= table.getColumn( statColumns.get(i-1).getName()).getWidth();
if (x < table.getColumn(statColumns.get(i).getName()).getWidth())
return i;
}
System.out.println("Could not find column for point: " + p.x);
return -1;
}
/**
* Removes a column from the table based on the position of the popup.
*/
protected void removeColumnFromPopup() {
int column = getColumnForPoint(popupPosition);
if (column>-1) {
//System.out.println("Point: " + popupPosition.getX() + " column index: " + column + " name: " + sgColumnNames.get(column));
removeColumn(statColumns.get(column).getName());
}
}
private void emitAll() {
System.out.println("Table columns " + table.getColumnCount() + " stat columns: " + statColumns.size() );
for(int i=0; i<statColumns.size(); i++) {
System.out.println(i + " : " + statColumns.get(i).getName() );
}
System.out.println();
}
/**
* Return the index of the StatColumn with the given name
* @param sg
* @return
*/
private int columnForName(String columnName) {
for(int i=0; i<statColumns.size(); i++) {
if (statColumns.get(i).getName().equals(columnName)) {
return i;
}
}
return -1;
}
/**
* Return the index of the StatColumn that refers to the given SequenceGroup
* @param sg
* @return
*/
// private int columnForSG(SequenceGroup sg) {
// for(int i=0; i<statColumns.size(); i++) {
// if (statColumns.get(i).getSG()==sg) {
// return i;
// }
// }
// return -1;
// }
/**
* Remove the column with the given name.
* @param columnName
*/
protected void removeColumn(String columnName) {
int index = columnForName(columnName);
if (index == -1) {
SunFishFrame.getSunFishFrame().getLogger().info("Could not remove StatTableColumn with name: " + columnName + ", no column with that name");
return;
}
statColumns.get(index).clearListeners();
statColumns.remove(index);
layoutColumns();
// System.out.println("State after removal, column count: " + tableModel.getColumnCount() );
// emitAll();
table.repaint();
}
// public List<SequenceGroup> getSequenceGroups() {
// return currentSGs;
// }
/**
* Add a new sequence group to be displayed as a column of this table. The header of the column is
* set to whatever 'name' is, and the width of the column is based on the width of the string
* @param sg
* @param name
*/
public void addSequenceGroup(SequenceGroup sg, String name) {
currentSGs.add(sg);
StatTableColumn newCol = new StatTableColumn(this, sg, name, currentStats);
statColumns.add(newCol);
//System.out.println(" \n Adding group : " + name + " column count before add : " + tableModel.getColumnCount());
layoutColumns();
//emitAll();
}
/**
* Add a new stat column with the same sequence group as col, but tracking the given partition index
* @param col
* @param newPartitionNumber
*/
public void handlePartitionAdd(StatTableColumn col, int newPartitionNumber) {
//First see if there's already a column with the same sg and partition number
for(StatTableColumn tCol : statColumns) {
if (tCol.getSG()==col.getSG() && tCol.getPartitionIndex()==newPartitionNumber) {
return;
}
}
//There's not a column tracking the new partition, so add one
SequenceGroup sg = col.getSG();
StatTableColumn newCol = new StatTableColumn(this, sg, col.getName() + " Par. " + partitionLetters[newPartitionNumber], currentStats, newPartitionNumber);
statColumns.add(newCol);
layoutColumns();
}
public void handlePartitionRemoved(StatTableColumn col) {
//See if there are any columns whose partition index does not match a partition in
//the sequence group
SequenceGroup sg = col.getSG();
List<StatTableColumn> colsToRemove = new ArrayList<StatTableColumn>();
for(StatTableColumn tCol : statColumns) {
if (tCol.getSG()==sg) {
if (sg.getPartitionSiteCount(tCol.getPartitionIndex() )==0) {
colsToRemove.add(tCol);
}
}
}
for(int i=0; i<colsToRemove.size(); i++)
statColumns.remove(colsToRemove.get(i));
layoutColumns();
}
/**
* This is called after any change to the stat columns. We refresh the model we new data to reflect any
* changes that may have occurred.
*/
private void layoutColumns() {
int totWidth = rowHeader.getWidth();
tableModel = new StatTableModel();
//System.out.println("Regenerating all columns...");
//Add a new column onto the end of each row
for(int j=0; j<statColumns.size(); j++) {
Object[] values = statColumns.get(j).getValues();
tableModel.addColumn(statColumns.get(j).getName(), values);
System.out.println("Added column " + j + " with name: " + statColumns.get(j).getName());
}
table.setModel( tableModel);
FontMetrics fm = table.getFontMetrics(colHeaderFont);
for(int i=0; i<tableModel.getColumnCount(); i++) {
String colName = statColumns.get(i).getName();
table.getColumnModel().getColumn( i ).setHeaderRenderer(new HeaderRenderer());
table.getColumnModel().getColumn( i ).setCellRenderer(new CellRenderer());
int colWidth = fm.stringWidth( colName )+10;
colWidth = Math.min(200, colWidth);
table.getColumnModel().getColumn( i ).setMinWidth(colWidth);
table.getColumnModel().getColumn( i ).setPreferredWidth(colWidth);
table.getColumnModel().getColumn( i ).setMaxWidth(Integer.MAX_VALUE);
table.getColumnModel().getColumn( i ).setResizable(true);
totWidth += colWidth;
//System.out.println("Setting header width for col " + colName + " to : " + colWidth);
}
scrollPane.setPreferredSize(new Dimension(totWidth, scrollPane.getHeight() ));
scrollPane.getViewport().setPreferredSize(new Dimension(totWidth, scrollPane.getHeight() ));
table.doLayout();
this.revalidate();
if (table.getWidth()>scrollPane.getWidth())
scrollPane.getHorizontalScrollBar().setVisible(true);
else
scrollPane.getHorizontalScrollBar().setVisible(false);
table.repaint();
System.out.println("Added " + statColumns.size() + " groups, table column count: " + table.getColumnModel().getColumnCount());
}
/**
* Adds a new statistic as a row
* @param statwww
*/
public void addStatistic(SGCalculator stat) {
currentStats.add(stat);
for(StatTableColumn statCol : statColumns)
statCol.addStatistic(stat);
rowHeader.addName(stat.getName());
layoutColumns();
}
/**
* Returns a list of the SG calculators currently used by this stat table
* @return
*/
public List<SGCalculator> getCalculators() {
return currentStats;
}
/**
* Removes this sequence group from the table. At least one column is removed from the
* table when this happens.
* @param sg
*/
public void removeSequenceGroup(SequenceGroup sg) {
int index = -1;
for(int i=0; i<statColumns.size(); i++) {
if (statColumns.get(i).getSG() == sg) {
index = i;
break;
}
}
statColumns.get(index).clearListeners();
statColumns.remove(index);
layoutColumns();
repaint();
}
/**
* Removes this statistic from the table. One row is removed from the table when
* this happens.
* @param stat
*/
// public void removeStatistic(SeqStatistic stat) {
//
// }
/**
* Remove all listeners from all the sequence groups
*/
public void clearAllListeners() {
for(StatTableColumn col : statColumns)
col.clearListeners();
}
/**
* A custom.. or not, table model. We may customize this someday.
* @author brendan
*
*/
class StatTableModel extends DefaultTableModel {
public boolean isCellEditable(int row, int col) {
return false;
}
}
/**
* Handles the drawing of the column headers
* @author brendan
*
*/
class HeaderRenderer extends JLabel implements TableCellRenderer {
int drawCloseBoxForColumn = -1;
int column = 0;
public HeaderRenderer() {
setBackground(Color.white);
this.setHorizontalTextPosition(JLabel.CENTER);
setFont(colHeaderFont);
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (statColumns.size()<2)
setText("");
else
setText(value.toString());
this.column = column;
return this;
}
public void paintComponent(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
g.setFont(colHeaderFont);
int textWidth = g.getFontMetrics().stringWidth(getText());
g.drawString(getText(), 3, getFont().getSize());
if (drawCloseBoxForColumn == column) {
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(2.2f));
int xPos = 3+g2d.getFontMetrics().stringWidth(getText());
if (xPos > getWidth()-10)
xPos = getWidth()-10;
int rectSize = 8;
g2d.drawLine(xPos, 1, xPos+rectSize, rectSize);
g2d.drawLine(xPos, rectSize, xPos+rectSize, 1);
}
}
}
/**
* Handles the drawing of individual values in the table
* @author brendan
*
*/
class CellRenderer extends DefaultTableCellRenderer {
int row;
public CellRenderer() {
setBackground(Color.white);
this.setHorizontalTextPosition(RIGHT);
setFont(valFont);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.row = row;
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
public void paintComponent(Graphics g) {
if (row%2==0)
g.setColor(getBackground());
else
g.setColor(stripeColor);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.black);
g.setFont(getFont());
int height = g.getFontMetrics().getHeight();
int width = g.getFontMetrics().stringWidth(getText());
g.drawString(getText(), Math.max(2, 40-width/2), getHeight()/2+height/2-2);
g.setColor(textShadowColor);
g.drawString(getText(), Math.max(2, 40-width/2)+1, getHeight()/2+height/2-1);
}
}
private char[] partitionLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'};
}
| 15,319 | 0.692082 | 0.684248 | 521 | 28.40307 | 28.961798 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.485605 | false | false | 0 |
190666d1230ea825a903c0f5652b73da649470d1 | 35,330,401,022,255 | 89ac798d2b856214c60d87ba7eae869d0e898868 | /src/main/java/io/cimi/compactjson/Encoder.java | 548fd6c927c178dd27574dbcd797d88df69e0aba | [] | no_license | cimi/compact-json-eval | https://github.com/cimi/compact-json-eval | 384c17998233ff3b8325df5e810f2f78acc00653 | 48f4e8a882a2360db437fb388b09076f729c927f | refs/heads/master | 2021-01-10T13:43:19.280000 | 2018-10-19T10:36:06 | 2018-10-19T10:36:06 | 48,495,583 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.cimi.compactjson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public abstract class Encoder extends AbstractProcessor {
protected Encoder(String extension) {
super(extension);
}
protected abstract ObjectMapper buildObjectMapper();
@Override
public File process(File inputFile) {
ObjectMapper encodedMapper = buildObjectMapper();
File outputFile = new File(inputFile.getAbsolutePath() + "." + extension);
try {
Map<String, Object> content = Utils.parseJsonFile(inputFile);
encodedMapper.writeValue(outputFile, content);
} catch (IOException e) {
Throwables.propagate(e);
}
return outputFile;
}
}
| UTF-8 | Java | 849 | java | Encoder.java | Java | [] | null | [] | package io.cimi.compactjson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public abstract class Encoder extends AbstractProcessor {
protected Encoder(String extension) {
super(extension);
}
protected abstract ObjectMapper buildObjectMapper();
@Override
public File process(File inputFile) {
ObjectMapper encodedMapper = buildObjectMapper();
File outputFile = new File(inputFile.getAbsolutePath() + "." + extension);
try {
Map<String, Object> content = Utils.parseJsonFile(inputFile);
encodedMapper.writeValue(outputFile, content);
} catch (IOException e) {
Throwables.propagate(e);
}
return outputFile;
}
}
| 849 | 0.683157 | 0.683157 | 30 | 27.299999 | 23.696905 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.533333 | false | false | 0 |
508a3de80ac1c9531459358a59d8ad0d08e42f43 | 34,273,839,077,001 | 03ec794ad2b54cfe40ea603cb1455d83dcf9cadc | /ebankCenter/src/test/java/com/amway/ebank/test/controller/base/BaseControllerTest.java | ed71b60735a1a8cb16552aae9126327f8431be19 | [] | no_license | moutainhigh/paymentCenter | https://github.com/moutainhigh/paymentCenter | 32d1676d740e11b951a5790ac5d03c5920e2782c | 661387a96dc78b7a7bb549ccd32dd7617059dc8a | refs/heads/master | 2020-09-04T06:34:30.586000 | 2019-11-04T10:36:05 | 2019-11-04T10:36:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.amway.ebank.test.controller.base;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = {"classpath:dispatcher-servlet.xml","classpath:spring-mybatis.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
@Test
public void test(){
System.out.println("BaseControllerTest.test");
}
}
| UTF-8 | Java | 648 | java | BaseControllerTest.java | Java | [] | null | [] | package com.amway.ebank.test.controller.base;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = {"classpath:dispatcher-servlet.xml","classpath:spring-mybatis.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
@Test
public void test(){
System.out.println("BaseControllerTest.test");
}
}
| 648 | 0.837963 | 0.828704 | 16 | 39.5 | 34.31472 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 0 |
6876940dcd7ff9e1365308f6465472d704bc31cb | 33,801,392,677,132 | 3a59c08c56fdf84260c22aecee982c4e5bd326c1 | /src/main/java/ru/kilg/wb/domain/project/Note.java | 09e620cc432b3bfc7fe64d6c6bf4d0c94e3e4cc8 | [] | no_license | kilg-kory/WB001 | https://github.com/kilg-kory/WB001 | df7ec40af1520e4bd630adb8c6ea8bbe34ebc571 | 4ca12dc5892ca7358c6b5355ce1306f971f4d69b | refs/heads/master | 2020-04-24T06:16:22.808000 | 2019-03-07T17:32:31 | 2019-03-07T17:32:31 | 171,759,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.kilg.wb.domain.project;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
/**
* WB001
* Note - [Description]
*
* @author KIlG
* @version 0.1
* Create 05.03.19
*/
@Entity
@Data
@Inheritance(strategy = InheritanceType.JOINED)
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private Date createDate;
}
| UTF-8 | Java | 426 | java | Note.java | Java | [
{
"context": "/**\n * WB001\n * Note - [Description]\n *\n * @author KIlG\n * @version 0.1\n * Create 05.03.19\n */\n@Entity\n@D",
"end": 164,
"score": 0.9721871018409729,
"start": 160,
"tag": "USERNAME",
"value": "KIlG"
}
] | null | [] | package ru.kilg.wb.domain.project;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
/**
* WB001
* Note - [Description]
*
* @author KIlG
* @version 0.1
* Create 05.03.19
*/
@Entity
@Data
@Inheritance(strategy = InheritanceType.JOINED)
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private Date createDate;
}
| 426 | 0.687793 | 0.661972 | 28 | 14.214286 | 14.036577 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 0 |
bef0f54c132f475a7279e84d81af6881dec1fcee | 36,541,581,800,120 | 4057115643c9bfd8ed6ca7148a6404de4c050e0a | /src/main/java/com/inspirenetz/api/core/dictionary/PaymentStatusStatus.java | 2edeec083ef68779596c51aa69d1dd4f5ac616b1 | [] | no_license | systemsarchitecture/java-spring | https://github.com/systemsarchitecture/java-spring | 38032a8d941f70ca588fce842fb056cef3537065 | 8462e54291e8a45b3b4a97f303490e2510d62a8e | refs/heads/master | 2022-05-20T12:18:08.190000 | 2017-01-05T10:54:31 | 2017-01-05T10:54:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inspirenetz.api.core.dictionary;
/**
* Created by sandheepgr on 16/8/14.
*/
public class PaymentStatusStatus {
public static final int APPROVED =1 ;
public static final int FAILED = 2;
public static final int UNKNOWN = 3;
public static final int CANCELLED = 4;
public static final int REFUNDED = 5;
public static final int CAPTURED = 6;
public static final int COMPLETED = 7;
}
| UTF-8 | Java | 423 | java | PaymentStatusStatus.java | Java | [
{
"context": "nspirenetz.api.core.dictionary;\n\n/**\n * Created by sandheepgr on 16/8/14.\n */\npublic class PaymentStatusStatus ",
"end": 74,
"score": 0.9996712803840637,
"start": 64,
"tag": "USERNAME",
"value": "sandheepgr"
}
] | null | [] | package com.inspirenetz.api.core.dictionary;
/**
* Created by sandheepgr on 16/8/14.
*/
public class PaymentStatusStatus {
public static final int APPROVED =1 ;
public static final int FAILED = 2;
public static final int UNKNOWN = 3;
public static final int CANCELLED = 4;
public static final int REFUNDED = 5;
public static final int CAPTURED = 6;
public static final int COMPLETED = 7;
}
| 423 | 0.699764 | 0.671395 | 16 | 25.4375 | 18.950491 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
9c76f426cd2b114fc23a728592865b8b261711b5 | 18,013,092,905,342 | 59408d7a4c005d19e25c8b05d6b9c9a23ab17ea2 | /JavaFundamental/Lab196.java | f11f28449c5265275dc90980ec70873276650707 | [] | no_license | saketkumar123/Java_Fundamental | https://github.com/saketkumar123/Java_Fundamental | 85ebb4b6507b69f31562428f2da90ecfc326b849 | 8f8082e2de500847509bd16facca572c44e5e7c5 | refs/heads/master | 2021-01-13T02:50:33.193000 | 2016-12-22T13:00:45 | 2016-12-22T13:00:45 | 77,144,616 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Lab196
{
public static void main(String[] args)
{
String arr[] = new String[3];
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
System.out.println("********");
arr[0] = "Java";
arr[1] = "Learning";
arr[2] = "Center";
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
/*
Output
======
E:\JLC Fundamental Lab>javac Lab196.java
E:\JLC Fundamental Lab>java Lab196
null
null
null
********
Java
Learning
Center
*/ | UTF-8 | Java | 461 | java | Lab196.java | Java | [] | null | [] | class Lab196
{
public static void main(String[] args)
{
String arr[] = new String[3];
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
System.out.println("********");
arr[0] = "Java";
arr[1] = "Learning";
arr[2] = "Center";
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
/*
Output
======
E:\JLC Fundamental Lab>javac Lab196.java
E:\JLC Fundamental Lab>java Lab196
null
null
null
********
Java
Learning
Center
*/ | 461 | 0.609544 | 0.577007 | 31 | 13.903226 | 13.591636 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.096774 | false | false | 0 |
4d93ade210ced0ba5b111130a633944fa7a7d3ce | 34,668,976,071,647 | d50ec43131be668368200315d1d9d307071d5385 | /keanu-project/src/test/java/io/improbable/keanu/algorithms/variational/optimizer/gradient/testcase/SumGaussianTestCase.java | 43b5f9958f5aa728ccf4eb96c9e882453baaa7a2 | [
"MIT"
] | permissive | improbable-research/keanu | https://github.com/improbable-research/keanu | 605e4dc6a2f90f095c2c1ec91fa1222ae8d04530 | 99de10a15e0d4b33d323093a5cc2dd10b31c9954 | refs/heads/develop | 2023-04-14T01:17:29.130000 | 2021-09-21T10:24:48 | 2021-09-21T10:24:48 | 128,393,918 | 155 | 47 | MIT | false | 2023-04-12T00:18:07 | 2018-04-06T12:48:36 | 2023-04-05T06:31:03 | 2023-04-12T00:18:07 | 15,477 | 149 | 35 | 11 | Java | false | false | package io.improbable.keanu.algorithms.variational.optimizer.gradient.testcase;
import io.improbable.keanu.algorithms.Variable;
import io.improbable.keanu.algorithms.variational.optimizer.FitnessFunction;
import io.improbable.keanu.algorithms.variational.optimizer.FitnessFunctionGradient;
import io.improbable.keanu.algorithms.variational.optimizer.OptimizedResult;
import io.improbable.keanu.algorithms.variational.optimizer.ProbabilityFitness;
import io.improbable.keanu.algorithms.variational.optimizer.nongradient.testcase.NonGradientOptimizationAlgorithmTestCase;
import io.improbable.keanu.network.BayesianNetwork;
import io.improbable.keanu.network.KeanuProbabilisticModelWithGradient;
import io.improbable.keanu.vertices.tensor.number.floating.dbl.DoubleVertex;
import io.improbable.keanu.vertices.tensor.number.floating.dbl.probabilistic.GaussianVertex;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SumGaussianTestCase implements GradientOptimizationAlgorithmTestCase, NonGradientOptimizationAlgorithmTestCase {
private final DoubleVertex A;
private final DoubleVertex B;
private final ProbabilityFitness probabilityFitness;
private final KeanuProbabilisticModelWithGradient model;
public SumGaussianTestCase(ProbabilityFitness probabilityFitness) {
this.probabilityFitness = probabilityFitness;
A = new GaussianVertex(20.0, 1.0);
B = new GaussianVertex(20.0, 1.0);
A.setValue(20.0);
B.setAndCascade(20.0);
DoubleVertex Cobserved = new GaussianVertex(A.plus(B), 1.0);
Cobserved.observe(46.0);
BayesianNetwork bayesianNetwork = new BayesianNetwork(Arrays.asList(A, B, Cobserved));
model = new KeanuProbabilisticModelWithGradient(bayesianNetwork);
}
private void assertMLE(OptimizedResult result) {
double maxA = result.getValueFor(A.getReference()).scalar();
double maxB = result.getValueFor(B.getReference()).scalar();
assertEquals(46, maxA + maxB, 0.1);
}
private void assertMAP(OptimizedResult result) {
double maxA = result.getValueFor(A.getReference()).scalar();
double maxB = result.getValueFor(B.getReference()).scalar();
assertEquals(22, maxA, 0.1);
assertEquals(22, maxB, 0.1);
}
@Override
public FitnessFunction getFitnessFunction() {
return probabilityFitness.getFitnessFunction(model);
}
@Override
public FitnessFunctionGradient getFitnessFunctionGradient() {
return probabilityFitness.getFitnessFunctionGradient(model);
}
@Override
public List<? extends Variable> getVariables() {
return model.getLatentVariables();
}
@Override
public void assertResult(OptimizedResult result) {
if (probabilityFitness.equals(ProbabilityFitness.MLE)) {
assertMLE(result);
} else {
assertMAP(result);
}
}
}
| UTF-8 | Java | 2,982 | java | SumGaussianTestCase.java | Java | [] | null | [] | package io.improbable.keanu.algorithms.variational.optimizer.gradient.testcase;
import io.improbable.keanu.algorithms.Variable;
import io.improbable.keanu.algorithms.variational.optimizer.FitnessFunction;
import io.improbable.keanu.algorithms.variational.optimizer.FitnessFunctionGradient;
import io.improbable.keanu.algorithms.variational.optimizer.OptimizedResult;
import io.improbable.keanu.algorithms.variational.optimizer.ProbabilityFitness;
import io.improbable.keanu.algorithms.variational.optimizer.nongradient.testcase.NonGradientOptimizationAlgorithmTestCase;
import io.improbable.keanu.network.BayesianNetwork;
import io.improbable.keanu.network.KeanuProbabilisticModelWithGradient;
import io.improbable.keanu.vertices.tensor.number.floating.dbl.DoubleVertex;
import io.improbable.keanu.vertices.tensor.number.floating.dbl.probabilistic.GaussianVertex;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SumGaussianTestCase implements GradientOptimizationAlgorithmTestCase, NonGradientOptimizationAlgorithmTestCase {
private final DoubleVertex A;
private final DoubleVertex B;
private final ProbabilityFitness probabilityFitness;
private final KeanuProbabilisticModelWithGradient model;
public SumGaussianTestCase(ProbabilityFitness probabilityFitness) {
this.probabilityFitness = probabilityFitness;
A = new GaussianVertex(20.0, 1.0);
B = new GaussianVertex(20.0, 1.0);
A.setValue(20.0);
B.setAndCascade(20.0);
DoubleVertex Cobserved = new GaussianVertex(A.plus(B), 1.0);
Cobserved.observe(46.0);
BayesianNetwork bayesianNetwork = new BayesianNetwork(Arrays.asList(A, B, Cobserved));
model = new KeanuProbabilisticModelWithGradient(bayesianNetwork);
}
private void assertMLE(OptimizedResult result) {
double maxA = result.getValueFor(A.getReference()).scalar();
double maxB = result.getValueFor(B.getReference()).scalar();
assertEquals(46, maxA + maxB, 0.1);
}
private void assertMAP(OptimizedResult result) {
double maxA = result.getValueFor(A.getReference()).scalar();
double maxB = result.getValueFor(B.getReference()).scalar();
assertEquals(22, maxA, 0.1);
assertEquals(22, maxB, 0.1);
}
@Override
public FitnessFunction getFitnessFunction() {
return probabilityFitness.getFitnessFunction(model);
}
@Override
public FitnessFunctionGradient getFitnessFunctionGradient() {
return probabilityFitness.getFitnessFunctionGradient(model);
}
@Override
public List<? extends Variable> getVariables() {
return model.getLatentVariables();
}
@Override
public void assertResult(OptimizedResult result) {
if (probabilityFitness.equals(ProbabilityFitness.MLE)) {
assertMLE(result);
} else {
assertMAP(result);
}
}
}
| 2,982 | 0.745808 | 0.734742 | 84 | 34.5 | 32.36676 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false | 0 |
228f1de5f82ddc0032a04d050a20485b8c065008 | 38,122,129,747,991 | c6f63cf4524567f12d4226b9cdcbfee9c5c3d95c | /gen/main/java/org/hl7/fhir/impl/RiskAssessmentImpl.java | 7775f84a8a2d08637299ec9b6a7a4655398a74a0 | [] | no_license | usnistgov/fhir.emf | https://github.com/usnistgov/fhir.emf | 83852f9388619fa7b76c05dd725c311c96e733e6 | affea7e1fc2b53cb67e706f47264b408909b2253 | refs/heads/master | 2021-01-11T02:40:21.282000 | 2016-10-21T18:51:25 | 2016-10-21T18:51:25 | 70,912,620 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*/
package org.hl7.fhir.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.hl7.fhir.CodeableConcept;
import org.hl7.fhir.DateTime;
import org.hl7.fhir.FhirPackage;
import org.hl7.fhir.Identifier;
import org.hl7.fhir.Reference;
import org.hl7.fhir.RiskAssessment;
import org.hl7.fhir.RiskAssessmentPrediction;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Risk Assessment</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getSubject <em>Subject</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getDate <em>Date</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getCondition <em>Condition</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getEncounter <em>Encounter</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getPerformer <em>Performer</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getIdentifier <em>Identifier</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getMethod <em>Method</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getBasis <em>Basis</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getPrediction <em>Prediction</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getMitigation <em>Mitigation</em>}</li>
* </ul>
*
* @generated
*/
public class RiskAssessmentImpl extends DomainResourceImpl implements RiskAssessment {
/**
* The cached value of the '{@link #getSubject() <em>Subject</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSubject()
* @generated
* @ordered
*/
protected Reference subject;
/**
* The cached value of the '{@link #getDate() <em>Date</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDate()
* @generated
* @ordered
*/
protected DateTime date;
/**
* The cached value of the '{@link #getCondition() <em>Condition</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCondition()
* @generated
* @ordered
*/
protected Reference condition;
/**
* The cached value of the '{@link #getEncounter() <em>Encounter</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEncounter()
* @generated
* @ordered
*/
protected Reference encounter;
/**
* The cached value of the '{@link #getPerformer() <em>Performer</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPerformer()
* @generated
* @ordered
*/
protected Reference performer;
/**
* The cached value of the '{@link #getIdentifier() <em>Identifier</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifier()
* @generated
* @ordered
*/
protected Identifier identifier;
/**
* The cached value of the '{@link #getMethod() <em>Method</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMethod()
* @generated
* @ordered
*/
protected CodeableConcept method;
/**
* The cached value of the '{@link #getBasis() <em>Basis</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBasis()
* @generated
* @ordered
*/
protected EList<Reference> basis;
/**
* The cached value of the '{@link #getPrediction() <em>Prediction</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPrediction()
* @generated
* @ordered
*/
protected EList<RiskAssessmentPrediction> prediction;
/**
* The cached value of the '{@link #getMitigation() <em>Mitigation</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMitigation()
* @generated
* @ordered
*/
protected org.hl7.fhir.String mitigation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RiskAssessmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return FhirPackage.eINSTANCE.getRiskAssessment();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getSubject() {
return subject;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSubject(Reference newSubject, NotificationChain msgs) {
Reference oldSubject = subject;
subject = newSubject;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__SUBJECT, oldSubject, newSubject);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSubject(Reference newSubject) {
if (newSubject != subject) {
NotificationChain msgs = null;
if (subject != null)
msgs = ((InternalEObject)subject).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__SUBJECT, null, msgs);
if (newSubject != null)
msgs = ((InternalEObject)newSubject).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__SUBJECT, null, msgs);
msgs = basicSetSubject(newSubject, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__SUBJECT, newSubject, newSubject));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DateTime getDate() {
return date;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDate(DateTime newDate, NotificationChain msgs) {
DateTime oldDate = date;
date = newDate;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__DATE, oldDate, newDate);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDate(DateTime newDate) {
if (newDate != date) {
NotificationChain msgs = null;
if (date != null)
msgs = ((InternalEObject)date).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__DATE, null, msgs);
if (newDate != null)
msgs = ((InternalEObject)newDate).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__DATE, null, msgs);
msgs = basicSetDate(newDate, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__DATE, newDate, newDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getCondition() {
return condition;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCondition(Reference newCondition, NotificationChain msgs) {
Reference oldCondition = condition;
condition = newCondition;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__CONDITION, oldCondition, newCondition);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCondition(Reference newCondition) {
if (newCondition != condition) {
NotificationChain msgs = null;
if (condition != null)
msgs = ((InternalEObject)condition).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__CONDITION, null, msgs);
if (newCondition != null)
msgs = ((InternalEObject)newCondition).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__CONDITION, null, msgs);
msgs = basicSetCondition(newCondition, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__CONDITION, newCondition, newCondition));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getEncounter() {
return encounter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEncounter(Reference newEncounter, NotificationChain msgs) {
Reference oldEncounter = encounter;
encounter = newEncounter;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__ENCOUNTER, oldEncounter, newEncounter);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEncounter(Reference newEncounter) {
if (newEncounter != encounter) {
NotificationChain msgs = null;
if (encounter != null)
msgs = ((InternalEObject)encounter).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__ENCOUNTER, null, msgs);
if (newEncounter != null)
msgs = ((InternalEObject)newEncounter).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__ENCOUNTER, null, msgs);
msgs = basicSetEncounter(newEncounter, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__ENCOUNTER, newEncounter, newEncounter));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getPerformer() {
return performer;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPerformer(Reference newPerformer, NotificationChain msgs) {
Reference oldPerformer = performer;
performer = newPerformer;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__PERFORMER, oldPerformer, newPerformer);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPerformer(Reference newPerformer) {
if (newPerformer != performer) {
NotificationChain msgs = null;
if (performer != null)
msgs = ((InternalEObject)performer).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__PERFORMER, null, msgs);
if (newPerformer != null)
msgs = ((InternalEObject)newPerformer).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__PERFORMER, null, msgs);
msgs = basicSetPerformer(newPerformer, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__PERFORMER, newPerformer, newPerformer));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Identifier getIdentifier() {
return identifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetIdentifier(Identifier newIdentifier, NotificationChain msgs) {
Identifier oldIdentifier = identifier;
identifier = newIdentifier;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__IDENTIFIER, oldIdentifier, newIdentifier);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdentifier(Identifier newIdentifier) {
if (newIdentifier != identifier) {
NotificationChain msgs = null;
if (identifier != null)
msgs = ((InternalEObject)identifier).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__IDENTIFIER, null, msgs);
if (newIdentifier != null)
msgs = ((InternalEObject)newIdentifier).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__IDENTIFIER, null, msgs);
msgs = basicSetIdentifier(newIdentifier, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__IDENTIFIER, newIdentifier, newIdentifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CodeableConcept getMethod() {
return method;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMethod(CodeableConcept newMethod, NotificationChain msgs) {
CodeableConcept oldMethod = method;
method = newMethod;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__METHOD, oldMethod, newMethod);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMethod(CodeableConcept newMethod) {
if (newMethod != method) {
NotificationChain msgs = null;
if (method != null)
msgs = ((InternalEObject)method).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__METHOD, null, msgs);
if (newMethod != null)
msgs = ((InternalEObject)newMethod).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__METHOD, null, msgs);
msgs = basicSetMethod(newMethod, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__METHOD, newMethod, newMethod));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Reference> getBasis() {
if (basis == null) {
basis = new EObjectContainmentEList<Reference>(Reference.class, this, FhirPackage.RISK_ASSESSMENT__BASIS);
}
return basis;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RiskAssessmentPrediction> getPrediction() {
if (prediction == null) {
prediction = new EObjectContainmentEList<RiskAssessmentPrediction>(RiskAssessmentPrediction.class, this, FhirPackage.RISK_ASSESSMENT__PREDICTION);
}
return prediction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.hl7.fhir.String getMitigation() {
return mitigation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMitigation(org.hl7.fhir.String newMitigation, NotificationChain msgs) {
org.hl7.fhir.String oldMitigation = mitigation;
mitigation = newMitigation;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__MITIGATION, oldMitigation, newMitigation);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMitigation(org.hl7.fhir.String newMitigation) {
if (newMitigation != mitigation) {
NotificationChain msgs = null;
if (mitigation != null)
msgs = ((InternalEObject)mitigation).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__MITIGATION, null, msgs);
if (newMitigation != null)
msgs = ((InternalEObject)newMitigation).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__MITIGATION, null, msgs);
msgs = basicSetMitigation(newMitigation, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__MITIGATION, newMitigation, newMitigation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return basicSetSubject(null, msgs);
case FhirPackage.RISK_ASSESSMENT__DATE:
return basicSetDate(null, msgs);
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return basicSetCondition(null, msgs);
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return basicSetEncounter(null, msgs);
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return basicSetPerformer(null, msgs);
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return basicSetIdentifier(null, msgs);
case FhirPackage.RISK_ASSESSMENT__METHOD:
return basicSetMethod(null, msgs);
case FhirPackage.RISK_ASSESSMENT__BASIS:
return ((InternalEList<?>)getBasis()).basicRemove(otherEnd, msgs);
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return ((InternalEList<?>)getPrediction()).basicRemove(otherEnd, msgs);
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return basicSetMitigation(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return getSubject();
case FhirPackage.RISK_ASSESSMENT__DATE:
return getDate();
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return getCondition();
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return getEncounter();
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return getPerformer();
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return getIdentifier();
case FhirPackage.RISK_ASSESSMENT__METHOD:
return getMethod();
case FhirPackage.RISK_ASSESSMENT__BASIS:
return getBasis();
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return getPrediction();
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return getMitigation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
setSubject((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__DATE:
setDate((DateTime)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
setCondition((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
setEncounter((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
setPerformer((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
setIdentifier((Identifier)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__METHOD:
setMethod((CodeableConcept)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__BASIS:
getBasis().clear();
getBasis().addAll((Collection<? extends Reference>)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
getPrediction().clear();
getPrediction().addAll((Collection<? extends RiskAssessmentPrediction>)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
setMitigation((org.hl7.fhir.String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
setSubject((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__DATE:
setDate((DateTime)null);
return;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
setCondition((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
setEncounter((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
setPerformer((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
setIdentifier((Identifier)null);
return;
case FhirPackage.RISK_ASSESSMENT__METHOD:
setMethod((CodeableConcept)null);
return;
case FhirPackage.RISK_ASSESSMENT__BASIS:
getBasis().clear();
return;
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
getPrediction().clear();
return;
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
setMitigation((org.hl7.fhir.String)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return subject != null;
case FhirPackage.RISK_ASSESSMENT__DATE:
return date != null;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return condition != null;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return encounter != null;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return performer != null;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return identifier != null;
case FhirPackage.RISK_ASSESSMENT__METHOD:
return method != null;
case FhirPackage.RISK_ASSESSMENT__BASIS:
return basis != null && !basis.isEmpty();
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return prediction != null && !prediction.isEmpty();
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return mitigation != null;
}
return super.eIsSet(featureID);
}
} //RiskAssessmentImpl
| UTF-8 | Java | 22,428 | java | RiskAssessmentImpl.java | Java | [] | null | [] | /**
*/
package org.hl7.fhir.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.hl7.fhir.CodeableConcept;
import org.hl7.fhir.DateTime;
import org.hl7.fhir.FhirPackage;
import org.hl7.fhir.Identifier;
import org.hl7.fhir.Reference;
import org.hl7.fhir.RiskAssessment;
import org.hl7.fhir.RiskAssessmentPrediction;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Risk Assessment</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getSubject <em>Subject</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getDate <em>Date</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getCondition <em>Condition</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getEncounter <em>Encounter</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getPerformer <em>Performer</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getIdentifier <em>Identifier</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getMethod <em>Method</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getBasis <em>Basis</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getPrediction <em>Prediction</em>}</li>
* <li>{@link org.hl7.fhir.impl.RiskAssessmentImpl#getMitigation <em>Mitigation</em>}</li>
* </ul>
*
* @generated
*/
public class RiskAssessmentImpl extends DomainResourceImpl implements RiskAssessment {
/**
* The cached value of the '{@link #getSubject() <em>Subject</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSubject()
* @generated
* @ordered
*/
protected Reference subject;
/**
* The cached value of the '{@link #getDate() <em>Date</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDate()
* @generated
* @ordered
*/
protected DateTime date;
/**
* The cached value of the '{@link #getCondition() <em>Condition</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCondition()
* @generated
* @ordered
*/
protected Reference condition;
/**
* The cached value of the '{@link #getEncounter() <em>Encounter</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEncounter()
* @generated
* @ordered
*/
protected Reference encounter;
/**
* The cached value of the '{@link #getPerformer() <em>Performer</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPerformer()
* @generated
* @ordered
*/
protected Reference performer;
/**
* The cached value of the '{@link #getIdentifier() <em>Identifier</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIdentifier()
* @generated
* @ordered
*/
protected Identifier identifier;
/**
* The cached value of the '{@link #getMethod() <em>Method</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMethod()
* @generated
* @ordered
*/
protected CodeableConcept method;
/**
* The cached value of the '{@link #getBasis() <em>Basis</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBasis()
* @generated
* @ordered
*/
protected EList<Reference> basis;
/**
* The cached value of the '{@link #getPrediction() <em>Prediction</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPrediction()
* @generated
* @ordered
*/
protected EList<RiskAssessmentPrediction> prediction;
/**
* The cached value of the '{@link #getMitigation() <em>Mitigation</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMitigation()
* @generated
* @ordered
*/
protected org.hl7.fhir.String mitigation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected RiskAssessmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return FhirPackage.eINSTANCE.getRiskAssessment();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getSubject() {
return subject;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSubject(Reference newSubject, NotificationChain msgs) {
Reference oldSubject = subject;
subject = newSubject;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__SUBJECT, oldSubject, newSubject);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSubject(Reference newSubject) {
if (newSubject != subject) {
NotificationChain msgs = null;
if (subject != null)
msgs = ((InternalEObject)subject).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__SUBJECT, null, msgs);
if (newSubject != null)
msgs = ((InternalEObject)newSubject).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__SUBJECT, null, msgs);
msgs = basicSetSubject(newSubject, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__SUBJECT, newSubject, newSubject));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DateTime getDate() {
return date;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDate(DateTime newDate, NotificationChain msgs) {
DateTime oldDate = date;
date = newDate;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__DATE, oldDate, newDate);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDate(DateTime newDate) {
if (newDate != date) {
NotificationChain msgs = null;
if (date != null)
msgs = ((InternalEObject)date).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__DATE, null, msgs);
if (newDate != null)
msgs = ((InternalEObject)newDate).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__DATE, null, msgs);
msgs = basicSetDate(newDate, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__DATE, newDate, newDate));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getCondition() {
return condition;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCondition(Reference newCondition, NotificationChain msgs) {
Reference oldCondition = condition;
condition = newCondition;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__CONDITION, oldCondition, newCondition);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCondition(Reference newCondition) {
if (newCondition != condition) {
NotificationChain msgs = null;
if (condition != null)
msgs = ((InternalEObject)condition).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__CONDITION, null, msgs);
if (newCondition != null)
msgs = ((InternalEObject)newCondition).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__CONDITION, null, msgs);
msgs = basicSetCondition(newCondition, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__CONDITION, newCondition, newCondition));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getEncounter() {
return encounter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetEncounter(Reference newEncounter, NotificationChain msgs) {
Reference oldEncounter = encounter;
encounter = newEncounter;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__ENCOUNTER, oldEncounter, newEncounter);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setEncounter(Reference newEncounter) {
if (newEncounter != encounter) {
NotificationChain msgs = null;
if (encounter != null)
msgs = ((InternalEObject)encounter).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__ENCOUNTER, null, msgs);
if (newEncounter != null)
msgs = ((InternalEObject)newEncounter).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__ENCOUNTER, null, msgs);
msgs = basicSetEncounter(newEncounter, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__ENCOUNTER, newEncounter, newEncounter));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Reference getPerformer() {
return performer;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetPerformer(Reference newPerformer, NotificationChain msgs) {
Reference oldPerformer = performer;
performer = newPerformer;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__PERFORMER, oldPerformer, newPerformer);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPerformer(Reference newPerformer) {
if (newPerformer != performer) {
NotificationChain msgs = null;
if (performer != null)
msgs = ((InternalEObject)performer).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__PERFORMER, null, msgs);
if (newPerformer != null)
msgs = ((InternalEObject)newPerformer).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__PERFORMER, null, msgs);
msgs = basicSetPerformer(newPerformer, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__PERFORMER, newPerformer, newPerformer));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Identifier getIdentifier() {
return identifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetIdentifier(Identifier newIdentifier, NotificationChain msgs) {
Identifier oldIdentifier = identifier;
identifier = newIdentifier;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__IDENTIFIER, oldIdentifier, newIdentifier);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIdentifier(Identifier newIdentifier) {
if (newIdentifier != identifier) {
NotificationChain msgs = null;
if (identifier != null)
msgs = ((InternalEObject)identifier).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__IDENTIFIER, null, msgs);
if (newIdentifier != null)
msgs = ((InternalEObject)newIdentifier).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__IDENTIFIER, null, msgs);
msgs = basicSetIdentifier(newIdentifier, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__IDENTIFIER, newIdentifier, newIdentifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CodeableConcept getMethod() {
return method;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMethod(CodeableConcept newMethod, NotificationChain msgs) {
CodeableConcept oldMethod = method;
method = newMethod;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__METHOD, oldMethod, newMethod);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMethod(CodeableConcept newMethod) {
if (newMethod != method) {
NotificationChain msgs = null;
if (method != null)
msgs = ((InternalEObject)method).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__METHOD, null, msgs);
if (newMethod != null)
msgs = ((InternalEObject)newMethod).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__METHOD, null, msgs);
msgs = basicSetMethod(newMethod, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__METHOD, newMethod, newMethod));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Reference> getBasis() {
if (basis == null) {
basis = new EObjectContainmentEList<Reference>(Reference.class, this, FhirPackage.RISK_ASSESSMENT__BASIS);
}
return basis;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<RiskAssessmentPrediction> getPrediction() {
if (prediction == null) {
prediction = new EObjectContainmentEList<RiskAssessmentPrediction>(RiskAssessmentPrediction.class, this, FhirPackage.RISK_ASSESSMENT__PREDICTION);
}
return prediction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.hl7.fhir.String getMitigation() {
return mitigation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetMitigation(org.hl7.fhir.String newMitigation, NotificationChain msgs) {
org.hl7.fhir.String oldMitigation = mitigation;
mitigation = newMitigation;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__MITIGATION, oldMitigation, newMitigation);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMitigation(org.hl7.fhir.String newMitigation) {
if (newMitigation != mitigation) {
NotificationChain msgs = null;
if (mitigation != null)
msgs = ((InternalEObject)mitigation).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__MITIGATION, null, msgs);
if (newMitigation != null)
msgs = ((InternalEObject)newMitigation).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FhirPackage.RISK_ASSESSMENT__MITIGATION, null, msgs);
msgs = basicSetMitigation(newMitigation, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, FhirPackage.RISK_ASSESSMENT__MITIGATION, newMitigation, newMitigation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return basicSetSubject(null, msgs);
case FhirPackage.RISK_ASSESSMENT__DATE:
return basicSetDate(null, msgs);
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return basicSetCondition(null, msgs);
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return basicSetEncounter(null, msgs);
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return basicSetPerformer(null, msgs);
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return basicSetIdentifier(null, msgs);
case FhirPackage.RISK_ASSESSMENT__METHOD:
return basicSetMethod(null, msgs);
case FhirPackage.RISK_ASSESSMENT__BASIS:
return ((InternalEList<?>)getBasis()).basicRemove(otherEnd, msgs);
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return ((InternalEList<?>)getPrediction()).basicRemove(otherEnd, msgs);
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return basicSetMitigation(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return getSubject();
case FhirPackage.RISK_ASSESSMENT__DATE:
return getDate();
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return getCondition();
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return getEncounter();
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return getPerformer();
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return getIdentifier();
case FhirPackage.RISK_ASSESSMENT__METHOD:
return getMethod();
case FhirPackage.RISK_ASSESSMENT__BASIS:
return getBasis();
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return getPrediction();
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return getMitigation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
setSubject((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__DATE:
setDate((DateTime)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
setCondition((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
setEncounter((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
setPerformer((Reference)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
setIdentifier((Identifier)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__METHOD:
setMethod((CodeableConcept)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__BASIS:
getBasis().clear();
getBasis().addAll((Collection<? extends Reference>)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
getPrediction().clear();
getPrediction().addAll((Collection<? extends RiskAssessmentPrediction>)newValue);
return;
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
setMitigation((org.hl7.fhir.String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
setSubject((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__DATE:
setDate((DateTime)null);
return;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
setCondition((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
setEncounter((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
setPerformer((Reference)null);
return;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
setIdentifier((Identifier)null);
return;
case FhirPackage.RISK_ASSESSMENT__METHOD:
setMethod((CodeableConcept)null);
return;
case FhirPackage.RISK_ASSESSMENT__BASIS:
getBasis().clear();
return;
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
getPrediction().clear();
return;
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
setMitigation((org.hl7.fhir.String)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case FhirPackage.RISK_ASSESSMENT__SUBJECT:
return subject != null;
case FhirPackage.RISK_ASSESSMENT__DATE:
return date != null;
case FhirPackage.RISK_ASSESSMENT__CONDITION:
return condition != null;
case FhirPackage.RISK_ASSESSMENT__ENCOUNTER:
return encounter != null;
case FhirPackage.RISK_ASSESSMENT__PERFORMER:
return performer != null;
case FhirPackage.RISK_ASSESSMENT__IDENTIFIER:
return identifier != null;
case FhirPackage.RISK_ASSESSMENT__METHOD:
return method != null;
case FhirPackage.RISK_ASSESSMENT__BASIS:
return basis != null && !basis.isEmpty();
case FhirPackage.RISK_ASSESSMENT__PREDICTION:
return prediction != null && !prediction.isEmpty();
case FhirPackage.RISK_ASSESSMENT__MITIGATION:
return mitigation != null;
}
return super.eIsSet(featureID);
}
} //RiskAssessmentImpl
| 22,428 | 0.686107 | 0.684992 | 721 | 30.106796 | 31.925858 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.196949 | false | false | 0 |
23d7079591c8af89ce6c2e783ff775901b46495a | 33,784,212,812,143 | 6c69998676e9df8be55e28f6d63942b9f7cef913 | /src/com/insigma/siis/local/business/comm/BusiAction.java | 3fca3fb28344d7c01f2fb7584232c2188aad9bcc | [] | no_license | HuangHL92/ZHGBSYS | https://github.com/HuangHL92/ZHGBSYS | 9dea4de5931edf5c93a6fbcf6a4655c020395554 | f2ff875eddd569dca52930d09ebc22c4dcb47baf | refs/heads/master | 2023-08-04T04:37:08.995000 | 2021-09-15T07:35:53 | 2021-09-15T07:35:53 | 406,219,162 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.insigma.siis.local.business.comm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.insigma.odin.framework.ActionSupport;
public class BusiAction extends ActionSupport {
public ActionForward zhgbrmb(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String a0000 = request.getParameter("a0000");
request.getRequestDispatcher("rmb/ZHGBrmb.jsp?FromModules=1&a0000="+a0000).forward(request, response);
return null;
}
}
| UTF-8 | Java | 703 | java | BusiAction.java | Java | [] | null | [] | package com.insigma.siis.local.business.comm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.insigma.odin.framework.ActionSupport;
public class BusiAction extends ActionSupport {
public ActionForward zhgbrmb(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String a0000 = request.getParameter("a0000");
request.getRequestDispatcher("rmb/ZHGBrmb.jsp?FromModules=1&a0000="+a0000).forward(request, response);
return null;
}
}
| 703 | 0.817923 | 0.793741 | 21 | 32.476189 | 30.742586 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false | 0 |
02017807fa90a33185d792f3c9caa192aeaf79f8 | 35,012,573,449,393 | 762a343a14853261187a0aec4c17f4cc830121b8 | /Lab07/src/edu/westga/cs6312/scores/testing/scoremanager/TestAddScore.java | f1986cf7f83c62de11cc5205eb33efc767b82dd1 | [] | no_license | kjkraus/CS6312-Program-Construction-IIb | https://github.com/kjkraus/CS6312-Program-Construction-IIb | 45605ed3cdf242ab0e0b0473732f5c32abe755a1 | 7612bbfec6fe3dc52b2396c3bc004ec89bd7a45e | refs/heads/master | 2021-03-22T05:04:17.409000 | 2018-04-29T23:19:57 | 2018-04-29T23:19:57 | 121,189,684 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.westga.cs6312.scores.testing.scoremanager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import edu.westga.cs6312.scores.model.ScoreManager;
class TestAddScore {
/**
* Test to see if addScore returns a value of 0
*/
@Test
void testAddScoreReturnsAValueOfZero() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(0);
assertEquals("0", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 1
*/
@Test
void testAddScoreReturnsAValueOf1() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(1);
assertEquals("1", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 99
*/
@Test
void testAddScoreReturnsAValueOf99() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(99);
assertEquals("99", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 100
*/
@Test
void testAddScoreReturnsAValueOf100() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(100);
assertEquals("100", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 55
*/
@Test
void testAddScoreReturnsAValueOf55() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(55);
assertEquals("55", theScoreManager.getTestScore(0).toString());
}
}
| UTF-8 | Java | 1,801 | java | TestAddScore.java | Java | [] | null | [] | package edu.westga.cs6312.scores.testing.scoremanager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import edu.westga.cs6312.scores.model.ScoreManager;
class TestAddScore {
/**
* Test to see if addScore returns a value of 0
*/
@Test
void testAddScoreReturnsAValueOfZero() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(0);
assertEquals("0", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 1
*/
@Test
void testAddScoreReturnsAValueOf1() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(1);
assertEquals("1", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 99
*/
@Test
void testAddScoreReturnsAValueOf99() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(99);
assertEquals("99", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 100
*/
@Test
void testAddScoreReturnsAValueOf100() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(100);
assertEquals("100", theScoreManager.getTestScore(0).toString());
}
/**
* Test to see if addScore returns a value of 55
*/
@Test
void testAddScoreReturnsAValueOf55() {
ScoreManager theScoreManager = new ScoreManager();
theScoreManager.addScore(55);
assertEquals("55", theScoreManager.getTestScore(0).toString());
}
}
| 1,801 | 0.631316 | 0.604664 | 61 | 27.52459 | 24.690615 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393443 | false | false | 0 |
01f80dc9c4597473012a40b28638af71e53eacd9 | 37,486,474,590,513 | b262b1e3487806cd6494fd4ac0220d932aa8b88f | /sample-mail/src/main/java/com/hannesdorfmann/mosby3/sample/mail/mails/MailsComponent.java | db2c7cd986c0e9bd796c126b38cba7556c600501 | [
"Apache-2.0"
] | permissive | SETANDGET/mosby | https://github.com/SETANDGET/mosby | 3dd5b3fcedddb4e045496a5aa5fee83ff71a5406 | 513d1e96da1e328634f533483c5e1af5013f7a0d | refs/heads/master | 2020-03-09T08:41:33.779000 | 2018-04-08T20:53:52 | 2018-04-08T20:53:52 | 128,695,145 | 4 | 1 | Apache-2.0 | true | 2018-04-09T00:53:56 | 2018-04-09T00:53:56 | 2018-04-08T20:54:01 | 2018-04-08T20:53:57 | 26,436 | 0 | 0 | 0 | null | false | null | package com.hannesdorfmann.mosby3.sample.mail.mails;
import com.hannesdorfmann.mosby3.sample.mail.dagger.MailAppComponent;
import com.hannesdorfmann.mosby3.sample.mail.dagger.MailModule;
import com.hannesdorfmann.mosby3.sample.mail.dagger.NavigationModule;
import dagger.Component;
import javax.inject.Singleton;
/**
* @author Hannes Dorfmann
*/
@Singleton @Component(
modules = {MailModule.class, NavigationModule.class},
dependencies = MailAppComponent.class)
public interface MailsComponent {
MailsPresenter presenter();
void inject(MailsFragment fragment);
}
| UTF-8 | Java | 581 | java | MailsComponent.java | Java | [
{
"context": "nt;\nimport javax.inject.Singleton;\n\n/**\n * @author Hannes Dorfmann\n */\n@Singleton @Component(\n modules = {MailMod",
"end": 345,
"score": 0.999876856803894,
"start": 330,
"tag": "NAME",
"value": "Hannes Dorfmann"
}
] | null | [] | package com.hannesdorfmann.mosby3.sample.mail.mails;
import com.hannesdorfmann.mosby3.sample.mail.dagger.MailAppComponent;
import com.hannesdorfmann.mosby3.sample.mail.dagger.MailModule;
import com.hannesdorfmann.mosby3.sample.mail.dagger.NavigationModule;
import dagger.Component;
import javax.inject.Singleton;
/**
* @author <NAME>
*/
@Singleton @Component(
modules = {MailModule.class, NavigationModule.class},
dependencies = MailAppComponent.class)
public interface MailsComponent {
MailsPresenter presenter();
void inject(MailsFragment fragment);
}
| 572 | 0.802065 | 0.795181 | 20 | 28.049999 | 23.980148 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 0 |
88514a3d0950da83c48c0e2370aa460e64d60ba0 | 2,413,771,623,908 | 81b3984cce8eab7e04a5b0b6bcef593bc0181e5a | /android/CarLife/app/src/main/java/com/baidu/location/p191d/C3314j.java | 1d4933c725fa265eeb02cc779ab5e6b34b1aa14c | [] | no_license | ausdruck/Demo | https://github.com/ausdruck/Demo | 20ee124734d3a56b99b8a8e38466f2adc28024d6 | e11f8844f4852cec901ba784ce93fcbb4200edc6 | refs/heads/master | 2020-04-10T03:49:24.198000 | 2018-07-27T10:14:56 | 2018-07-27T10:14:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.baidu.location.p191d;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import com.baidu.location.C3377f;
import com.baidu.location.Jni;
import com.baidu.location.indoor.p197b.C3416d;
import com.baidu.location.p187a.C3200h;
import com.baidu.location.p187a.C3207j;
import com.baidu.location.p188h.C3186e;
import com.baidu.location.p188h.C3381b;
import com.baidu.location.p188h.C3382c;
import com.baidu.location.p188h.C3391g;
import com.baidu.location.p189b.C3218c;
import com.baidu.location.p194f.C3376f;
import com.baidu.location.p195g.C3379a;
import com.baidu.platform.comapi.map.MapBundleKey.OfflineMapKey;
import com.facebook.common.p141m.C2924g;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
/* renamed from: com.baidu.location.d.j */
public class C3314j extends C3186e {
/* renamed from: A */
private C3312c f17951A;
/* renamed from: B */
private int f17952B;
/* renamed from: C */
private boolean f17953C;
/* renamed from: D */
private long f17954D;
/* renamed from: E */
private SQLiteDatabase f17955E;
/* renamed from: F */
private C3310b f17956F;
/* renamed from: a */
String f17957a;
/* renamed from: b */
String f17958b;
/* renamed from: c */
String f17959c;
/* renamed from: d */
private boolean f17960d;
/* renamed from: e */
private boolean f17961e;
/* renamed from: f */
private ArrayList<C3309a> f17962f;
/* renamed from: p */
private int f17963p;
/* renamed from: q */
private String f17964q;
/* renamed from: r */
private boolean f17965r;
/* renamed from: s */
private boolean f17966s;
/* renamed from: t */
private boolean f17967t;
/* renamed from: u */
private boolean f17968u;
/* renamed from: v */
private int f17969v;
/* renamed from: w */
private int f17970w;
/* renamed from: x */
private int f17971x;
/* renamed from: y */
private int f17972y;
/* renamed from: z */
private boolean f17973z;
/* renamed from: com.baidu.location.d.j$1 */
class C33051 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17933a;
C33051(C3314j c3314j) {
this.f17933a = c3314j;
}
public void run() {
this.f17933a.m13927m();
}
}
/* renamed from: com.baidu.location.d.j$2 */
class C33062 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17934a;
C33062(C3314j c3314j) {
this.f17934a = c3314j;
}
public void run() {
int i = 0;
ArrayList b = this.f17934a.m13937b(C3376f.m14355a().m14380p().f18275a);
if (b == null || b.size() <= 0) {
this.f17934a.f17952B = this.f17934a.f17952B + 1;
return;
}
this.f17934a.f17952B = 0;
Bundle bundle = new Bundle();
int size = b.size();
if (size > 3) {
size = 3;
}
int i2 = 0;
while (i2 < size) {
int i3;
byte[] a = C3314j.m13918b((String) b.get(i2));
if (a == null || a.length != 6) {
i3 = i;
} else {
bundle.putByteArray("mac" + i, a);
i3 = i + 1;
}
i2++;
i = i3;
}
if (i != 0) {
Message obtainMessage = C3294d.m13799a().m13835e().obtainMessage(1);
bundle.putInt("num", i);
obtainMessage.setData(bundle);
obtainMessage.sendToTarget();
}
}
}
/* renamed from: com.baidu.location.d.j$3 */
class C33073 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17935a;
C33073(C3314j c3314j) {
this.f17935a = c3314j;
}
public void run() {
if (C3376f.m14363j()) {
this.f17935a.m13300h();
C3382c.m14410a().m14420e(System.currentTimeMillis());
}
}
}
/* renamed from: com.baidu.location.d.j$4 */
class C33084 extends Thread {
/* renamed from: a */
final /* synthetic */ C3314j f17936a;
C33084(C3314j c3314j) {
this.f17936a = c3314j;
}
public void run() {
this.f17936a.m13931q();
}
}
/* renamed from: com.baidu.location.d.j$a */
private class C3309a {
/* renamed from: a */
int f17937a;
/* renamed from: b */
double f17938b;
/* renamed from: c */
double f17939c;
/* renamed from: d */
double f17940d;
/* renamed from: e */
double f17941e;
/* renamed from: f */
boolean f17942f = false;
/* renamed from: g */
final /* synthetic */ C3314j f17943g;
C3309a(C3314j c3314j, Cursor cursor) {
this.f17943g = c3314j;
try {
this.f17937a = cursor.getInt(0);
this.f17938b = cursor.getDouble(4);
this.f17939c = cursor.getDouble(3);
this.f17940d = cursor.getDouble(2);
this.f17941e = cursor.getDouble(1);
this.f17942f = true;
} catch (Exception e) {
this.f17942f = false;
}
}
}
/* renamed from: com.baidu.location.d.j$b */
public enum C3310b {
NET_FRONT,
NET_BACK,
GPS
}
/* renamed from: com.baidu.location.d.j$c */
private class C3312c implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17949a;
/* renamed from: com.baidu.location.d.j$c$1 */
class C33111 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3312c f17948a;
C33111(C3312c c3312c) {
this.f17948a = c3312c;
}
public void run() {
if (this.f17948a.f17949a.m13936a(C3376f.m14355a().m14380p().f18275a)) {
C3200h.m13362c().m13389h();
}
}
}
private C3312c(C3314j c3314j) {
this.f17949a = c3314j;
}
public void run() {
if (this.f17949a.f17973z) {
this.f17949a.f17973z = false;
if (this.f17949a.f17956F == C3310b.NET_BACK) {
if (C3376f.m14355a().m14372g()) {
C3379a.m14386a().postDelayed(new C33111(this), 3000);
}
C3379a.m14386a().postDelayed(this.f17949a.f17951A, (long) (this.f17949a.f17970w * 1000));
this.f17949a.f17973z = true;
}
}
}
}
/* renamed from: com.baidu.location.d.j$d */
private static class C3313d {
/* renamed from: a */
public static final C3314j f17950a = new C3314j();
}
private C3314j() {
this.f17960d = false;
this.f17961e = false;
this.f17962f = null;
this.f17963p = 0;
this.f17964q = "0";
this.f17965r = true;
this.f17966s = true;
this.f17967t = true;
this.f17968u = true;
this.f17969v = 60;
this.f17970w = 120;
this.f17971x = 15;
this.f17972y = 20;
this.f17973z = false;
this.f17951A = null;
this.f17952B = 0;
this.f17953C = false;
this.f17954D = 0;
this.f17957a = null;
this.f17958b = null;
this.f17959c = null;
this.f17955E = null;
this.f17956F = C3310b.NET_FRONT;
try {
File file = new File(C3391g.m14456l() + File.separator + "bus_mac.db");
File file2 = new File(C3391g.m14456l() + File.separator + "bus_mac_repll.db");
if (file.exists()) {
if (file2.exists()) {
file2.delete();
}
file.renameTo(file2);
this.f17960d = true;
} else if (file2.exists()) {
this.f17960d = true;
} else {
this.f17960d = false;
}
} catch (Exception e) {
this.f17960d = false;
}
}
/* renamed from: a */
private static byte m13911a(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/* renamed from: b */
public static C3314j m13917b() {
return C3313d.f17950a;
}
/* renamed from: b */
private static byte[] m13918b(String str) {
if (str == null || str.equals("")) {
return null;
}
String toUpperCase = str.toUpperCase(Locale.US);
int length = toUpperCase.length() / 2;
char[] toCharArray = toUpperCase.toCharArray();
byte[] bArr = new byte[length];
for (int i = 0; i < length; i++) {
int i2 = i * 2;
bArr[i] = (byte) (C3314j.m13911a(toCharArray[i2 + 1]) | (C3314j.m13911a(toCharArray[i2]) << 4));
}
return bArr;
}
/* renamed from: d */
private void m13921d(String str) {
Editor edit = C3377f.getServiceContext().getSharedPreferences("loc_realbus_config", 0).edit();
edit.putString("config", str);
edit.commit();
}
/* renamed from: k */
private boolean m13925k() {
return C3218c.m13487a().m13495f() >= this.f17972y;
}
/* renamed from: l */
private void m13926l() {
this.f17953C = false;
this.f17952B = 0;
this.f17954D = 0;
}
/* renamed from: m */
private void m13927m() {
if (this.f17953C && this.f17956F == C3310b.GPS) {
this.f17953C = false;
if (this.f17965r && this.f17968u) {
m13928n();
}
}
}
/* renamed from: n */
private void m13928n() {
C3379a.m14386a().post(new C33062(this));
}
/* renamed from: o */
private void m13929o() {
if (System.currentTimeMillis() - C3382c.m14410a().m14419e() > 86400000) {
C3379a.m14386a().postDelayed(new C33073(this), 7000);
}
}
/* renamed from: p */
private void m13930p() {
Object string = C3377f.getServiceContext().getSharedPreferences("loc_realbus_config", 0).getString("config", null);
if (!TextUtils.isEmpty(string)) {
try {
JSONObject jSONObject = new JSONObject(string);
if (jSONObject.has("is_on") && !jSONObject.getString("is_on").equals("on")) {
this.f17965r = false;
}
if (jSONObject.has("is_net_front_on") && !jSONObject.getString("is_net_front_on").equals("on")) {
this.f17966s = false;
}
if (jSONObject.has("is_net_back_on") && !jSONObject.getString("is_net_back_on").equals("on")) {
this.f17967t = false;
}
if (jSONObject.has("is_gps_on") && !jSONObject.getString("is_gps_on").equals("on")) {
this.f17968u = false;
}
if (jSONObject.has("net_front_threshold")) {
this.f17969v = jSONObject.getInt("net_front_threshold");
}
if (jSONObject.has("net_back_threshold")) {
this.f17970w = jSONObject.getInt("net_back_threshold");
}
if (jSONObject.has("gps_threshold")) {
this.f17971x = jSONObject.getInt("gps_threshold");
}
if (jSONObject.has("battery_threshold")) {
this.f17972y = jSONObject.getInt("battery_threshold");
}
} catch (Exception e) {
}
}
}
/* renamed from: q */
private void m13931q() {
if (this.f17958b != null && C3376f.m14363j()) {
try {
File file = new File(C3391g.m14456l() + File.separator + this.f17958b);
if (file.exists()) {
file.delete();
}
if (!file.exists() && C3207j.m13416a("http://" + this.f17957a + "/" + this.f17958b, this.f17958b)) {
String a = C3391g.m14435a(file, "MD5");
if (!(this.f17959c == null || a == null || !this.f17959c.equals(a))) {
new C3416d().m14594a(C3391g.m14456l() + File.separator + this.f17958b, C3391g.m14456l() + File.separator);
}
file.delete();
}
} catch (Exception e) {
}
}
}
/* renamed from: a */
public void mo2494a() {
StringBuffer stringBuffer = new StringBuffer(128);
stringBuffer.append("&sdk=");
stringBuffer.append(7.32f);
stringBuffer.append("&fw=");
stringBuffer.append(C3377f.getFrameVersion());
stringBuffer.append("&suit=");
stringBuffer.append(1);
if (C3381b.m14398a().f18317b == null) {
stringBuffer.append("&im=");
stringBuffer.append(C3381b.m14398a().f18316a);
} else {
stringBuffer.append("&cu=");
stringBuffer.append(C3381b.m14398a().f18317b);
}
stringBuffer.append("&mb=");
stringBuffer.append(Build.MODEL);
stringBuffer.append("&sv=");
String str = VERSION.RELEASE;
if (str != null && str.length() > 10) {
str = str.substring(0, 10);
}
stringBuffer.append(str);
stringBuffer.append("&pack=");
stringBuffer.append(C3381b.f18311d);
stringBuffer.append("&ver=");
stringBuffer.append("" + this.f17964q);
this.h = C3391g.m14451g() + "?&it=" + Jni.en1(stringBuffer.toString());
}
/* renamed from: a */
public void m13933a(double d, double d2) {
if (!this.f17961e) {
this.f17961e = true;
if (this.f17960d && this.f17962f != null && this.f17962f.size() > 0) {
int i = 0;
while (i < this.f17962f.size()) {
C3309a c3309a = (C3309a) this.f17962f.get(i);
if (d > c3309a.f17938b || d < c3309a.f17939c || d2 < c3309a.f17941e || d2 > c3309a.f17940d) {
i++;
} else {
this.f17963p = c3309a.f17937a;
return;
}
}
}
}
}
/* renamed from: a */
public void m13934a(C3310b c3310b) {
this.f17956F = c3310b;
if (this.f17973z && this.f17951A != null) {
C3379a.m14386a().removeCallbacks(this.f17951A);
}
if (this.f17956F != C3310b.GPS) {
if (this.f17956F == C3310b.NET_FRONT) {
m13926l();
return;
}
m13926l();
if (this.f17965r && this.f17967t && m13925k()) {
if (this.f17951A == null) {
this.f17951A = new C3312c();
}
C3379a.m14386a().postDelayed(this.f17951A, (long) (this.f17970w * 1000));
this.f17973z = true;
}
}
}
/* renamed from: a */
public void mo2495a(boolean z) {
if (z) {
try {
JSONObject jSONObject = new JSONObject(this.j);
String string = jSONObject.getString(C2924g.f12892f);
if (OfflineMapKey.OFFLINE_UPDATE.equals(string)) {
this.f17957a = jSONObject.getString("upath");
if (jSONObject.has("u1")) {
this.f17958b = jSONObject.getString("u1");
}
if (jSONObject.has("u1_md5")) {
this.f17959c = jSONObject.getString("u1_md5");
}
new C33084(this).start();
}
if (!"fail".equals(string)) {
m13921d(jSONObject.toString());
}
} catch (Exception e) {
}
}
}
/* renamed from: a */
public boolean m13936a(List<ScanResult> list) {
ArrayList b = m13937b((List) list);
return b != null && b.size() > 0;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
/* renamed from: b */
public java.util.ArrayList<java.lang.String> m13937b(java.util.List<android.net.wifi.ScanResult> r11) {
/*
r10 = this;
r2 = 1;
r3 = 0;
r4 = 0;
java.lang.System.currentTimeMillis();
r0 = r10.f17963p;
if (r0 == 0) goto L_0x000e;
L_0x000a:
r0 = r10.f17955E;
if (r0 != 0) goto L_0x000f;
L_0x000e:
return r4;
L_0x000f:
if (r11 == 0) goto L_0x000e;
L_0x0011:
r0 = r11.size();
if (r0 == 0) goto L_0x000e;
L_0x0017:
r5 = new java.util.HashMap;
r5.<init>();
r6 = r11.iterator();
r7 = new java.lang.StringBuffer;
r7.<init>();
r1 = r2;
L_0x0026:
r0 = r6.hasNext();
if (r0 == 0) goto L_0x005e;
L_0x002c:
r0 = r6.next();
r0 = (android.net.wifi.ScanResult) r0;
r0 = r0.BSSID;
r8 = android.text.TextUtils.isEmpty(r0);
if (r8 != 0) goto L_0x005c;
L_0x003a:
r8 = ":";
r9 = "";
r0 = r0.replace(r8, r9);
r8 = com.baidu.location.Jni.encode3(r0);
r5.put(r8, r0);
if (r1 == 0) goto L_0x0053;
L_0x004d:
r7.append(r8);
r0 = r3;
L_0x0051:
r1 = r0;
goto L_0x0026;
L_0x0053:
r0 = ",";
r7.append(r0);
r7.append(r8);
L_0x005c:
r0 = r1;
goto L_0x0051;
L_0x005e:
r0 = r7.toString();
r0 = android.text.TextUtils.isEmpty(r0);
if (r0 != 0) goto L_0x00e1;
L_0x0068:
r0 = java.util.Locale.US;
r1 = "select * from bus_mac_data_%d where mac in (%s);";
r6 = 2;
r6 = new java.lang.Object[r6];
r8 = r10.f17963p;
r8 = java.lang.Integer.valueOf(r8);
r6[r3] = r8;
r3 = r7.toString();
r6[r2] = r3;
r0 = java.lang.String.format(r0, r1, r6);
r1 = r10.f17955E; Catch:{ Exception -> 0x00d8, all -> 0x00ca }
r2 = 0;
r1 = r1.rawQuery(r0, r2); Catch:{ Exception -> 0x00d8, all -> 0x00ca }
if (r1 == 0) goto L_0x00df;
L_0x008b:
r0 = r1.moveToFirst(); Catch:{ Exception -> 0x00db, all -> 0x00d6 }
if (r0 == 0) goto L_0x00df;
L_0x0091:
if (r4 != 0) goto L_0x0099;
L_0x0093:
r0 = new java.util.ArrayList; Catch:{ Exception -> 0x00db, all -> 0x00d6 }
r0.<init>(); Catch:{ Exception -> 0x00db, all -> 0x00d6 }
r4 = r0;
L_0x0099:
r0 = r1.isAfterLast(); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
if (r0 != 0) goto L_0x00c1;
L_0x009f:
r0 = 0;
r2 = r1.getLong(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r0 = java.lang.Long.valueOf(r2); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r0 = r5.get(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r4.add(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r1.moveToNext(); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
goto L_0x0099;
L_0x00b3:
r0 = move-exception;
r0 = r4;
r4 = r1;
L_0x00b6:
if (r4 == 0) goto L_0x00bb;
L_0x00b8:
r4.close(); Catch:{ Exception -> 0x00d2 }
L_0x00bb:
java.lang.System.currentTimeMillis();
r4 = r0;
goto L_0x000e;
L_0x00c1:
r0 = r4;
L_0x00c2:
if (r1 == 0) goto L_0x00bb;
L_0x00c4:
r1.close(); Catch:{ Exception -> 0x00c8 }
goto L_0x00bb;
L_0x00c8:
r1 = move-exception;
goto L_0x00bb;
L_0x00ca:
r0 = move-exception;
r1 = r4;
L_0x00cc:
if (r1 == 0) goto L_0x00d1;
L_0x00ce:
r1.close(); Catch:{ Exception -> 0x00d4 }
L_0x00d1:
throw r0;
L_0x00d2:
r1 = move-exception;
goto L_0x00bb;
L_0x00d4:
r1 = move-exception;
goto L_0x00d1;
L_0x00d6:
r0 = move-exception;
goto L_0x00cc;
L_0x00d8:
r0 = move-exception;
r0 = r4;
goto L_0x00b6;
L_0x00db:
r0 = move-exception;
r0 = r4;
r4 = r1;
goto L_0x00b6;
L_0x00df:
r0 = r4;
goto L_0x00c2;
L_0x00e1:
r0 = r4;
goto L_0x00bb;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.location.d.j.b(java.util.List):java.util.ArrayList<java.lang.String>");
}
/* renamed from: c */
public void mo2499c() {
if (this.f17965r && this.f17968u && m13925k()) {
this.f17953C = false;
if (this.f17952B > 3) {
long currentTimeMillis = System.currentTimeMillis() - this.f17954D;
if (currentTimeMillis <= ((long) ((this.f17952B - 3) * ((this.f17971x * 2) * 1000))) && currentTimeMillis <= 120000) {
return;
}
}
C3376f.m14355a().m14372g();
this.f17953C = true;
this.f17954D = System.currentTimeMillis();
C3379a.m14386a().postDelayed(new C33051(this), 3000);
}
}
/* renamed from: d */
public boolean m13939d() {
boolean z = this.f17956F == C3310b.NET_FRONT;
if (!(this.f17965r && this.f17966s)) {
z = false;
}
return !m13925k() ? false : z;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
/* renamed from: e */
public void m13940e() {
/*
r6 = this;
r0 = 0;
r6.f17955E = r0;
r1 = r6.f17960d;
if (r1 == 0) goto L_0x0085;
L_0x0007:
r1 = new java.lang.StringBuilder;
r1.<init>();
r2 = com.baidu.location.p188h.C3391g.m14456l();
r1 = r1.append(r2);
r2 = java.io.File.separator;
r1 = r1.append(r2);
r2 = "bus_mac_repll.db";
r1 = r1.append(r2);
r1 = r1.toString();
r2 = 0;
r1 = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(r1, r2); Catch:{ Exception -> 0x008c }
r6.f17955E = r1; Catch:{ Exception -> 0x008c }
L_0x002c:
r1 = r6.f17955E;
if (r1 == 0) goto L_0x0085;
L_0x0030:
r1 = r6.f17955E; Catch:{ Exception -> 0x00c3, all -> 0x009d }
r2 = "select * from bus_mac_version;";
r3 = 0;
r1 = r1.rawQuery(r2, r3); Catch:{ Exception -> 0x00c3, all -> 0x009d }
if (r1 == 0) goto L_0x0049;
L_0x003c:
r2 = r1.moveToFirst(); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
if (r2 == 0) goto L_0x0049;
L_0x0042:
r2 = 0;
r2 = r1.getString(r2); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
r6.f17964q = r2; Catch:{ Exception -> 0x007a, all -> 0x00b7 }
L_0x0049:
r2 = r6.f17955E; Catch:{ Exception -> 0x007a, all -> 0x00b7 }
r3 = "select * from bus_mac_city;";
r4 = 0;
r0 = r2.rawQuery(r3, r4); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
if (r0 == 0) goto L_0x0090;
L_0x0055:
r2 = r0.moveToFirst(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r2 == 0) goto L_0x0090;
L_0x005b:
r2 = new java.util.ArrayList; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r2.<init>(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
r6.f17962f = r2; Catch:{ Exception -> 0x007a, all -> 0x00bd }
L_0x0062:
r2 = r0.isAfterLast(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r2 != 0) goto L_0x0090;
L_0x0068:
r2 = new com.baidu.location.d.j$a; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r2.<init>(r6, r0); Catch:{ Exception -> 0x007a, all -> 0x00bd }
r3 = r2.f17942f; Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r3 == 0) goto L_0x0076;
L_0x0071:
r3 = r6.f17962f; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r3.add(r2); Catch:{ Exception -> 0x007a, all -> 0x00bd }
L_0x0076:
r0.moveToNext(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
goto L_0x0062;
L_0x007a:
r2 = move-exception;
L_0x007b:
if (r1 == 0) goto L_0x0080;
L_0x007d:
r1.close(); Catch:{ Exception -> 0x00af }
L_0x0080:
if (r0 == 0) goto L_0x0085;
L_0x0082:
r0.close(); Catch:{ Exception -> 0x00b1 }
L_0x0085:
r6.m13930p();
r6.m13929o();
return;
L_0x008c:
r1 = move-exception;
r6.f17955E = r0;
goto L_0x002c;
L_0x0090:
if (r1 == 0) goto L_0x0095;
L_0x0092:
r1.close(); Catch:{ Exception -> 0x00ad }
L_0x0095:
if (r0 == 0) goto L_0x0085;
L_0x0097:
r0.close(); Catch:{ Exception -> 0x009b }
goto L_0x0085;
L_0x009b:
r0 = move-exception;
goto L_0x0085;
L_0x009d:
r1 = move-exception;
r2 = r0;
r5 = r0;
r0 = r1;
r1 = r5;
L_0x00a2:
if (r2 == 0) goto L_0x00a7;
L_0x00a4:
r2.close(); Catch:{ Exception -> 0x00b3 }
L_0x00a7:
if (r1 == 0) goto L_0x00ac;
L_0x00a9:
r1.close(); Catch:{ Exception -> 0x00b5 }
L_0x00ac:
throw r0;
L_0x00ad:
r1 = move-exception;
goto L_0x0095;
L_0x00af:
r1 = move-exception;
goto L_0x0080;
L_0x00b1:
r0 = move-exception;
goto L_0x0085;
L_0x00b3:
r2 = move-exception;
goto L_0x00a7;
L_0x00b5:
r1 = move-exception;
goto L_0x00ac;
L_0x00b7:
r2 = move-exception;
r5 = r2;
r2 = r1;
r1 = r0;
r0 = r5;
goto L_0x00a2;
L_0x00bd:
r2 = move-exception;
r5 = r2;
r2 = r1;
r1 = r0;
r0 = r5;
goto L_0x00a2;
L_0x00c3:
r1 = move-exception;
r1 = r0;
goto L_0x007b;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.location.d.j.e():void");
}
/* renamed from: f */
public void m13941f() {
if (this.f17955E != null) {
try {
this.f17955E.close();
} catch (Exception e) {
}
}
}
/* renamed from: g */
public int m13942g() {
return this.f17969v;
}
}
| UTF-8 | Java | 27,187 | java | C3314j.java | Java | [] | null | [] | package com.baidu.location.p191d;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import com.baidu.location.C3377f;
import com.baidu.location.Jni;
import com.baidu.location.indoor.p197b.C3416d;
import com.baidu.location.p187a.C3200h;
import com.baidu.location.p187a.C3207j;
import com.baidu.location.p188h.C3186e;
import com.baidu.location.p188h.C3381b;
import com.baidu.location.p188h.C3382c;
import com.baidu.location.p188h.C3391g;
import com.baidu.location.p189b.C3218c;
import com.baidu.location.p194f.C3376f;
import com.baidu.location.p195g.C3379a;
import com.baidu.platform.comapi.map.MapBundleKey.OfflineMapKey;
import com.facebook.common.p141m.C2924g;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
/* renamed from: com.baidu.location.d.j */
public class C3314j extends C3186e {
/* renamed from: A */
private C3312c f17951A;
/* renamed from: B */
private int f17952B;
/* renamed from: C */
private boolean f17953C;
/* renamed from: D */
private long f17954D;
/* renamed from: E */
private SQLiteDatabase f17955E;
/* renamed from: F */
private C3310b f17956F;
/* renamed from: a */
String f17957a;
/* renamed from: b */
String f17958b;
/* renamed from: c */
String f17959c;
/* renamed from: d */
private boolean f17960d;
/* renamed from: e */
private boolean f17961e;
/* renamed from: f */
private ArrayList<C3309a> f17962f;
/* renamed from: p */
private int f17963p;
/* renamed from: q */
private String f17964q;
/* renamed from: r */
private boolean f17965r;
/* renamed from: s */
private boolean f17966s;
/* renamed from: t */
private boolean f17967t;
/* renamed from: u */
private boolean f17968u;
/* renamed from: v */
private int f17969v;
/* renamed from: w */
private int f17970w;
/* renamed from: x */
private int f17971x;
/* renamed from: y */
private int f17972y;
/* renamed from: z */
private boolean f17973z;
/* renamed from: com.baidu.location.d.j$1 */
class C33051 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17933a;
C33051(C3314j c3314j) {
this.f17933a = c3314j;
}
public void run() {
this.f17933a.m13927m();
}
}
/* renamed from: com.baidu.location.d.j$2 */
class C33062 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17934a;
C33062(C3314j c3314j) {
this.f17934a = c3314j;
}
public void run() {
int i = 0;
ArrayList b = this.f17934a.m13937b(C3376f.m14355a().m14380p().f18275a);
if (b == null || b.size() <= 0) {
this.f17934a.f17952B = this.f17934a.f17952B + 1;
return;
}
this.f17934a.f17952B = 0;
Bundle bundle = new Bundle();
int size = b.size();
if (size > 3) {
size = 3;
}
int i2 = 0;
while (i2 < size) {
int i3;
byte[] a = C3314j.m13918b((String) b.get(i2));
if (a == null || a.length != 6) {
i3 = i;
} else {
bundle.putByteArray("mac" + i, a);
i3 = i + 1;
}
i2++;
i = i3;
}
if (i != 0) {
Message obtainMessage = C3294d.m13799a().m13835e().obtainMessage(1);
bundle.putInt("num", i);
obtainMessage.setData(bundle);
obtainMessage.sendToTarget();
}
}
}
/* renamed from: com.baidu.location.d.j$3 */
class C33073 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17935a;
C33073(C3314j c3314j) {
this.f17935a = c3314j;
}
public void run() {
if (C3376f.m14363j()) {
this.f17935a.m13300h();
C3382c.m14410a().m14420e(System.currentTimeMillis());
}
}
}
/* renamed from: com.baidu.location.d.j$4 */
class C33084 extends Thread {
/* renamed from: a */
final /* synthetic */ C3314j f17936a;
C33084(C3314j c3314j) {
this.f17936a = c3314j;
}
public void run() {
this.f17936a.m13931q();
}
}
/* renamed from: com.baidu.location.d.j$a */
private class C3309a {
/* renamed from: a */
int f17937a;
/* renamed from: b */
double f17938b;
/* renamed from: c */
double f17939c;
/* renamed from: d */
double f17940d;
/* renamed from: e */
double f17941e;
/* renamed from: f */
boolean f17942f = false;
/* renamed from: g */
final /* synthetic */ C3314j f17943g;
C3309a(C3314j c3314j, Cursor cursor) {
this.f17943g = c3314j;
try {
this.f17937a = cursor.getInt(0);
this.f17938b = cursor.getDouble(4);
this.f17939c = cursor.getDouble(3);
this.f17940d = cursor.getDouble(2);
this.f17941e = cursor.getDouble(1);
this.f17942f = true;
} catch (Exception e) {
this.f17942f = false;
}
}
}
/* renamed from: com.baidu.location.d.j$b */
public enum C3310b {
NET_FRONT,
NET_BACK,
GPS
}
/* renamed from: com.baidu.location.d.j$c */
private class C3312c implements Runnable {
/* renamed from: a */
final /* synthetic */ C3314j f17949a;
/* renamed from: com.baidu.location.d.j$c$1 */
class C33111 implements Runnable {
/* renamed from: a */
final /* synthetic */ C3312c f17948a;
C33111(C3312c c3312c) {
this.f17948a = c3312c;
}
public void run() {
if (this.f17948a.f17949a.m13936a(C3376f.m14355a().m14380p().f18275a)) {
C3200h.m13362c().m13389h();
}
}
}
private C3312c(C3314j c3314j) {
this.f17949a = c3314j;
}
public void run() {
if (this.f17949a.f17973z) {
this.f17949a.f17973z = false;
if (this.f17949a.f17956F == C3310b.NET_BACK) {
if (C3376f.m14355a().m14372g()) {
C3379a.m14386a().postDelayed(new C33111(this), 3000);
}
C3379a.m14386a().postDelayed(this.f17949a.f17951A, (long) (this.f17949a.f17970w * 1000));
this.f17949a.f17973z = true;
}
}
}
}
/* renamed from: com.baidu.location.d.j$d */
private static class C3313d {
/* renamed from: a */
public static final C3314j f17950a = new C3314j();
}
private C3314j() {
this.f17960d = false;
this.f17961e = false;
this.f17962f = null;
this.f17963p = 0;
this.f17964q = "0";
this.f17965r = true;
this.f17966s = true;
this.f17967t = true;
this.f17968u = true;
this.f17969v = 60;
this.f17970w = 120;
this.f17971x = 15;
this.f17972y = 20;
this.f17973z = false;
this.f17951A = null;
this.f17952B = 0;
this.f17953C = false;
this.f17954D = 0;
this.f17957a = null;
this.f17958b = null;
this.f17959c = null;
this.f17955E = null;
this.f17956F = C3310b.NET_FRONT;
try {
File file = new File(C3391g.m14456l() + File.separator + "bus_mac.db");
File file2 = new File(C3391g.m14456l() + File.separator + "bus_mac_repll.db");
if (file.exists()) {
if (file2.exists()) {
file2.delete();
}
file.renameTo(file2);
this.f17960d = true;
} else if (file2.exists()) {
this.f17960d = true;
} else {
this.f17960d = false;
}
} catch (Exception e) {
this.f17960d = false;
}
}
/* renamed from: a */
private static byte m13911a(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/* renamed from: b */
public static C3314j m13917b() {
return C3313d.f17950a;
}
/* renamed from: b */
private static byte[] m13918b(String str) {
if (str == null || str.equals("")) {
return null;
}
String toUpperCase = str.toUpperCase(Locale.US);
int length = toUpperCase.length() / 2;
char[] toCharArray = toUpperCase.toCharArray();
byte[] bArr = new byte[length];
for (int i = 0; i < length; i++) {
int i2 = i * 2;
bArr[i] = (byte) (C3314j.m13911a(toCharArray[i2 + 1]) | (C3314j.m13911a(toCharArray[i2]) << 4));
}
return bArr;
}
/* renamed from: d */
private void m13921d(String str) {
Editor edit = C3377f.getServiceContext().getSharedPreferences("loc_realbus_config", 0).edit();
edit.putString("config", str);
edit.commit();
}
/* renamed from: k */
private boolean m13925k() {
return C3218c.m13487a().m13495f() >= this.f17972y;
}
/* renamed from: l */
private void m13926l() {
this.f17953C = false;
this.f17952B = 0;
this.f17954D = 0;
}
/* renamed from: m */
private void m13927m() {
if (this.f17953C && this.f17956F == C3310b.GPS) {
this.f17953C = false;
if (this.f17965r && this.f17968u) {
m13928n();
}
}
}
/* renamed from: n */
private void m13928n() {
C3379a.m14386a().post(new C33062(this));
}
/* renamed from: o */
private void m13929o() {
if (System.currentTimeMillis() - C3382c.m14410a().m14419e() > 86400000) {
C3379a.m14386a().postDelayed(new C33073(this), 7000);
}
}
/* renamed from: p */
private void m13930p() {
Object string = C3377f.getServiceContext().getSharedPreferences("loc_realbus_config", 0).getString("config", null);
if (!TextUtils.isEmpty(string)) {
try {
JSONObject jSONObject = new JSONObject(string);
if (jSONObject.has("is_on") && !jSONObject.getString("is_on").equals("on")) {
this.f17965r = false;
}
if (jSONObject.has("is_net_front_on") && !jSONObject.getString("is_net_front_on").equals("on")) {
this.f17966s = false;
}
if (jSONObject.has("is_net_back_on") && !jSONObject.getString("is_net_back_on").equals("on")) {
this.f17967t = false;
}
if (jSONObject.has("is_gps_on") && !jSONObject.getString("is_gps_on").equals("on")) {
this.f17968u = false;
}
if (jSONObject.has("net_front_threshold")) {
this.f17969v = jSONObject.getInt("net_front_threshold");
}
if (jSONObject.has("net_back_threshold")) {
this.f17970w = jSONObject.getInt("net_back_threshold");
}
if (jSONObject.has("gps_threshold")) {
this.f17971x = jSONObject.getInt("gps_threshold");
}
if (jSONObject.has("battery_threshold")) {
this.f17972y = jSONObject.getInt("battery_threshold");
}
} catch (Exception e) {
}
}
}
/* renamed from: q */
private void m13931q() {
if (this.f17958b != null && C3376f.m14363j()) {
try {
File file = new File(C3391g.m14456l() + File.separator + this.f17958b);
if (file.exists()) {
file.delete();
}
if (!file.exists() && C3207j.m13416a("http://" + this.f17957a + "/" + this.f17958b, this.f17958b)) {
String a = C3391g.m14435a(file, "MD5");
if (!(this.f17959c == null || a == null || !this.f17959c.equals(a))) {
new C3416d().m14594a(C3391g.m14456l() + File.separator + this.f17958b, C3391g.m14456l() + File.separator);
}
file.delete();
}
} catch (Exception e) {
}
}
}
/* renamed from: a */
public void mo2494a() {
StringBuffer stringBuffer = new StringBuffer(128);
stringBuffer.append("&sdk=");
stringBuffer.append(7.32f);
stringBuffer.append("&fw=");
stringBuffer.append(C3377f.getFrameVersion());
stringBuffer.append("&suit=");
stringBuffer.append(1);
if (C3381b.m14398a().f18317b == null) {
stringBuffer.append("&im=");
stringBuffer.append(C3381b.m14398a().f18316a);
} else {
stringBuffer.append("&cu=");
stringBuffer.append(C3381b.m14398a().f18317b);
}
stringBuffer.append("&mb=");
stringBuffer.append(Build.MODEL);
stringBuffer.append("&sv=");
String str = VERSION.RELEASE;
if (str != null && str.length() > 10) {
str = str.substring(0, 10);
}
stringBuffer.append(str);
stringBuffer.append("&pack=");
stringBuffer.append(C3381b.f18311d);
stringBuffer.append("&ver=");
stringBuffer.append("" + this.f17964q);
this.h = C3391g.m14451g() + "?&it=" + Jni.en1(stringBuffer.toString());
}
/* renamed from: a */
public void m13933a(double d, double d2) {
if (!this.f17961e) {
this.f17961e = true;
if (this.f17960d && this.f17962f != null && this.f17962f.size() > 0) {
int i = 0;
while (i < this.f17962f.size()) {
C3309a c3309a = (C3309a) this.f17962f.get(i);
if (d > c3309a.f17938b || d < c3309a.f17939c || d2 < c3309a.f17941e || d2 > c3309a.f17940d) {
i++;
} else {
this.f17963p = c3309a.f17937a;
return;
}
}
}
}
}
/* renamed from: a */
public void m13934a(C3310b c3310b) {
this.f17956F = c3310b;
if (this.f17973z && this.f17951A != null) {
C3379a.m14386a().removeCallbacks(this.f17951A);
}
if (this.f17956F != C3310b.GPS) {
if (this.f17956F == C3310b.NET_FRONT) {
m13926l();
return;
}
m13926l();
if (this.f17965r && this.f17967t && m13925k()) {
if (this.f17951A == null) {
this.f17951A = new C3312c();
}
C3379a.m14386a().postDelayed(this.f17951A, (long) (this.f17970w * 1000));
this.f17973z = true;
}
}
}
/* renamed from: a */
public void mo2495a(boolean z) {
if (z) {
try {
JSONObject jSONObject = new JSONObject(this.j);
String string = jSONObject.getString(C2924g.f12892f);
if (OfflineMapKey.OFFLINE_UPDATE.equals(string)) {
this.f17957a = jSONObject.getString("upath");
if (jSONObject.has("u1")) {
this.f17958b = jSONObject.getString("u1");
}
if (jSONObject.has("u1_md5")) {
this.f17959c = jSONObject.getString("u1_md5");
}
new C33084(this).start();
}
if (!"fail".equals(string)) {
m13921d(jSONObject.toString());
}
} catch (Exception e) {
}
}
}
/* renamed from: a */
public boolean m13936a(List<ScanResult> list) {
ArrayList b = m13937b((List) list);
return b != null && b.size() > 0;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
/* renamed from: b */
public java.util.ArrayList<java.lang.String> m13937b(java.util.List<android.net.wifi.ScanResult> r11) {
/*
r10 = this;
r2 = 1;
r3 = 0;
r4 = 0;
java.lang.System.currentTimeMillis();
r0 = r10.f17963p;
if (r0 == 0) goto L_0x000e;
L_0x000a:
r0 = r10.f17955E;
if (r0 != 0) goto L_0x000f;
L_0x000e:
return r4;
L_0x000f:
if (r11 == 0) goto L_0x000e;
L_0x0011:
r0 = r11.size();
if (r0 == 0) goto L_0x000e;
L_0x0017:
r5 = new java.util.HashMap;
r5.<init>();
r6 = r11.iterator();
r7 = new java.lang.StringBuffer;
r7.<init>();
r1 = r2;
L_0x0026:
r0 = r6.hasNext();
if (r0 == 0) goto L_0x005e;
L_0x002c:
r0 = r6.next();
r0 = (android.net.wifi.ScanResult) r0;
r0 = r0.BSSID;
r8 = android.text.TextUtils.isEmpty(r0);
if (r8 != 0) goto L_0x005c;
L_0x003a:
r8 = ":";
r9 = "";
r0 = r0.replace(r8, r9);
r8 = com.baidu.location.Jni.encode3(r0);
r5.put(r8, r0);
if (r1 == 0) goto L_0x0053;
L_0x004d:
r7.append(r8);
r0 = r3;
L_0x0051:
r1 = r0;
goto L_0x0026;
L_0x0053:
r0 = ",";
r7.append(r0);
r7.append(r8);
L_0x005c:
r0 = r1;
goto L_0x0051;
L_0x005e:
r0 = r7.toString();
r0 = android.text.TextUtils.isEmpty(r0);
if (r0 != 0) goto L_0x00e1;
L_0x0068:
r0 = java.util.Locale.US;
r1 = "select * from bus_mac_data_%d where mac in (%s);";
r6 = 2;
r6 = new java.lang.Object[r6];
r8 = r10.f17963p;
r8 = java.lang.Integer.valueOf(r8);
r6[r3] = r8;
r3 = r7.toString();
r6[r2] = r3;
r0 = java.lang.String.format(r0, r1, r6);
r1 = r10.f17955E; Catch:{ Exception -> 0x00d8, all -> 0x00ca }
r2 = 0;
r1 = r1.rawQuery(r0, r2); Catch:{ Exception -> 0x00d8, all -> 0x00ca }
if (r1 == 0) goto L_0x00df;
L_0x008b:
r0 = r1.moveToFirst(); Catch:{ Exception -> 0x00db, all -> 0x00d6 }
if (r0 == 0) goto L_0x00df;
L_0x0091:
if (r4 != 0) goto L_0x0099;
L_0x0093:
r0 = new java.util.ArrayList; Catch:{ Exception -> 0x00db, all -> 0x00d6 }
r0.<init>(); Catch:{ Exception -> 0x00db, all -> 0x00d6 }
r4 = r0;
L_0x0099:
r0 = r1.isAfterLast(); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
if (r0 != 0) goto L_0x00c1;
L_0x009f:
r0 = 0;
r2 = r1.getLong(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r0 = java.lang.Long.valueOf(r2); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r0 = r5.get(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r4.add(r0); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
r1.moveToNext(); Catch:{ Exception -> 0x00b3, all -> 0x00d6 }
goto L_0x0099;
L_0x00b3:
r0 = move-exception;
r0 = r4;
r4 = r1;
L_0x00b6:
if (r4 == 0) goto L_0x00bb;
L_0x00b8:
r4.close(); Catch:{ Exception -> 0x00d2 }
L_0x00bb:
java.lang.System.currentTimeMillis();
r4 = r0;
goto L_0x000e;
L_0x00c1:
r0 = r4;
L_0x00c2:
if (r1 == 0) goto L_0x00bb;
L_0x00c4:
r1.close(); Catch:{ Exception -> 0x00c8 }
goto L_0x00bb;
L_0x00c8:
r1 = move-exception;
goto L_0x00bb;
L_0x00ca:
r0 = move-exception;
r1 = r4;
L_0x00cc:
if (r1 == 0) goto L_0x00d1;
L_0x00ce:
r1.close(); Catch:{ Exception -> 0x00d4 }
L_0x00d1:
throw r0;
L_0x00d2:
r1 = move-exception;
goto L_0x00bb;
L_0x00d4:
r1 = move-exception;
goto L_0x00d1;
L_0x00d6:
r0 = move-exception;
goto L_0x00cc;
L_0x00d8:
r0 = move-exception;
r0 = r4;
goto L_0x00b6;
L_0x00db:
r0 = move-exception;
r0 = r4;
r4 = r1;
goto L_0x00b6;
L_0x00df:
r0 = r4;
goto L_0x00c2;
L_0x00e1:
r0 = r4;
goto L_0x00bb;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.location.d.j.b(java.util.List):java.util.ArrayList<java.lang.String>");
}
/* renamed from: c */
public void mo2499c() {
if (this.f17965r && this.f17968u && m13925k()) {
this.f17953C = false;
if (this.f17952B > 3) {
long currentTimeMillis = System.currentTimeMillis() - this.f17954D;
if (currentTimeMillis <= ((long) ((this.f17952B - 3) * ((this.f17971x * 2) * 1000))) && currentTimeMillis <= 120000) {
return;
}
}
C3376f.m14355a().m14372g();
this.f17953C = true;
this.f17954D = System.currentTimeMillis();
C3379a.m14386a().postDelayed(new C33051(this), 3000);
}
}
/* renamed from: d */
public boolean m13939d() {
boolean z = this.f17956F == C3310b.NET_FRONT;
if (!(this.f17965r && this.f17966s)) {
z = false;
}
return !m13925k() ? false : z;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
/* renamed from: e */
public void m13940e() {
/*
r6 = this;
r0 = 0;
r6.f17955E = r0;
r1 = r6.f17960d;
if (r1 == 0) goto L_0x0085;
L_0x0007:
r1 = new java.lang.StringBuilder;
r1.<init>();
r2 = com.baidu.location.p188h.C3391g.m14456l();
r1 = r1.append(r2);
r2 = java.io.File.separator;
r1 = r1.append(r2);
r2 = "bus_mac_repll.db";
r1 = r1.append(r2);
r1 = r1.toString();
r2 = 0;
r1 = android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(r1, r2); Catch:{ Exception -> 0x008c }
r6.f17955E = r1; Catch:{ Exception -> 0x008c }
L_0x002c:
r1 = r6.f17955E;
if (r1 == 0) goto L_0x0085;
L_0x0030:
r1 = r6.f17955E; Catch:{ Exception -> 0x00c3, all -> 0x009d }
r2 = "select * from bus_mac_version;";
r3 = 0;
r1 = r1.rawQuery(r2, r3); Catch:{ Exception -> 0x00c3, all -> 0x009d }
if (r1 == 0) goto L_0x0049;
L_0x003c:
r2 = r1.moveToFirst(); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
if (r2 == 0) goto L_0x0049;
L_0x0042:
r2 = 0;
r2 = r1.getString(r2); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
r6.f17964q = r2; Catch:{ Exception -> 0x007a, all -> 0x00b7 }
L_0x0049:
r2 = r6.f17955E; Catch:{ Exception -> 0x007a, all -> 0x00b7 }
r3 = "select * from bus_mac_city;";
r4 = 0;
r0 = r2.rawQuery(r3, r4); Catch:{ Exception -> 0x007a, all -> 0x00b7 }
if (r0 == 0) goto L_0x0090;
L_0x0055:
r2 = r0.moveToFirst(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r2 == 0) goto L_0x0090;
L_0x005b:
r2 = new java.util.ArrayList; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r2.<init>(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
r6.f17962f = r2; Catch:{ Exception -> 0x007a, all -> 0x00bd }
L_0x0062:
r2 = r0.isAfterLast(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r2 != 0) goto L_0x0090;
L_0x0068:
r2 = new com.baidu.location.d.j$a; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r2.<init>(r6, r0); Catch:{ Exception -> 0x007a, all -> 0x00bd }
r3 = r2.f17942f; Catch:{ Exception -> 0x007a, all -> 0x00bd }
if (r3 == 0) goto L_0x0076;
L_0x0071:
r3 = r6.f17962f; Catch:{ Exception -> 0x007a, all -> 0x00bd }
r3.add(r2); Catch:{ Exception -> 0x007a, all -> 0x00bd }
L_0x0076:
r0.moveToNext(); Catch:{ Exception -> 0x007a, all -> 0x00bd }
goto L_0x0062;
L_0x007a:
r2 = move-exception;
L_0x007b:
if (r1 == 0) goto L_0x0080;
L_0x007d:
r1.close(); Catch:{ Exception -> 0x00af }
L_0x0080:
if (r0 == 0) goto L_0x0085;
L_0x0082:
r0.close(); Catch:{ Exception -> 0x00b1 }
L_0x0085:
r6.m13930p();
r6.m13929o();
return;
L_0x008c:
r1 = move-exception;
r6.f17955E = r0;
goto L_0x002c;
L_0x0090:
if (r1 == 0) goto L_0x0095;
L_0x0092:
r1.close(); Catch:{ Exception -> 0x00ad }
L_0x0095:
if (r0 == 0) goto L_0x0085;
L_0x0097:
r0.close(); Catch:{ Exception -> 0x009b }
goto L_0x0085;
L_0x009b:
r0 = move-exception;
goto L_0x0085;
L_0x009d:
r1 = move-exception;
r2 = r0;
r5 = r0;
r0 = r1;
r1 = r5;
L_0x00a2:
if (r2 == 0) goto L_0x00a7;
L_0x00a4:
r2.close(); Catch:{ Exception -> 0x00b3 }
L_0x00a7:
if (r1 == 0) goto L_0x00ac;
L_0x00a9:
r1.close(); Catch:{ Exception -> 0x00b5 }
L_0x00ac:
throw r0;
L_0x00ad:
r1 = move-exception;
goto L_0x0095;
L_0x00af:
r1 = move-exception;
goto L_0x0080;
L_0x00b1:
r0 = move-exception;
goto L_0x0085;
L_0x00b3:
r2 = move-exception;
goto L_0x00a7;
L_0x00b5:
r1 = move-exception;
goto L_0x00ac;
L_0x00b7:
r2 = move-exception;
r5 = r2;
r2 = r1;
r1 = r0;
r0 = r5;
goto L_0x00a2;
L_0x00bd:
r2 = move-exception;
r5 = r2;
r2 = r1;
r1 = r0;
r0 = r5;
goto L_0x00a2;
L_0x00c3:
r1 = move-exception;
r1 = r0;
goto L_0x007b;
*/
throw new UnsupportedOperationException("Method not decompiled: com.baidu.location.d.j.e():void");
}
/* renamed from: f */
public void m13941f() {
if (this.f17955E != null) {
try {
this.f17955E.close();
} catch (Exception e) {
}
}
}
/* renamed from: g */
public int m13942g() {
return this.f17969v;
}
}
| 27,187 | 0.504248 | 0.385883 | 866 | 30.393764 | 21.973654 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655889 | false | false | 0 |
1fbeed72cd48cda32a060e0ce41353f04a1f49cb | 15,685,220,571,297 | aed9b9acac54c3b965654d77d1dc9ad510f65bae | /src/com/java/my/设计模式/代理模式/Run_.java | 02b2a5e5724fed65ae433de5626ab1450e1ce662 | [] | no_license | summerVibe/test | https://github.com/summerVibe/test | 207612cf0e345a6550fe46b7e35ba592a7d182ad | 191b193fc3a92125804d582e0894f120921cb379 | refs/heads/master | 2023-02-06T01:38:46.142000 | 2020-12-30T08:11:21 | 2020-12-30T08:11:21 | 213,938,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package my.设计模式.代理模式;
/**
* @author : J
* @version : Jul 5, 2017 2:26:11 PM
* explain :
*/
public class Run_ {
public static void main(String[] args) {
People p1 = new People();
p1.setCash(60000);
p1.setUserName("張三");
People p2 =new People();
p2.setCash(40000);
p2.setUserName("李四");
People p3 =new People();
p3.setCash(0);
p3.setUserName("王五");
p3.setVip("VIP");
ProxyClass proxy_buy = new ProxyClass();
proxy_buy.setPeople(p1);
proxy_buy.buy_myCar();
proxy_buy.setPeople(p2);
proxy_buy.buy_myCar();
proxy_buy.setPeople(p3);
proxy_buy.buy_myCar();
}
}
| UTF-8 | Java | 688 | java | Run_.java | Java | [
{
"context": "package my.设计模式.代理模式;\n/**\n * @author : J\n * @version : Jul 5, 2017 2:26:11 PM\n * explain ",
"end": 41,
"score": 0.9056863784790039,
"start": 40,
"tag": "NAME",
"value": "J"
},
{
"context": " People();\n\t\tp1.setCash(60000);\n\t\tp1.setUserName(\"張三\");\n\t\t\n\t\... | null | [] | package my.设计模式.代理模式;
/**
* @author : J
* @version : Jul 5, 2017 2:26:11 PM
* explain :
*/
public class Run_ {
public static void main(String[] args) {
People p1 = new People();
p1.setCash(60000);
p1.setUserName("張三");
People p2 =new People();
p2.setCash(40000);
p2.setUserName("李四");
People p3 =new People();
p3.setCash(0);
p3.setUserName("王五");
p3.setVip("VIP");
ProxyClass proxy_buy = new ProxyClass();
proxy_buy.setPeople(p1);
proxy_buy.buy_myCar();
proxy_buy.setPeople(p2);
proxy_buy.buy_myCar();
proxy_buy.setPeople(p3);
proxy_buy.buy_myCar();
}
}
| 688 | 0.572727 | 0.521212 | 34 | 18.411764 | 12.090632 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.794118 | false | false | 0 |
fe3b005b557df83af15ac54125658321c439e9f5 | 32,366,873,546,977 | c9829492c2a522ad7032504fee5081148e21dae2 | /src/com/bhtec/service/impl/platform/primarykey/PrimaryKeySeqServiceImpl.java | 89f765960bda9cc8e0b567854f032c0452966aca | [] | no_license | kevinkerry/bhtsys | https://github.com/kevinkerry/bhtsys | e8cef9105d3bd3b3e0ade514110ae3069f8f5cad | 833171c995852a69201fbb207b9077a1cf26ea9f | refs/heads/master | 2021-01-18T02:58:23.960000 | 2011-12-01T12:56:37 | 2011-12-01T12:56:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bhtec.service.impl.platform.primarykey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bhtec.common.constant.PojoVariable;
import com.bhtec.dao.iface.platform.primarykey.PrimaryKeySeqDao;
import com.bhtec.domain.pojo.platform.SysplPrimarykeySeq;
import com.bhtec.service.iface.platform.primarykey.PrimaryKeySeqService;
import com.bhtec.service.impl.BaseServiceImpl;
/**
*功能描述:
*@since Mar 14, 2010 11:57:44 AM
*@author jacobliang
*@version 1.0
*/
public class PrimaryKeySeqServiceImpl extends BaseServiceImpl implements
PrimaryKeySeqService {
private PrimaryKeySeqDao primaryKeySeqDao;
public void deletePrimaryKeySeq(String pojoName) {
}
public List findAllPrimaryKeySeq() {
// TODO Auto-generated method stub
return null;
}
public void savePrimaryKeySeq() {
// TODO Auto-generated method stub
}
public void updatePrimaryKeySeq() {
// TODO Auto-generated method stub
}
public Map getSeqMap() {
List<SysplPrimarykeySeq> seqList = primaryKeySeqDao.getAll(PojoVariable.SYSPL_PRIMARYKEY_SEQ,"");
Map<String,Long> map = new HashMap<String,Long>();
for(int i=0;i<seqList.size();i++){
SysplPrimarykeySeq sysplPrimarykeySeq = seqList.get(i);
String pojoName = sysplPrimarykeySeq.getPojoName();
String primaryKeyName = sysplPrimarykeySeq.getPrimarykeyName();
Long maxId = primaryKeySeqDao.getMaxIdOfTable(pojoName,primaryKeyName);
map.put(pojoName, maxId);
}
return map;
}
public void setPrimaryKeySeqDao(PrimaryKeySeqDao primaryKeySeqDao) {
this.primaryKeySeqDao = primaryKeySeqDao;
}
}
| UTF-8 | Java | 1,674 | java | PrimaryKeySeqServiceImpl.java | Java | [
{
"context": ":\r\n *@since Mar 14, 2010 11:57:44 AM\r\n *@author jacobliang\r\n *@version 1.0\r\n */\r\npublic class PrimaryKeySeqS",
"end": 500,
"score": 0.9964745044708252,
"start": 490,
"tag": "USERNAME",
"value": "jacobliang"
}
] | null | [] | package com.bhtec.service.impl.platform.primarykey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.bhtec.common.constant.PojoVariable;
import com.bhtec.dao.iface.platform.primarykey.PrimaryKeySeqDao;
import com.bhtec.domain.pojo.platform.SysplPrimarykeySeq;
import com.bhtec.service.iface.platform.primarykey.PrimaryKeySeqService;
import com.bhtec.service.impl.BaseServiceImpl;
/**
*功能描述:
*@since Mar 14, 2010 11:57:44 AM
*@author jacobliang
*@version 1.0
*/
public class PrimaryKeySeqServiceImpl extends BaseServiceImpl implements
PrimaryKeySeqService {
private PrimaryKeySeqDao primaryKeySeqDao;
public void deletePrimaryKeySeq(String pojoName) {
}
public List findAllPrimaryKeySeq() {
// TODO Auto-generated method stub
return null;
}
public void savePrimaryKeySeq() {
// TODO Auto-generated method stub
}
public void updatePrimaryKeySeq() {
// TODO Auto-generated method stub
}
public Map getSeqMap() {
List<SysplPrimarykeySeq> seqList = primaryKeySeqDao.getAll(PojoVariable.SYSPL_PRIMARYKEY_SEQ,"");
Map<String,Long> map = new HashMap<String,Long>();
for(int i=0;i<seqList.size();i++){
SysplPrimarykeySeq sysplPrimarykeySeq = seqList.get(i);
String pojoName = sysplPrimarykeySeq.getPojoName();
String primaryKeyName = sysplPrimarykeySeq.getPrimarykeyName();
Long maxId = primaryKeySeqDao.getMaxIdOfTable(pojoName,primaryKeyName);
map.put(pojoName, maxId);
}
return map;
}
public void setPrimaryKeySeqDao(PrimaryKeySeqDao primaryKeySeqDao) {
this.primaryKeySeqDao = primaryKeySeqDao;
}
}
| 1,674 | 0.742188 | 0.733173 | 59 | 26.20339 | 25.575928 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.440678 | false | false | 0 |
6f106d6ff622c69af31711ed200e806ab6809f7a | 14,731,737,837,482 | 16ed4d34e8995292434190b0371273ab5dfbdbc9 | /src/main/java/com/petsuite/Services/dto/WalkInvoice_Dto.java | 753bfaeb09176b27c48a3789dc9b8095aacac822 | [] | no_license | esgonzalezca/PetSuiteBack | https://github.com/esgonzalezca/PetSuiteBack | 900a45e0103cbd1d6650f4d344df01441305163d | 439a630d969f4bb8af3f720644e4a8702207ca29 | refs/heads/master | 2023-06-19T12:21:37.903000 | 2021-07-06T02:33:37 | 2021-07-06T02:33:37 | 246,206,329 | 0 | 2 | null | false | 2021-07-06T01:09:57 | 2020-03-10T04:14:55 | 2021-07-05T22:45:37 | 2021-07-06T01:09:56 | 565 | 0 | 0 | 0 | Java | false | false | package com.petsuite.Services.dto;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WalkInvoice_Dto {
private Integer walk_invoice_id;
private float walk_invoice_price;
private String walk_invoice_status;
private String client_id;
private String dog_walker_id;
private String walk_invoice_notes;
private Integer dog_id;
private Float walker_score;
private LocalDateTime walk_invoice_date;
private String walk_invoice_address;
private Float walk_invoice_duration;
private String dog_name;
private String dog_race;
private float dog_height;
private float dog_weight;
}
| UTF-8 | Java | 761 | java | WalkInvoice_Dto.java | Java | [] | null | [] | package com.petsuite.Services.dto;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WalkInvoice_Dto {
private Integer walk_invoice_id;
private float walk_invoice_price;
private String walk_invoice_status;
private String client_id;
private String dog_walker_id;
private String walk_invoice_notes;
private Integer dog_id;
private Float walker_score;
private LocalDateTime walk_invoice_date;
private String walk_invoice_address;
private Float walk_invoice_duration;
private String dog_name;
private String dog_race;
private float dog_height;
private float dog_weight;
}
| 761 | 0.755585 | 0.755585 | 29 | 25.206896 | 13.744916 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 0 |
1dfafa87c21d4cdf2c503f3b3a8037ec8c3f9cf9 | 7,404,523,623,028 | 17e37ca416a82f4081f01df86941ca6e5ae4c914 | /core-projects/nhm-language-definition/src/main/java/uk/org/cse/nhm/language/definition/two/dates/XSingleDate.java | f27b3b121532d2fcbbd4d788c8ca04e1c2e67982 | [] | no_license | decc/national-household-model-core-components | https://github.com/decc/national-household-model-core-components | d0c8e08c9d23da4c6812df9e07b69eadf7fa16a4 | 31b72cdb3ddaf834a3ba57954d42f531004786b9 | refs/heads/master | 2020-05-26T00:33:53.193000 | 2017-08-29T14:23:05 | 2017-08-29T14:23:05 | 57,210,476 | 0 | 1 | null | false | 2017-04-04T13:45:41 | 2016-04-27T12:08:08 | 2016-05-20T11:26:41 | 2017-04-04T13:45:41 | 41,739 | 0 | 0 | 3 | Java | null | null | package uk.org.cse.nhm.language.definition.two.dates;
import org.joda.time.DateTime;
import uk.org.cse.nhm.language.definition.Doc;
import uk.org.cse.nhm.language.two.build.IBuilder;
import com.larkery.jasb.bind.Bind;
import com.larkery.jasb.bind.BindPositionalArgument;
@Doc({
"Contains a single date; these can also be written in the form dd/mm/yyyy."
})
@Bind("just")
public class XSingleDate extends XDate {
protected DateTime date;
@BindPositionalArgument(0)
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
@Override
public DateTime asDate(IBuilder builder) {
return date;
}
}
| UTF-8 | Java | 660 | java | XSingleDate.java | Java | [] | null | [] | package uk.org.cse.nhm.language.definition.two.dates;
import org.joda.time.DateTime;
import uk.org.cse.nhm.language.definition.Doc;
import uk.org.cse.nhm.language.two.build.IBuilder;
import com.larkery.jasb.bind.Bind;
import com.larkery.jasb.bind.BindPositionalArgument;
@Doc({
"Contains a single date; these can also be written in the form dd/mm/yyyy."
})
@Bind("just")
public class XSingleDate extends XDate {
protected DateTime date;
@BindPositionalArgument(0)
public DateTime getDate() {
return date;
}
public void setDate(DateTime date) {
this.date = date;
}
@Override
public DateTime asDate(IBuilder builder) {
return date;
}
}
| 660 | 0.74697 | 0.745455 | 32 | 19.625 | 20.668137 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.90625 | false | false | 0 |
0de00949246da451154ad21c428eb4ee04212f84 | 7,404,523,622,734 | 3eed31d4c45f7628a7fe8f088d19ea2357125e78 | /wam/adminm/src/main/java/com/ingenico/ams/wam/adminm/service/report/engine/AbstractReportPrinter.java | 636a97badd5adeea5213ce352bd9ec02118dfa9c | [] | no_license | somaizouhaier/helpProject | https://github.com/somaizouhaier/helpProject | 38d82cd7945d7ae38883beaa8157a4fabda06146 | d90baff8e2c79b8fe7cdab988cf39eb317fe6f1d | refs/heads/master | 2017-04-23T00:32:57.991000 | 2016-08-31T21:12:05 | 2016-08-31T21:12:05 | 65,663,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.ingenico.ams.wam.adminm.service.report.engine;
import java.io.ByteArrayOutputStream;
import org.slf4j.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
/**
* @author czhu
*
*/
public abstract class AbstractReportPrinter implements ReportPrinter {
private static final String MSG_ERROR_DURING_REPORT_EXPORT = "Une erreur s'est produite pendant la phase d'export du rapport";
@Override
public abstract ByteArrayOutputStream print(JasperPrint jasperPrint);
protected abstract Logger getLogger();
protected String logErrorAndThrowIllegalStateException(JRException e) {
getLogger().error(MSG_ERROR_DURING_REPORT_EXPORT, e);
throw new IllegalStateException(MSG_ERROR_DURING_REPORT_EXPORT, e);
}
}
| UTF-8 | Java | 790 | java | AbstractReportPrinter.java | Java | [
{
"context": ".jasperreports.engine.JasperPrint;\n\n/**\n * @author czhu\n *\n */\npublic abstract class AbstractReportPrinte",
"end": 253,
"score": 0.9995839595794678,
"start": 249,
"tag": "USERNAME",
"value": "czhu"
}
] | null | [] | /**
*
*/
package com.ingenico.ams.wam.adminm.service.report.engine;
import java.io.ByteArrayOutputStream;
import org.slf4j.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
/**
* @author czhu
*
*/
public abstract class AbstractReportPrinter implements ReportPrinter {
private static final String MSG_ERROR_DURING_REPORT_EXPORT = "Une erreur s'est produite pendant la phase d'export du rapport";
@Override
public abstract ByteArrayOutputStream print(JasperPrint jasperPrint);
protected abstract Logger getLogger();
protected String logErrorAndThrowIllegalStateException(JRException e) {
getLogger().error(MSG_ERROR_DURING_REPORT_EXPORT, e);
throw new IllegalStateException(MSG_ERROR_DURING_REPORT_EXPORT, e);
}
}
| 790 | 0.786076 | 0.78481 | 30 | 25.333334 | 32.286564 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 0 |
a646ee2c48a48cc9bc4a962e5a9c01591cd10086 | 19,902,878,518,749 | 9b7b7c2862ee705c4efd5491cd389bb144b084b5 | /src/领扣算法/A简单题/字符串的最大公因子/Main.java | 85a4940e8cb7f3b24112c4bf5fc2d3d787f862f9 | [] | no_license | g1587613421/arithmetic | https://github.com/g1587613421/arithmetic | 5bf16083df2b9791d6ff09ea4463610184a250cb | 22f99afb5f785eadb8cff57ec09c635dead69d50 | refs/heads/master | 2021-07-10T03:19:08.413000 | 2021-04-02T00:58:25 | 2021-04-02T00:58:25 | 235,080,687 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2020.版权所有高金磊
*/
package 领扣算法.A简单题.字符串的最大公因子;
public class Main {
public String gcdOfStrings(String str1, String str2) {
int size=Math.min(str1.length(), str2.length())+1;
String ss;
for (int i = size; i>0 ; i--) {
ss=str1.substring(0,i);
if (str1.replaceAll(ss, "").length()==0&&str2.replaceAll(ss, "").length()==0){
return ss;
}
}
return "";
}
}
| UTF-8 | Java | 509 | java | Main.java | Java | [
{
"context": "/*\n * Copyright (c) 2020.版权所有高金磊\n */\n\npackage 领扣算法.A简单题.字符串的最大公因子;\n\npublic class M",
"end": 32,
"score": 0.9994382858276367,
"start": 29,
"tag": "NAME",
"value": "高金磊"
}
] | null | [] | /*
* Copyright (c) 2020.版权所有高金磊
*/
package 领扣算法.A简单题.字符串的最大公因子;
public class Main {
public String gcdOfStrings(String str1, String str2) {
int size=Math.min(str1.length(), str2.length())+1;
String ss;
for (int i = size; i>0 ; i--) {
ss=str1.substring(0,i);
if (str1.replaceAll(ss, "").length()==0&&str2.replaceAll(ss, "").length()==0){
return ss;
}
}
return "";
}
}
| 509 | 0.518359 | 0.483801 | 20 | 22.15 | 23.597193 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.