blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15600525fad55a2745188eb1c9546cbf0a781f76 | 21,912,923,172,200 | 28c33b30f0799cc3dd04dadb9ce4a17e1368a99e | /GradeDisplay.java | 184dd3d32f7e0652b6db3f544c1071d108c74f42 | [] | no_license | sujanchhetri/javasoln | https://github.com/sujanchhetri/javasoln | d2af881ecb447f65690fc49f0eee33e98de8d46f | fa1eca357cddae5d4c905e0dd494a390a92f00bc | refs/heads/main | 2023-02-06T17:36:24.038000 | 2020-12-19T07:15:44 | 2020-12-19T07:15:44 | 322,768,627 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class GradeDisplay {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Grade (0-100):");
Integer grade = in.nextInt();
if(grade >=90 && grade<=100){
System.out.println("Letter Grade is A");
}
else if(grade >=80 && grade<=89){
System.out.println("Letter Grade is B");
}
else if(grade >=70 && grade<=79){
System.out.println("Letter Grade is C");
}
else if(grade >=60 && grade<=69){
System.out.println("Letter Grade is D");
}
else if(grade <60){
System.out.println("Letter Grade is F");
}
else{
System.out.println("Grade entered is not in range");
}
}
}
| UTF-8 | Java | 836 | java | GradeDisplay.java | Java | [] | null | [] | import java.util.*;
public class GradeDisplay {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Grade (0-100):");
Integer grade = in.nextInt();
if(grade >=90 && grade<=100){
System.out.println("Letter Grade is A");
}
else if(grade >=80 && grade<=89){
System.out.println("Letter Grade is B");
}
else if(grade >=70 && grade<=79){
System.out.println("Letter Grade is C");
}
else if(grade >=60 && grade<=69){
System.out.println("Letter Grade is D");
}
else if(grade <60){
System.out.println("Letter Grade is F");
}
else{
System.out.println("Grade entered is not in range");
}
}
}
| 836 | 0.510766 | 0.483254 | 28 | 28.857143 | 19.738857 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 9 |
d32d0ede3ff10f95b501f8abe41142937f0b8cdc | 21,431,886,839,337 | 8d90d9246881b3dc27b941185518148b837d9fa2 | /Practice-2020/Feb2020/java/PathBasedSCC.java | d8a3d2da387a6e8b9aace2568dcbf79f7683d138 | [] | no_license | su225/algorithmic-programming | https://github.com/su225/algorithmic-programming | 5c53e18240e700c839b61b3f3cb81548711bc418 | 67afb648b3495a97a77dbab6cbae97ade23dbeee | refs/heads/master | 2021-09-28T23:20:41.658000 | 2021-09-28T09:27:23 | 2021-09-28T09:27:23 | 141,442,341 | 0 | 0 | null | false | 2021-09-30T18:51:38 | 2018-07-18T13:58:41 | 2021-09-30T18:41:34 | 2021-09-30T18:51:37 | 2,303 | 0 | 0 | 0 | Java | false | false | import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class PathBasedSCC {
private Graph g;
private boolean[] isSCCAssigned;
private Stack<Integer> sccNotAssigned;
private Stack<Integer> sccAmbiguous;
private int[] preorder;
private int tick;
private List<List<Integer>> sccList;
private List<List<Integer>> solve(Graph g) {
int nodeCount = g.getNodeCount();
this.g = g;
this.isSCCAssigned = new boolean[nodeCount];
this.sccNotAssigned = new Stack<>();
this.sccAmbiguous = new Stack<>();
this.preorder = new int[nodeCount];
this.tick = 1;
this.sccList = new ArrayList<>();
for (int v = 0; v < nodeCount; v++) {
if (preorder[v] == 0) {
doSolve(v);
}
}
return sccList;
}
private void doSolve(int v) {
isSCCAssigned[v] = false;
sccNotAssigned.push(v);
sccAmbiguous.push(v);
preorder[v] = tick;
tick++;
for (int u : g.adjacent(v)) {
if (preorder[u] == 0) {
doSolve(u);
} else if (!isSCCAssigned[u]) {
while (!sccAmbiguous.isEmpty() && preorder[sccAmbiguous.peek()] > preorder[u]) {
sccAmbiguous.pop();
}
}
}
if (sccAmbiguous.peek() == v) {
List<Integer> scc = new ArrayList<>();
while (!sccNotAssigned.isEmpty() && sccNotAssigned.peek() != v) {
int popped = sccNotAssigned.pop();
isSCCAssigned[popped] = true;
scc.add(popped);
}
scc.add(v); isSCCAssigned[v] = true;
sccAmbiguous.pop(); sccNotAssigned.pop();
sccList.add(scc);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numNodes = in.nextInt();
int numEdges = in.nextInt();
Graph g = new Graph(numNodes);
for (int i = 0; i < numEdges; ++i) {
int fromNodeID = in.nextInt();
int toNodeID = in.nextInt();
g.addEdge(fromNodeID, toNodeID);
}
PathBasedSCC pathBasedSCCFinder = new PathBasedSCC();
List<List<Integer>> stronglyConnectedComponents = pathBasedSCCFinder.solve(g);
printSCC(stronglyConnectedComponents);
}
private static void printSCC(List<List<Integer>> stronglyConnectedComponents) {
for (int i = 0; i < stronglyConnectedComponents.size(); ++i) {
System.out.printf("%d: ", i);
for (int x : stronglyConnectedComponents.get(i)) {
System.out.printf("%d ", x);
}
System.out.println();
}
}
}
class Graph {
private final Map<Integer,List<Integer>> adjList;
private final int nodeCount;
private int edgeCount;
public Graph(int nodeCount) {
this.nodeCount = nodeCount;
this.adjList = new HashMap<>();
for (int i = 0; i < nodeCount; ++i) {
adjList.put(i, new ArrayList<>());
}
}
public int getNodeCount() { return nodeCount; }
public int getEdgeCount() { return edgeCount; }
public List<Integer> adjacent(int nodeID) {
if (!isValidNodeID(nodeID)) {
throw new IllegalArgumentException("nodeID should be valid");
}
return adjList.get(nodeID);
}
public void addEdge(int from, int to) {
if (!isValidNodeID(from) && !isValidNodeID(to)) {
throw new IllegalArgumentException("to and from nodeIDs should be valid");
}
adjList.get(from).add(to);
this.edgeCount++;
}
private boolean isValidNodeID(int nodeID) {
return nodeID >= 0 && nodeID < nodeCount;
}
} | UTF-8 | Java | 3,475 | java | PathBasedSCC.java | Java | [] | null | [] | import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class PathBasedSCC {
private Graph g;
private boolean[] isSCCAssigned;
private Stack<Integer> sccNotAssigned;
private Stack<Integer> sccAmbiguous;
private int[] preorder;
private int tick;
private List<List<Integer>> sccList;
private List<List<Integer>> solve(Graph g) {
int nodeCount = g.getNodeCount();
this.g = g;
this.isSCCAssigned = new boolean[nodeCount];
this.sccNotAssigned = new Stack<>();
this.sccAmbiguous = new Stack<>();
this.preorder = new int[nodeCount];
this.tick = 1;
this.sccList = new ArrayList<>();
for (int v = 0; v < nodeCount; v++) {
if (preorder[v] == 0) {
doSolve(v);
}
}
return sccList;
}
private void doSolve(int v) {
isSCCAssigned[v] = false;
sccNotAssigned.push(v);
sccAmbiguous.push(v);
preorder[v] = tick;
tick++;
for (int u : g.adjacent(v)) {
if (preorder[u] == 0) {
doSolve(u);
} else if (!isSCCAssigned[u]) {
while (!sccAmbiguous.isEmpty() && preorder[sccAmbiguous.peek()] > preorder[u]) {
sccAmbiguous.pop();
}
}
}
if (sccAmbiguous.peek() == v) {
List<Integer> scc = new ArrayList<>();
while (!sccNotAssigned.isEmpty() && sccNotAssigned.peek() != v) {
int popped = sccNotAssigned.pop();
isSCCAssigned[popped] = true;
scc.add(popped);
}
scc.add(v); isSCCAssigned[v] = true;
sccAmbiguous.pop(); sccNotAssigned.pop();
sccList.add(scc);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numNodes = in.nextInt();
int numEdges = in.nextInt();
Graph g = new Graph(numNodes);
for (int i = 0; i < numEdges; ++i) {
int fromNodeID = in.nextInt();
int toNodeID = in.nextInt();
g.addEdge(fromNodeID, toNodeID);
}
PathBasedSCC pathBasedSCCFinder = new PathBasedSCC();
List<List<Integer>> stronglyConnectedComponents = pathBasedSCCFinder.solve(g);
printSCC(stronglyConnectedComponents);
}
private static void printSCC(List<List<Integer>> stronglyConnectedComponents) {
for (int i = 0; i < stronglyConnectedComponents.size(); ++i) {
System.out.printf("%d: ", i);
for (int x : stronglyConnectedComponents.get(i)) {
System.out.printf("%d ", x);
}
System.out.println();
}
}
}
class Graph {
private final Map<Integer,List<Integer>> adjList;
private final int nodeCount;
private int edgeCount;
public Graph(int nodeCount) {
this.nodeCount = nodeCount;
this.adjList = new HashMap<>();
for (int i = 0; i < nodeCount; ++i) {
adjList.put(i, new ArrayList<>());
}
}
public int getNodeCount() { return nodeCount; }
public int getEdgeCount() { return edgeCount; }
public List<Integer> adjacent(int nodeID) {
if (!isValidNodeID(nodeID)) {
throw new IllegalArgumentException("nodeID should be valid");
}
return adjList.get(nodeID);
}
public void addEdge(int from, int to) {
if (!isValidNodeID(from) && !isValidNodeID(to)) {
throw new IllegalArgumentException("to and from nodeIDs should be valid");
}
adjList.get(from).add(to);
this.edgeCount++;
}
private boolean isValidNodeID(int nodeID) {
return nodeID >= 0 && nodeID < nodeCount;
}
} | 3,475 | 0.627338 | 0.625036 | 124 | 27.032259 | 20.172617 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 9 |
fe3c234f3570a9a777b1d26a3d2ef2980ef10cde | 6,330,781,845,286 | 5e02dfd09bf572828fd8bf681144cb16a3e641c8 | /src/main/java/pageobjects/Seller/OfferLetterPage.java | 31ca43be6140685b8a0b15de18b405bbc180bd39 | [] | no_license | NaugolnyhN/OrderFlowTravelataTest | https://github.com/NaugolnyhN/OrderFlowTravelataTest | 686674e373d5a71df9c04fa82755cc5ed74b82e8 | 90de32504150857fed1f21e38e4444399373cb3e | refs/heads/master | 2018-01-08T08:16:27.270000 | 2015-12-28T13:39:12 | 2015-12-28T13:39:12 | 44,386,663 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pageobjects.Seller;
import framework.WebDriverCommands;
import org.openqa.selenium.By;
/**
* Created by User on 10.12.2015.
*/
public class OfferLetterPage extends WebDriverCommands
{
private final String GREETING_HEAD = "//h1[contains(@data-bind, 'greetingHead')]";
private final String GREETING_TEXT = "greetingText";/*id*/
//private final String REMOVE_OFFER_BUTTON = "removeFromOffer";/*id*/
private final String REMOVE_OFFER_BUTTON = "(//a[@id = 'removeFromOffer'])[1]";
private final String DEPARTURE_CITY_DROPDOWN = "//select[contains(@data-bind, 'departureCity')]";
private final String DEPARTURE_CITY_VALUE = "//select[contains(@data-bind, 'departureCity')]/option[text(), '%s']";
private final String DATE_FROM = "//input[contains(@data-bind, 'dateFrom')]";
private final String NIGHTS_DROPDOWN = "//select[contains(@data-bind, 'nights')]";
private final String NIGHTS_VALLUE = "//select[contains(@data-bind, 'nights')]/option[text() = '%s']";
private final String ROOM_TYPE = "//input[contains(@data-bind, 'roomCode')]";
private final String MEAL_DROPDOWN = "//select[contains(@data-bind, 'meal')]";
private final String MEAL_VALUE = "//select[contains(@data-bind, 'meal')]/option[contains(text(), '%s')]";
private final String ADULTS_DROPDOWN = "//select[contains(@data-bind, 'adults')]";
private final String ADULTS_VALUE = "//select[contains(@data-bind, 'adults')]/option[text() = '%s']";
private final String KIDS_DROPDOWN = "//select[contains(@data-bind, 'kids')]";
private final String KIDS_VALUE = "//select[contains(@data-bind, 'kids')]/option[text() = '%s']";
private final String INFANTS_DROPDOWN = "//select[contains(@data-bind, 'infants')]";
private final String INFANTS_VALUE = "//select[contains(@data-bind, 'infants')]/option[text() = '%s']";
private final String TOUR_CLASS_DROPDOWN = "//select[contains(@data-bind, 'selectClass')]";
private final String TOUR_CLASS_VALUE = "//select[contains(@data-bind, 'selectClass')]/option[value = '%s']";/*economy or business*/
private final String DEPARTURE_AIRPORT_DROPDOWN = "(//div[contains(@class, 'departure')]/span/span)[%s]";
private final String ARRIVAL_AIRPORT_DROPDOWN = "(//div[@class = 'arrival']/span/span)[%s]";
private final String AIR_COMPANY_DROPDOWN = "//div[@class = 'otherInfo']/div/span/span/span";
private final String FLIGHT_NUMBER = "//input[contains(@class, 'flightNumber')]";
private final String FLIGHT_DATE_FROM = "//input[contains(@data-bind, 'dateForward')]";
private final String FLIGHT_DATE_TO = "//input[contains(@data-bind, 'dateBackward')]";
private final String TRANSFER_TYPE_DROPDOWN = "//select[contains(@data-bind, 'transferType')]";
private final String TRANSFER_TYPE_VALUE = "//select[contains(@data-bind, 'transferType')]/option[%s]";
private final String MEDICAL_INSURANCE_DROPDOWN = "//select[contains(@data-bind, 'medicalInsurance')]";
private final String MEDICAL_INSURANCE_VALUE = "//select[contains(@data-bind, 'medicalInsurance')]/option[%s]";
private final String ADDITIONAL_TERMS_FIELD = "//textarea[contains(@data-bind, 'additionalTerms')]";
private final String OIL_TAX_FIELD = "//input[contains(@data-bind, 'oilTax')]";
private final String PRICE_FIELD = "//input[contains(@data-bind, 'price')]";
private final String FIRST_PAYMENT_FIELD = "//input[contains(@data-bind, 'firstPayment')]";
private final String OFFER_TOUR_PRICE = "offerTourPrice";/*class*/
private final String ADD_NEW_HOTEL = "addNewHotel";/*class*/
private final String HOTEL_NAME_FIELD = "//input[@placeholder = 'Имя отеля']";
private final String RESORT_NAME_DROPDOWN = "//span[text() = 'Курорт']";
private final String RESORT_NAME_FIELD = "//input[@type = 'search']";
private final String RESORT_NAME_VALUE = "//li[@role = 'treeitem' and text() = '%s']";
private final String CANCEL_HOTEL_ADD_BUTTON = "cancelHotelAdd";/*id*/
private final String HOTEL_ADD_BUTTON = "//button[text() = 'Добавить']";
private final String OFFER_PREVIEW_BUTTON = "//a[text() = 'Предпросмотр']";
private final String PHOTO_GALLERY = "(//a[@data-lightbox = 'gallery']/img)[1]";
private final String DATES_VALUE = "//dt[text() = 'Даты поездки']/dd";
private final String DURATION_VALUE = "//dt[text() = 'Длительность']/dd";
private final String ROOM_TYPE_VALUE = "//dt[text() = 'Тип комнаты']/dd";
private final String MEAL_TYPE_VALUE = "//dt[text() = 'Питание']/dd";
private final String OIL_TAX_VALUE = "//dt[text() = 'Топливный сбор']/dd";
private final String TOUR_PRICE_VALUE = "//dt[text() = 'Цена пакета']/dd";
public OfferLetterPage removeFromOffer()
{
By byRemoveFromOfferButton = By.xpath(REMOVE_OFFER_BUTTON);
waitForElementDisplayed(byRemoveFromOfferButton, 10);
click(byRemoveFromOfferButton);
return this;
}
public OfferLetterPage selectDepartureCityDropdown() throws Exception
{
By byDepartureCityDropDown = By.xpath(DEPARTURE_CITY_DROPDOWN);
waitForElementDisplayed(byDepartureCityDropDown, CONSTANT_3_SECONDS);
click(byDepartureCityDropDown);
return this;
}
public OfferLetterPage selectDepartureCityValue()
{
By byDepartureCityValue = By.xpath(String.format(DEPARTURE_CITY_VALUE, "Санкт-Петербург"));
waitForElementDisplayed(byDepartureCityValue, CONSTANT_3_SECONDS);
click(byDepartureCityValue);
return this;
}
public OfferLetterPage selectNightsDropdown()
{
By byNightsDropdown = By.xpath(NIGHTS_DROPDOWN);
waitForElementDisplayed(byNightsDropdown, CONSTANT_3_SECONDS);
click(byNightsDropdown);
return this;
}
public OfferLetterPage selectNightsValue()
{
By byNightsValue
return this;
}
}
| UTF-8 | Java | 6,025 | java | OfferLetterPage.java | Java | [
{
"context": "tring HOTEL_NAME_FIELD = \"//input[@placeholder = 'Имя отеля']\";\n private final String RESORT_NAME_DROPDOWN",
"end": 3678,
"score": 0.9988083839416504,
"start": 3669,
"tag": "NAME",
"value": "Имя отеля"
}
] | null | [] | package pageobjects.Seller;
import framework.WebDriverCommands;
import org.openqa.selenium.By;
/**
* Created by User on 10.12.2015.
*/
public class OfferLetterPage extends WebDriverCommands
{
private final String GREETING_HEAD = "//h1[contains(@data-bind, 'greetingHead')]";
private final String GREETING_TEXT = "greetingText";/*id*/
//private final String REMOVE_OFFER_BUTTON = "removeFromOffer";/*id*/
private final String REMOVE_OFFER_BUTTON = "(//a[@id = 'removeFromOffer'])[1]";
private final String DEPARTURE_CITY_DROPDOWN = "//select[contains(@data-bind, 'departureCity')]";
private final String DEPARTURE_CITY_VALUE = "//select[contains(@data-bind, 'departureCity')]/option[text(), '%s']";
private final String DATE_FROM = "//input[contains(@data-bind, 'dateFrom')]";
private final String NIGHTS_DROPDOWN = "//select[contains(@data-bind, 'nights')]";
private final String NIGHTS_VALLUE = "//select[contains(@data-bind, 'nights')]/option[text() = '%s']";
private final String ROOM_TYPE = "//input[contains(@data-bind, 'roomCode')]";
private final String MEAL_DROPDOWN = "//select[contains(@data-bind, 'meal')]";
private final String MEAL_VALUE = "//select[contains(@data-bind, 'meal')]/option[contains(text(), '%s')]";
private final String ADULTS_DROPDOWN = "//select[contains(@data-bind, 'adults')]";
private final String ADULTS_VALUE = "//select[contains(@data-bind, 'adults')]/option[text() = '%s']";
private final String KIDS_DROPDOWN = "//select[contains(@data-bind, 'kids')]";
private final String KIDS_VALUE = "//select[contains(@data-bind, 'kids')]/option[text() = '%s']";
private final String INFANTS_DROPDOWN = "//select[contains(@data-bind, 'infants')]";
private final String INFANTS_VALUE = "//select[contains(@data-bind, 'infants')]/option[text() = '%s']";
private final String TOUR_CLASS_DROPDOWN = "//select[contains(@data-bind, 'selectClass')]";
private final String TOUR_CLASS_VALUE = "//select[contains(@data-bind, 'selectClass')]/option[value = '%s']";/*economy or business*/
private final String DEPARTURE_AIRPORT_DROPDOWN = "(//div[contains(@class, 'departure')]/span/span)[%s]";
private final String ARRIVAL_AIRPORT_DROPDOWN = "(//div[@class = 'arrival']/span/span)[%s]";
private final String AIR_COMPANY_DROPDOWN = "//div[@class = 'otherInfo']/div/span/span/span";
private final String FLIGHT_NUMBER = "//input[contains(@class, 'flightNumber')]";
private final String FLIGHT_DATE_FROM = "//input[contains(@data-bind, 'dateForward')]";
private final String FLIGHT_DATE_TO = "//input[contains(@data-bind, 'dateBackward')]";
private final String TRANSFER_TYPE_DROPDOWN = "//select[contains(@data-bind, 'transferType')]";
private final String TRANSFER_TYPE_VALUE = "//select[contains(@data-bind, 'transferType')]/option[%s]";
private final String MEDICAL_INSURANCE_DROPDOWN = "//select[contains(@data-bind, 'medicalInsurance')]";
private final String MEDICAL_INSURANCE_VALUE = "//select[contains(@data-bind, 'medicalInsurance')]/option[%s]";
private final String ADDITIONAL_TERMS_FIELD = "//textarea[contains(@data-bind, 'additionalTerms')]";
private final String OIL_TAX_FIELD = "//input[contains(@data-bind, 'oilTax')]";
private final String PRICE_FIELD = "//input[contains(@data-bind, 'price')]";
private final String FIRST_PAYMENT_FIELD = "//input[contains(@data-bind, 'firstPayment')]";
private final String OFFER_TOUR_PRICE = "offerTourPrice";/*class*/
private final String ADD_NEW_HOTEL = "addNewHotel";/*class*/
private final String HOTEL_NAME_FIELD = "//input[@placeholder = '<NAME>']";
private final String RESORT_NAME_DROPDOWN = "//span[text() = 'Курорт']";
private final String RESORT_NAME_FIELD = "//input[@type = 'search']";
private final String RESORT_NAME_VALUE = "//li[@role = 'treeitem' and text() = '%s']";
private final String CANCEL_HOTEL_ADD_BUTTON = "cancelHotelAdd";/*id*/
private final String HOTEL_ADD_BUTTON = "//button[text() = 'Добавить']";
private final String OFFER_PREVIEW_BUTTON = "//a[text() = 'Предпросмотр']";
private final String PHOTO_GALLERY = "(//a[@data-lightbox = 'gallery']/img)[1]";
private final String DATES_VALUE = "//dt[text() = 'Даты поездки']/dd";
private final String DURATION_VALUE = "//dt[text() = 'Длительность']/dd";
private final String ROOM_TYPE_VALUE = "//dt[text() = 'Тип комнаты']/dd";
private final String MEAL_TYPE_VALUE = "//dt[text() = 'Питание']/dd";
private final String OIL_TAX_VALUE = "//dt[text() = 'Топливный сбор']/dd";
private final String TOUR_PRICE_VALUE = "//dt[text() = 'Цена пакета']/dd";
public OfferLetterPage removeFromOffer()
{
By byRemoveFromOfferButton = By.xpath(REMOVE_OFFER_BUTTON);
waitForElementDisplayed(byRemoveFromOfferButton, 10);
click(byRemoveFromOfferButton);
return this;
}
public OfferLetterPage selectDepartureCityDropdown() throws Exception
{
By byDepartureCityDropDown = By.xpath(DEPARTURE_CITY_DROPDOWN);
waitForElementDisplayed(byDepartureCityDropDown, CONSTANT_3_SECONDS);
click(byDepartureCityDropDown);
return this;
}
public OfferLetterPage selectDepartureCityValue()
{
By byDepartureCityValue = By.xpath(String.format(DEPARTURE_CITY_VALUE, "Санкт-Петербург"));
waitForElementDisplayed(byDepartureCityValue, CONSTANT_3_SECONDS);
click(byDepartureCityValue);
return this;
}
public OfferLetterPage selectNightsDropdown()
{
By byNightsDropdown = By.xpath(NIGHTS_DROPDOWN);
waitForElementDisplayed(byNightsDropdown, CONSTANT_3_SECONDS);
click(byNightsDropdown);
return this;
}
public OfferLetterPage selectNightsValue()
{
By byNightsValue
return this;
}
}
| 6,014 | 0.681096 | 0.67839 | 114 | 50.877193 | 40.283237 | 136 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.929825 | false | false | 9 |
de2eff217378a324976a1e0017f7798232ec66cf | 9,131,100,491,728 | 0e406dc1a3afd9a1b5e5b2c2aabe7a2fe728cddd | /Bataille/Bataille.java | 3094a3306090fc925ab44d5482621673dafeec62 | [] | no_license | Matx99/Java-L3PW | https://github.com/Matx99/Java-L3PW | ce0786ee3c8baa2caba59010aa34265e427d62dd | 349da9f6bd803b35599a2bafb0efeba6fc6f80b9 | refs/heads/master | 2020-08-09T18:45:57.279000 | 2019-12-10T11:25:28 | 2019-12-10T11:25:28 | 214,146,813 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.mat.bataille;
import java.util.*;
public class Bataille {
public static void main(String[] args) {
// TODO Auto-generated method stub
// on créé les deux joueurs
Joueur joueur1 = new Joueur();
Joueur joueur2 = new Joueur();
//on créé toutes les cartes possibles
ArrayList<Carte> bataille = new ArrayList<Carte>();
for(int i = 0; i < Carte.couleurs.length; i++){// tant que i est plus petit que le nombre de couleurs, on l'incremente
for(int j = 0; j < Carte.valeurs.length; j++){// tant que j est plus petit que le nombre de couleurs, on l'incremente
Carte carte = new Carte (i,j);// puis on créé une carte à chaque tour de la boucle for
bataille.add(carte);// et on l'ajoute à la bataille
}
}
// mélange du jeu
Collections.shuffle(bataille); // la consigne indique math.random mais j'utilise https://www.geeksforgeeks.org/collections-shuffle-java-examples/
// initialisation des paquets
for(int i = 0; i < bataille.size() ; i++) { // tant qu'il reste des cartes, on continue la boucle
if(i % 2 == 0) // i % 2 permet d'avoir un résultat impair (1) une fois sur deux (sinon c'est 0...) et donc de distribuer les cartes 1 fois sur 2 à chaque joueur
joueur1.addCarte(bataille.get(i)); // si 1 % 2 == 0 alors on ajoute au paquet du joueur1 la carte qui se trouve à l'index i (https://www.geeksforgeeks.org/arraylist-get-method-java-examples/)
else
joueur2.addCarte(bataille.get(i)); // sinon on ajoute la carte au paquet du joueur2
}
// deroulement d'une partie
while(joueur1.getPaquet().size() != 0 && joueur2.getPaquet().size() != 0){// tant que les deux joueurs ont encore des cartes, la partie continue
// initialisation des paquets
Carte carteJoueur1 = joueur1.pickCarte();
Carte carteJoueur2 = joueur2.pickCarte();
if(carteJoueur1.comparateur(carteJoueur2) > 0) { // si la valeur de la carte du j1 et > à celle du j2
joueur1.gagnePoint(); // alors j1 gagne un pt
joueur1.addCarte(carteJoueur1);
joueur1.addCarte(carteJoueur2); // puis il recupere les cartes
}
else { // sinon
joueur2.gagnePoint(); // j2 gagne un pt
joueur2.addCarte(carteJoueur2);
joueur2.addCarte(carteJoueur1); // puis il recupere les cartes
}
System.out.println("Nombre de cartes du Joueur 1 " + joueur1.getPaquet().size() + ", score :" + joueur1.getScore());
System.out.println("Nombre de cartes du Joueur 2 : " + joueur2.getPaquet().size() + ", score :" + joueur2.getScore());
System.out.println("-----------------------------");
}
if(joueur1.getScore() > joueur2.getScore()){
System.out.println("Le gagnant est le Joueur 1");
}
else {
System.out.println("Le gagnant est le Joueur 2");
}
}
}
| UTF-8 | Java | 3,117 | java | Bataille.java | Java | [] | null | [] | package fr.mat.bataille;
import java.util.*;
public class Bataille {
public static void main(String[] args) {
// TODO Auto-generated method stub
// on créé les deux joueurs
Joueur joueur1 = new Joueur();
Joueur joueur2 = new Joueur();
//on créé toutes les cartes possibles
ArrayList<Carte> bataille = new ArrayList<Carte>();
for(int i = 0; i < Carte.couleurs.length; i++){// tant que i est plus petit que le nombre de couleurs, on l'incremente
for(int j = 0; j < Carte.valeurs.length; j++){// tant que j est plus petit que le nombre de couleurs, on l'incremente
Carte carte = new Carte (i,j);// puis on créé une carte à chaque tour de la boucle for
bataille.add(carte);// et on l'ajoute à la bataille
}
}
// mélange du jeu
Collections.shuffle(bataille); // la consigne indique math.random mais j'utilise https://www.geeksforgeeks.org/collections-shuffle-java-examples/
// initialisation des paquets
for(int i = 0; i < bataille.size() ; i++) { // tant qu'il reste des cartes, on continue la boucle
if(i % 2 == 0) // i % 2 permet d'avoir un résultat impair (1) une fois sur deux (sinon c'est 0...) et donc de distribuer les cartes 1 fois sur 2 à chaque joueur
joueur1.addCarte(bataille.get(i)); // si 1 % 2 == 0 alors on ajoute au paquet du joueur1 la carte qui se trouve à l'index i (https://www.geeksforgeeks.org/arraylist-get-method-java-examples/)
else
joueur2.addCarte(bataille.get(i)); // sinon on ajoute la carte au paquet du joueur2
}
// deroulement d'une partie
while(joueur1.getPaquet().size() != 0 && joueur2.getPaquet().size() != 0){// tant que les deux joueurs ont encore des cartes, la partie continue
// initialisation des paquets
Carte carteJoueur1 = joueur1.pickCarte();
Carte carteJoueur2 = joueur2.pickCarte();
if(carteJoueur1.comparateur(carteJoueur2) > 0) { // si la valeur de la carte du j1 et > à celle du j2
joueur1.gagnePoint(); // alors j1 gagne un pt
joueur1.addCarte(carteJoueur1);
joueur1.addCarte(carteJoueur2); // puis il recupere les cartes
}
else { // sinon
joueur2.gagnePoint(); // j2 gagne un pt
joueur2.addCarte(carteJoueur2);
joueur2.addCarte(carteJoueur1); // puis il recupere les cartes
}
System.out.println("Nombre de cartes du Joueur 1 " + joueur1.getPaquet().size() + ", score :" + joueur1.getScore());
System.out.println("Nombre de cartes du Joueur 2 : " + joueur2.getPaquet().size() + ", score :" + joueur2.getScore());
System.out.println("-----------------------------");
}
if(joueur1.getScore() > joueur2.getScore()){
System.out.println("Le gagnant est le Joueur 1");
}
else {
System.out.println("Le gagnant est le Joueur 2");
}
}
}
| 3,117 | 0.592139 | 0.574742 | 60 | 50.716667 | 48.155334 | 208 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.95 | false | false | 9 |
3bb9e5979e391db0bab09f402f05ec94c47972f8 | 30,185,030,174,849 | ee00cea819879bd97b681b0ce0d0569aea5fc5f7 | /efcs/src/main/java/com/wxzd/efcs/business/application/realtime/dto/HeartbeatStatus.java | aef1bbe3921b0d1d6ed4e436aec4db795875d4c5 | [] | no_license | developTiger/sy-efcs | https://github.com/developTiger/sy-efcs | 3eb2c17b3f3a32c842b5201ac484647cdff142ab | 8952145e05a2ba66fb3838198beff7cf8486dc06 | refs/heads/master | 2020-12-03T09:26:19.250000 | 2017-06-28T02:43:13 | 2017-06-28T02:43:13 | 95,620,688 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wxzd.efcs.business.application.realtime.dto;
/**
* 设备心跳状态类
* @author Leon Regulus on 2017/4/25.
* @version 1.0
* @since 1.0
*/
public class HeartbeatStatus {
private String deviceNo;
private boolean online;
public String getDeviceNo() {
return deviceNo;
}
public void setDeviceNo(String deviceNo) {
this.deviceNo = deviceNo;
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
}
| UTF-8 | Java | 546 | java | HeartbeatStatus.java | Java | [
{
"context": "plication.realtime.dto;\n\n/**\n * 设备心跳状态类\n * @author Leon Regulus on 2017/4/25.\n * @version 1.0\n * @since 1.0\n */\np",
"end": 96,
"score": 0.9998811483383179,
"start": 84,
"tag": "NAME",
"value": "Leon Regulus"
}
] | null | [] | package com.wxzd.efcs.business.application.realtime.dto;
/**
* 设备心跳状态类
* @author <NAME> on 2017/4/25.
* @version 1.0
* @since 1.0
*/
public class HeartbeatStatus {
private String deviceNo;
private boolean online;
public String getDeviceNo() {
return deviceNo;
}
public void setDeviceNo(String deviceNo) {
this.deviceNo = deviceNo;
}
public boolean isOnline() {
return online;
}
public void setOnline(boolean online) {
this.online = online;
}
}
| 540 | 0.633459 | 0.612782 | 28 | 18 | 16.327015 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
881412cc2b8e01d8c38bdc2b814ffc00ef6477b5 | 30,726,196,035,730 | ed5b0397f1b6646c851296f60465864a2129c4e6 | /src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java | fd9c64c2b83debe726d769dc2c603f6add66a5ec | [] | no_license | weispring/chun-easyexcel | https://github.com/weispring/chun-easyexcel | fc130db027c687014385dffd8ec0ebe83c1bc24d | bdc106d2ba6b0258e5cc3b8b3ca12ab77d52060e | refs/heads/master | 2022-12-24T19:02:32.813000 | 2019-05-30T08:57:24 | 2019-05-30T08:57:24 | 188,518,107 | 0 | 0 | null | false | 2022-12-10T03:14:27 | 2019-05-25T03:56:10 | 2019-05-30T08:57:37 | 2022-12-10T03:14:26 | 85 | 0 | 0 | 6 | Java | false | false | package com.alibaba.excel.constant;
public class ExcelXmlConstants
{
public static final String DIMENSION = "dimension";
public static final String DIMENSION_REF = "ref";
public static final String POSITION = "r";
public static final String ROW_TAG = "row";
public static final String CELL_TAG = "c";
public static final String CELL_VALUE_TAG = "v";
public static final String CELL_VALUE_TAG_1 = "t";
}
/* Location: C:\Users\Dell\Desktop\easyexcel-1.1.2-vphonor-SNAPSHOT.jar
* Qualified Name: com.alibaba.excel.constant.ExcelXmlConstants
* JD-Core Version: 0.6.0
*/ | UTF-8 | Java | 601 | java | ExcelXmlConstants.java | Java | [
{
"context": "_TAG_1 = \"t\";\n}\n\n/* Location: C:\\Users\\Dell\\Desktop\\easyexcel-1.1.2-vphonor-SNAPSHOT.jar\n * Q",
"end": 455,
"score": 0.5777491331100464,
"start": 452,
"tag": "USERNAME",
"value": "ell"
}
] | null | [] | package com.alibaba.excel.constant;
public class ExcelXmlConstants
{
public static final String DIMENSION = "dimension";
public static final String DIMENSION_REF = "ref";
public static final String POSITION = "r";
public static final String ROW_TAG = "row";
public static final String CELL_TAG = "c";
public static final String CELL_VALUE_TAG = "v";
public static final String CELL_VALUE_TAG_1 = "t";
}
/* Location: C:\Users\Dell\Desktop\easyexcel-1.1.2-vphonor-SNAPSHOT.jar
* Qualified Name: com.alibaba.excel.constant.ExcelXmlConstants
* JD-Core Version: 0.6.0
*/ | 601 | 0.71381 | 0.702163 | 17 | 34.411766 | 24.67449 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 9 |
332eed2e4bad552e486f7124899f900294254a78 | 28,269,474,784,910 | 1abc6c3f43aaca4de2ec5f707a885d90322d3171 | /KeepCalmAndWatch/src/main/java/com/keepcalmandwatch/controller/VideoWatchController.java | 615bfb06d684262dba1b20d6b9adb20f09126d3f | [] | no_license | SimeonMarkov/KeepCalmAndWatch.bg | https://github.com/SimeonMarkov/KeepCalmAndWatch.bg | 08095312fa25b5897818bfad5b6e6f9279a07cdd | 0df9d210dd7f6d1e92a3f7fb2c12220bd443c41b | refs/heads/master | 2021-01-17T06:54:21.927000 | 2016-06-19T13:09:59 | 2016-06-19T13:09:59 | 54,643,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.keepcalmandwatch.controller;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
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.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.keepcalmandwatch.model.Comment;
import com.keepcalmandwatch.model.User;
import com.keepcalmandwatch.model.Video;
import com.keepcalmandwatch.model.dao.DBPlaylistDAO;
import com.keepcalmandwatch.model.dao.DBUserDAO;
import com.keepcalmandwatch.model.dao.DBVideoDAO;
@Controller
@SessionAttributes(value = "{LoggedUser,AllVideos}")
public class VideoWatchController {
@SuppressWarnings("resource")
@RequestMapping(value = "/watchVideo", method = RequestMethod.GET)
public String watchVideo(Model model, @RequestParam("v") int id, HttpSession session) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBVideoDAO videoJDBCTemplate = (DBVideoDAO) context.getBean("DBVideoDAO");
Video video = null;
try {
video = videoJDBCTemplate.getVideo(id);
model.addAttribute("uploader", video.getUploader().getUsername());
} catch (EmptyResultDataAccessException e) {
model.addAttribute("badUrl", HttpStatus.NOT_FOUND);
return "error";
}
List<Comment> commentsToCurrentVideo = videoJDBCTemplate.getCommentsForSingleVideo(id);
// get all videos from the same category
List<Video> suggestedVideos = videoJDBCTemplate.getVideosByCategory(video.getCategory());
suggestedVideos.remove(video);
Collections.reverse(suggestedVideos);
suggestedVideos.add(video);
model.addAttribute("video", video);
model.addAttribute("comments", commentsToCurrentVideo);
model.addAttribute("SuggestedVideos", suggestedVideos);
return "watchVideo";
}
@SuppressWarnings("resource")
@RequestMapping(value = "/submitComment", method = RequestMethod.POST)
@ResponseBody
public void submitComment(@RequestBody String json) { // @RequestParam("channelName")
// String
// channelName,
// @RequestParam("text")
// String text,
// @RequestParam("videoId")
// int videoId){
System.out.println(json);
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBUserDAO userDao = (DBUserDAO) context.getBean("DBUserDAO");
DBVideoDAO videoDao = (DBVideoDAO) context.getBean("DBVideoDAO");
JsonObject jsonObjectParsed = (JsonObject) new JsonParser().parse(json);
Comment comment = new Comment();
System.out.println("json---> " + jsonObjectParsed.get("text").getAsString());
comment.setText(jsonObjectParsed.get("text").getAsString());
comment.setDatetime(LocalDateTime.now());
comment.setLikes(0);
comment.setDislikes(0);
User user = userDao.getUserBChannelName(jsonObjectParsed.get("channelName").getAsString());
comment.setUser(user);
Video video = videoDao.getVideo(jsonObjectParsed.get("videoId").getAsInt());
comment.setVideo(video);
userDao.addComment(comment);
}
@SuppressWarnings({ "resource", "unused" })
@RequestMapping(value = "/favorite", method = RequestMethod.GET)
public String favorite(Model model, @RequestParam("v") int id, HttpSession session) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBUserDAO userDao = (DBUserDAO) context.getBean("DBUserDAO");
DBPlaylistDAO playlistDAO = (DBPlaylistDAO)context.getBean("DBPlaylistDAO");
User user = null;
if (session.getAttribute("LoggedUser") != null) {
user = (User) session.getAttribute("LoggedUser");
model.addAttribute(user);
user.setFavorites(playlistDAO.getFavorites(user));
playlistDAO.addToFavorites(user.getFavorites(), id);
}else{
return "redirect:login";
}
return "redirect:watchVideo?v=" + id;
}
}
| UTF-8 | Java | 4,470 | java | VideoWatchController.java | Java | [] | null | [] | package com.keepcalmandwatch.controller;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
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.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.keepcalmandwatch.model.Comment;
import com.keepcalmandwatch.model.User;
import com.keepcalmandwatch.model.Video;
import com.keepcalmandwatch.model.dao.DBPlaylistDAO;
import com.keepcalmandwatch.model.dao.DBUserDAO;
import com.keepcalmandwatch.model.dao.DBVideoDAO;
@Controller
@SessionAttributes(value = "{LoggedUser,AllVideos}")
public class VideoWatchController {
@SuppressWarnings("resource")
@RequestMapping(value = "/watchVideo", method = RequestMethod.GET)
public String watchVideo(Model model, @RequestParam("v") int id, HttpSession session) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBVideoDAO videoJDBCTemplate = (DBVideoDAO) context.getBean("DBVideoDAO");
Video video = null;
try {
video = videoJDBCTemplate.getVideo(id);
model.addAttribute("uploader", video.getUploader().getUsername());
} catch (EmptyResultDataAccessException e) {
model.addAttribute("badUrl", HttpStatus.NOT_FOUND);
return "error";
}
List<Comment> commentsToCurrentVideo = videoJDBCTemplate.getCommentsForSingleVideo(id);
// get all videos from the same category
List<Video> suggestedVideos = videoJDBCTemplate.getVideosByCategory(video.getCategory());
suggestedVideos.remove(video);
Collections.reverse(suggestedVideos);
suggestedVideos.add(video);
model.addAttribute("video", video);
model.addAttribute("comments", commentsToCurrentVideo);
model.addAttribute("SuggestedVideos", suggestedVideos);
return "watchVideo";
}
@SuppressWarnings("resource")
@RequestMapping(value = "/submitComment", method = RequestMethod.POST)
@ResponseBody
public void submitComment(@RequestBody String json) { // @RequestParam("channelName")
// String
// channelName,
// @RequestParam("text")
// String text,
// @RequestParam("videoId")
// int videoId){
System.out.println(json);
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBUserDAO userDao = (DBUserDAO) context.getBean("DBUserDAO");
DBVideoDAO videoDao = (DBVideoDAO) context.getBean("DBVideoDAO");
JsonObject jsonObjectParsed = (JsonObject) new JsonParser().parse(json);
Comment comment = new Comment();
System.out.println("json---> " + jsonObjectParsed.get("text").getAsString());
comment.setText(jsonObjectParsed.get("text").getAsString());
comment.setDatetime(LocalDateTime.now());
comment.setLikes(0);
comment.setDislikes(0);
User user = userDao.getUserBChannelName(jsonObjectParsed.get("channelName").getAsString());
comment.setUser(user);
Video video = videoDao.getVideo(jsonObjectParsed.get("videoId").getAsInt());
comment.setVideo(video);
userDao.addComment(comment);
}
@SuppressWarnings({ "resource", "unused" })
@RequestMapping(value = "/favorite", method = RequestMethod.GET)
public String favorite(Model model, @RequestParam("v") int id, HttpSession session) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBUserDAO userDao = (DBUserDAO) context.getBean("DBUserDAO");
DBPlaylistDAO playlistDAO = (DBPlaylistDAO)context.getBean("DBPlaylistDAO");
User user = null;
if (session.getAttribute("LoggedUser") != null) {
user = (User) session.getAttribute("LoggedUser");
model.addAttribute(user);
user.setFavorites(playlistDAO.getFavorites(user));
playlistDAO.addToFavorites(user.getFavorites(), id);
}else{
return "redirect:login";
}
return "redirect:watchVideo?v=" + id;
}
}
| 4,470 | 0.765101 | 0.764653 | 112 | 38.910713 | 26.477266 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.642857 | false | false | 9 |
cc69e378aa6e99d4598ac748a0462f0105ecd167 | 34,093,450,403,213 | db1d5882a0ce5549e907c1faea32fdcefeeb0452 | /GestiNotesV2-Git/src/Menu.java | d24601ef99a19add583e976d46d1235b9e4ff0cd | [] | no_license | Sacacaka/GestiNotesV2-Test | https://github.com/Sacacaka/GestiNotesV2-Test | 81415550aa244687c14cfa4f9a7cbf3cebc4d37a | c2189e73a8441274a12a550836474f20ad33f5e1 | refs/heads/master | 2020-12-24T08:48:26.542000 | 2016-11-09T20:21:37 | 2016-11-09T20:21:37 | 73,317,441 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
//import static gestinotesv2-Git.PrincipaleFrame.retourAuMenu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Victor Rondeau¸=
*/
public class Menu extends JMenuBar implements ActionListener{
JFrame uneFrame;
Etablissement unEtablissement = new Etablissement();
PanelNouvelEtudiant pne = new PanelNouvelEtudiant(unEtablissement);
JProgressBar pBar1;
JLabel blackLabel;
JMenu gestionnaire, etudiant, aide;
JMenuItem menuLister, menuModifier, menuStatistiques, menuNouveau, menuAfficher, menuModifier2, menuApropos, menuQuestion, menuAnnuler, menuQuitter;
int i=0;
public Menu(JFrame frame){
this.uneFrame=frame;
gestionnaire = new JMenu("Gestionnaire"); //Création du menu Gestionnaire
etudiant = new JMenu("Étudiant"); //Création du menu Étudiant
aide = new JMenu("Aide"); //Création du menu Aide
//Ajout des onglets
add(gestionnaire);
add(etudiant);
add(aide);
//Création des options du menu Gestionnaire
menuLister = new JMenuItem("Lister");
menuModifier = new JMenuItem("Modifier");
menuStatistiques = new JMenuItem("Statisitques");
//Création des options du menu Etudiant
menuNouveau = new JMenuItem("Nouveau");
menuAfficher = new JMenuItem("Afficher");
menuModifier2 = new JMenuItem("Modifier");
//Création des options du menu Aide
menuApropos = new JMenuItem("À propos");
menuQuestion = new JMenuItem("?");
menuAnnuler = new JMenuItem("Annuler");
menuQuitter = new JMenuItem("Quitter");
//Ajout des options du menu Gestionnaire
gestionnaire.add(menuLister);
menuLister.addActionListener(this);
gestionnaire.add(menuModifier);
menuModifier.addActionListener(this);
gestionnaire.add(menuStatistiques);
menuStatistiques.addActionListener(this);
//Ajout des options du menu Etudiant
etudiant.add(menuNouveau);
menuNouveau.addActionListener(this);
etudiant.add(menuAfficher);
menuAfficher.addActionListener(this);
etudiant.add(menuModifier2);
menuModifier2.addActionListener(this);
//Ajout des options du menu Aide
aide.add(menuApropos);
menuApropos.addActionListener(this);
aide.add(menuQuestion);
menuQuestion.addActionListener(this);
aide.add(menuAnnuler);
menuAnnuler.addActionListener(this);
aide.add(menuQuitter);
menuQuitter.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event){
if (event.getSource() == menuLister){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelLister(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if (event.getSource() == menuModifier){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelModifier(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if (event.getSource() == menuStatistiques){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelStatistiques(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuNouveau){
uneFrame.getContentPane().removeAll();
uneFrame.add(pne);
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuAfficher){
uneFrame.getContentPane().removeAll();
String uneEntree = JOptionPane.showInputDialog("Code de l'étudiant");
uneFrame.add(new PanelAfficher(unEtablissement,uneEntree));
if(PrincipaleFrame.retourAuMenu = true){
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
PrincipaleFrame.retourAuMenu = false;
}
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuModifier2){
uneFrame.getContentPane().removeAll();
String uneEntree = JOptionPane.showInputDialog("Code de l'étudiant");
uneFrame.add(new PanelMenuModifier2(unEtablissement,uneEntree));
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuApropos){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelMenuApropos());
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuQuestion) {
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelMenuQuestion());
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuAnnuler) {
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuQuitter) {
int answer = JOptionPane.showConfirmDialog(null,"Êtes-vous certain de vouloir fermer l'application?");
switch (answer) {
case JOptionPane.YES_OPTION:
JOptionPane.showMessageDialog(null, "Merci d'avoir utilisé GestiNotes");
System.exit(0);
case JOptionPane.NO_OPTION://L'application demeure sur le panel actuel
break;
case JOptionPane.CANCEL_OPTION://L'option d'annuler permet de réaliser la même action que lorsque l'option aide>annuler est sélectionée
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
default:
break;
}
}
}
}
| UTF-8 | Java | 6,347 | java | Menu.java | Java | [
{
"context": ";\r\nimport java.awt.event.*;\r\n\r\n/**\r\n *\r\n * @author Victor Rondeau¸=\r\n */\r\npublic class Menu extends JMenuBar implem",
"end": 173,
"score": 0.9998936653137207,
"start": 159,
"tag": "NAME",
"value": "Victor Rondeau"
}
] | null | [] |
//import static gestinotesv2-Git.PrincipaleFrame.retourAuMenu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author <NAME>¸=
*/
public class Menu extends JMenuBar implements ActionListener{
JFrame uneFrame;
Etablissement unEtablissement = new Etablissement();
PanelNouvelEtudiant pne = new PanelNouvelEtudiant(unEtablissement);
JProgressBar pBar1;
JLabel blackLabel;
JMenu gestionnaire, etudiant, aide;
JMenuItem menuLister, menuModifier, menuStatistiques, menuNouveau, menuAfficher, menuModifier2, menuApropos, menuQuestion, menuAnnuler, menuQuitter;
int i=0;
public Menu(JFrame frame){
this.uneFrame=frame;
gestionnaire = new JMenu("Gestionnaire"); //Création du menu Gestionnaire
etudiant = new JMenu("Étudiant"); //Création du menu Étudiant
aide = new JMenu("Aide"); //Création du menu Aide
//Ajout des onglets
add(gestionnaire);
add(etudiant);
add(aide);
//Création des options du menu Gestionnaire
menuLister = new JMenuItem("Lister");
menuModifier = new JMenuItem("Modifier");
menuStatistiques = new JMenuItem("Statisitques");
//Création des options du menu Etudiant
menuNouveau = new JMenuItem("Nouveau");
menuAfficher = new JMenuItem("Afficher");
menuModifier2 = new JMenuItem("Modifier");
//Création des options du menu Aide
menuApropos = new JMenuItem("À propos");
menuQuestion = new JMenuItem("?");
menuAnnuler = new JMenuItem("Annuler");
menuQuitter = new JMenuItem("Quitter");
//Ajout des options du menu Gestionnaire
gestionnaire.add(menuLister);
menuLister.addActionListener(this);
gestionnaire.add(menuModifier);
menuModifier.addActionListener(this);
gestionnaire.add(menuStatistiques);
menuStatistiques.addActionListener(this);
//Ajout des options du menu Etudiant
etudiant.add(menuNouveau);
menuNouveau.addActionListener(this);
etudiant.add(menuAfficher);
menuAfficher.addActionListener(this);
etudiant.add(menuModifier2);
menuModifier2.addActionListener(this);
//Ajout des options du menu Aide
aide.add(menuApropos);
menuApropos.addActionListener(this);
aide.add(menuQuestion);
menuQuestion.addActionListener(this);
aide.add(menuAnnuler);
menuAnnuler.addActionListener(this);
aide.add(menuQuitter);
menuQuitter.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event){
if (event.getSource() == menuLister){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelLister(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if (event.getSource() == menuModifier){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelModifier(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if (event.getSource() == menuStatistiques){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelStatistiques(unEtablissement));
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuNouveau){
uneFrame.getContentPane().removeAll();
uneFrame.add(pne);
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuAfficher){
uneFrame.getContentPane().removeAll();
String uneEntree = JOptionPane.showInputDialog("Code de l'étudiant");
uneFrame.add(new PanelAfficher(unEtablissement,uneEntree));
if(PrincipaleFrame.retourAuMenu = true){
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
PrincipaleFrame.retourAuMenu = false;
}
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuModifier2){
uneFrame.getContentPane().removeAll();
String uneEntree = JOptionPane.showInputDialog("Code de l'étudiant");
uneFrame.add(new PanelMenuModifier2(unEtablissement,uneEntree));
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuApropos){
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelMenuApropos());
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuQuestion) {
uneFrame.getContentPane().removeAll();
uneFrame.add(new PanelMenuQuestion());
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuAnnuler) {
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
}else if(event.getSource() == menuQuitter) {
int answer = JOptionPane.showConfirmDialog(null,"Êtes-vous certain de vouloir fermer l'application?");
switch (answer) {
case JOptionPane.YES_OPTION:
JOptionPane.showMessageDialog(null, "Merci d'avoir utilisé GestiNotes");
System.exit(0);
case JOptionPane.NO_OPTION://L'application demeure sur le panel actuel
break;
case JOptionPane.CANCEL_OPTION://L'option d'annuler permet de réaliser la même action que lorsque l'option aide>annuler est sélectionée
uneFrame.getContentPane().removeAll();
uneFrame.add(PrincipaleFrame.simplePanel);
uneFrame.revalidate();
uneFrame.repaint();
default:
break;
}
}
}
}
| 6,339 | 0.600253 | 0.598673 | 145 | 41.620689 | 23.261059 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 9 |
0d48438887383f6ec9398ca6f931ea86d83c1571 | 34,093,450,399,645 | 504d87886d815c23574b8496c80424af07a62dbc | /app/src/main/java/com/example/grosoapp/adapter.java | b0ba0829b3eee8b37ec49b96f0840c31d02d5e43 | [] | no_license | amartya15/APP | https://github.com/amartya15/APP | 22fe5e09c459b6e74cca1f70a245b85c641d9d78 | 8159e34f32f5b76738a0267841708f096de5118e | refs/heads/master | 2022-12-25T02:34:21.069000 | 2020-10-03T02:03:17 | 2020-10-03T02:03:17 | 300,776,431 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.grosoapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class adapter extends BaseAdapter {
ImageView image;
public static final int pick_image = 1;
ArrayList<bookstructure> data;
Context c;
LayoutInflater in;
int bookid;
public adapter(ArrayList<bookstructure> data, Context c) {
this.data = data;
this.c = c;
in = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = in.inflate(R.layout.lists, null);
TextView nam = v.findViewById(R.id.nam);
TextView pos = v.findViewById(R.id.pos);
TextView poi = v.findViewById(R.id.poi);
TextView cat = v.findViewById(R.id.cat);
CheckBox ch = v.findViewById(R.id.check);
ImageView edit = v.findViewById(R.id.update);
ImageView icondelete = v.findViewById(R.id.delete);
image = v.findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) c).startActivityForResult(Intent.createChooser(intent, "select pivture"), pick_image);
}
});
/* @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
String filepath = data.getDataString();
Toast.makeText(getActivity(), "Hello onActivityResult", Toast.LENGTH_SHORT).show();
}
}
*/
edit.setTag(i);
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos =(int)view.getTag();
String uname=data.get(pos).name;
String uauthor=data.get(pos).author;
String ucategory=data.get(pos).category;
int unumber=data.get(pos).number;
int uid=data.get(pos).bookid;
Intent intent=new Intent(c,Updatethis.class);
intent.putExtra("name",uname);
intent.putExtra("author",uauthor);
intent.putExtra("number",unumber);
intent.putExtra("category",ucategory);
intent.putExtra("bookid",uid);
c.startActivity(intent);
}
});
icondelete.setTag(i);
icondelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos=(int)view.getTag();
bookid = data.get(pos).bookid;
AlertDialog.Builder alertdialogbuilder=new AlertDialog.Builder(c);
alertdialogbuilder.setTitle("do you want to delete this item from the list ?");
alertdialogbuilder.setMessage("click yes to delete");
alertdialogbuilder.setCancelable(false);
alertdialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dbclass db= new dbclass(c);
db.deleteBook(bookid);
Toast.makeText(c,"book deleted sucesfully!!!",Toast.LENGTH_LONG).show();;
Intent intent=new Intent(c,MainActivity.class);
c.startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog=alertdialogbuilder.create();
alertDialog.show();
}
});
nam.setText(data.get(i).name);
pos.setText(data.get(i).author);
cat.setText(data.get(i).category);
poi.setText(""+data.get(i).number);
ch.isChecked();
return v;
}
}
| UTF-8 | Java | 5,103 | java | adapter.java | Java | [] | null | [] | package com.example.grosoapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class adapter extends BaseAdapter {
ImageView image;
public static final int pick_image = 1;
ArrayList<bookstructure> data;
Context c;
LayoutInflater in;
int bookid;
public adapter(ArrayList<bookstructure> data, Context c) {
this.data = data;
this.c = c;
in = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = in.inflate(R.layout.lists, null);
TextView nam = v.findViewById(R.id.nam);
TextView pos = v.findViewById(R.id.pos);
TextView poi = v.findViewById(R.id.poi);
TextView cat = v.findViewById(R.id.cat);
CheckBox ch = v.findViewById(R.id.check);
ImageView edit = v.findViewById(R.id.update);
ImageView icondelete = v.findViewById(R.id.delete);
image = v.findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) c).startActivityForResult(Intent.createChooser(intent, "select pivture"), pick_image);
}
});
/* @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
String filepath = data.getDataString();
Toast.makeText(getActivity(), "Hello onActivityResult", Toast.LENGTH_SHORT).show();
}
}
*/
edit.setTag(i);
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos =(int)view.getTag();
String uname=data.get(pos).name;
String uauthor=data.get(pos).author;
String ucategory=data.get(pos).category;
int unumber=data.get(pos).number;
int uid=data.get(pos).bookid;
Intent intent=new Intent(c,Updatethis.class);
intent.putExtra("name",uname);
intent.putExtra("author",uauthor);
intent.putExtra("number",unumber);
intent.putExtra("category",ucategory);
intent.putExtra("bookid",uid);
c.startActivity(intent);
}
});
icondelete.setTag(i);
icondelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos=(int)view.getTag();
bookid = data.get(pos).bookid;
AlertDialog.Builder alertdialogbuilder=new AlertDialog.Builder(c);
alertdialogbuilder.setTitle("do you want to delete this item from the list ?");
alertdialogbuilder.setMessage("click yes to delete");
alertdialogbuilder.setCancelable(false);
alertdialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dbclass db= new dbclass(c);
db.deleteBook(bookid);
Toast.makeText(c,"book deleted sucesfully!!!",Toast.LENGTH_LONG).show();;
Intent intent=new Intent(c,MainActivity.class);
c.startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog=alertdialogbuilder.create();
alertDialog.show();
}
});
nam.setText(data.get(i).name);
pos.setText(data.get(i).author);
cat.setText(data.get(i).category);
poi.setText(""+data.get(i).number);
ch.isChecked();
return v;
}
}
| 5,103 | 0.581815 | 0.581227 | 166 | 29.73494 | 26.20015 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.662651 | false | false | 9 |
cf2a85f8f6efe2e00797e1fa5a0666bdb2ebdd6c | 29,669,634,142,696 | 46254b08829c6cd930fac2fda2b33520dacf3e86 | /src/test/java/org/Mytesting/VerficationTest.java | c706668f520a41a952be27e7aa0562dfdf8033a9 | [] | no_license | kamalakannan9781/KeywordTestingFramework | https://github.com/kamalakannan9781/KeywordTestingFramework | d7659078d8d4f9a87243284cc541a509e74d8577 | 3ffcb7f50dce94fa5a12912cf1eb62d7e013993b | refs/heads/master | 2021-05-05T07:18:42.740000 | 2018-02-14T09:26:41 | 2018-02-14T09:26:41 | 118,863,588 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.Mytesting;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.rmi.UnexpectedException;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.appium.java_client.ios.IOSDriver;
public class VerficationTest {
BusinessLogic buslogic= new BusinessLogic();
private ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
private ThreadLocal<String> sessionId = new ThreadLocal<String>();
private ThreadLocal<IOSDriver> iosDriver = new ThreadLocal<IOSDriver>();
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersFF")
public void SaucefirefoxTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersIE")
public void SauceIETest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowserschrome")
public void SauceChromeTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersedge")
public void SauceedgeTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowserssafari")
public void SaucesafariTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@DataProvider(name = "hardCodedBrowsersFF", parallel = true)
public static Object[][] sauceBrowserDataProviderff(Method testMethod) {
return new Object[][]{
new Object[]{"firefox", "58.0", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowsersIE", parallel = true)
public static Object[][] sauceBrowserDataProviderIE(Method testMethod) {
return new Object[][]{
new Object[]{"internet explorer", "11.0", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowserschrome", parallel = true)
public static Object[][] sauceBrowserDataProviderchrome(Method testMethod) {
return new Object[][]{
new Object[]{"chrome", "54.0", "OS X 10.10"},
};
}
@DataProvider(name = "hardCodedBrowsersedge", parallel = true)
public static Object[][] sauceBrowserDataProvideredge(Method testMethod) {
return new Object[][]{
new Object[]{"MicrosoftEdge", "16", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowserssafari", parallel = true)
public static Object[][] sauceBrowserDataProvidersafari(Method testMethod) {
return new Object[][]{
new Object[]{"safari", "10.0", "OS X 10.11"},
};
}
}
| UTF-8 | Java | 10,371 | java | VerficationTest.java | Java | [] | null | [] | package org.Mytesting;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.rmi.UnexpectedException;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.appium.java_client.ios.IOSDriver;
public class VerficationTest {
BusinessLogic buslogic= new BusinessLogic();
private ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
private ThreadLocal<String> sessionId = new ThreadLocal<String>();
private ThreadLocal<IOSDriver> iosDriver = new ThreadLocal<IOSDriver>();
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersFF")
public void SaucefirefoxTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersIE")
public void SauceIETest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowserschrome")
public void SauceChromeTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowsersedge")
public void SauceedgeTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@org.testng.annotations.Test(dataProvider = "hardCodedBrowserssafari")
public void SaucesafariTest(String browser, String version, String os)
throws InvalidElementStateException, IOException, InterruptedException {
buslogic.createDriver(browser, version, os);
WebDriver driver= buslogic.getWebDriver();
BeanLogic.navigateImplement(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 6s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_7']/div/div[2]/div/div/a/img",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.closebrowserImplement();
buslogic.closebrowser(driver);
BeanLogic.swithparentImplement();
buslogic.swithparent(driver);
BeanLogic.ClicknameImplement();
buslogic.entername("field-keywords", "iphone 7s",driver);
BeanLogic.ClickclassnameImplement();
buslogic.clickclassname("nav-input",driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='result_0']/div/div/div/div[2]/div[1]/div[1]/a/h2",driver);
BeanLogic.swithtabImplement();
buslogic.swithtab(driver);
BeanLogic.ClickxpathImplement();
buslogic.clickxpath(".//*[@id='add-to-cart-button']",driver);
BeanLogic.verifyImplement(driver);
BeanLogic.quitbrowserImplement();
buslogic.quitbrowser(driver);
}
@DataProvider(name = "hardCodedBrowsersFF", parallel = true)
public static Object[][] sauceBrowserDataProviderff(Method testMethod) {
return new Object[][]{
new Object[]{"firefox", "58.0", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowsersIE", parallel = true)
public static Object[][] sauceBrowserDataProviderIE(Method testMethod) {
return new Object[][]{
new Object[]{"internet explorer", "11.0", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowserschrome", parallel = true)
public static Object[][] sauceBrowserDataProviderchrome(Method testMethod) {
return new Object[][]{
new Object[]{"chrome", "54.0", "OS X 10.10"},
};
}
@DataProvider(name = "hardCodedBrowsersedge", parallel = true)
public static Object[][] sauceBrowserDataProvideredge(Method testMethod) {
return new Object[][]{
new Object[]{"MicrosoftEdge", "16", "Windows 10"},
};
}
@DataProvider(name = "hardCodedBrowserssafari", parallel = true)
public static Object[][] sauceBrowserDataProvidersafari(Method testMethod) {
return new Object[][]{
new Object[]{"safari", "10.0", "OS X 10.11"},
};
}
}
| 10,371 | 0.690387 | 0.683348 | 242 | 41.855373 | 22.675755 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.004132 | false | false | 9 |
79852ba2ff02596475919e1f4dadf4948117441b | 4,973,572,175,924 | 31c376c5cf2e3f6de7ad62b48edde44980c57bc2 | /ChessPiece.java | 571147c3e7b47240213acba80edd4fb8499521a1 | [] | no_license | shavbeens/chessgame | https://github.com/shavbeens/chessgame | d5d7b8372bdcc8bdb81d9a9eca73308b42ca31d4 | 094851ac309501911677c08617e6ded4b49f943e | refs/heads/master | 2021-09-06T06:00:24.665000 | 2018-02-03T00:17:29 | 2018-02-03T00:17:29 | 120,045,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/**
* Write a description of class ChessPiece here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ChessPiece
{
private ChessGame game;
private String owner;
private ChessLocation location;
protected char id;
public ChessPiece(String owner, ChessLocation initialLocation, ChessGame game)
{
this.owner = owner;
this.location = initialLocation;
this.game = game;
game.getBoard().placePieceAt(this, location);
}
/**
* Moves the chess piece to the location in the parameter.
*/
protected void moveTo(ChessLocation newLocation)
{
game.getBoard().removePiece(location);
location = newLocation;
game.getBoard().setBoard(this, location);
}
protected boolean checkLineOfSight(ChessLocation start, ChessLocation end)
{
//for horizontal movement in the same row
if(start.getrow() == end.getrow()){
//when the starting column is smaller than the ending column
if(start.getcol()<end.getcol()){
for(int i=(start.getcol()+1); i<=end.getcol();)
{
if(ChessBoard.board[start.getrow()][i] != null){
return false;
}
i++;
}
}
//when the ending column is smaller than the starting column
if(start.getcol()>end.getcol()){
for(int i=(start.getcol()-1); i>=end.getcol();)
{
if(ChessBoard.board[start.getrow()][i] != null){
return false;
}
i--;
}
}
}
//for vertival movement in the same colomn
if(start.getcol() == end.getcol()){
//when the starting row is smaller than the ending row
if(start.getrow()<end.getrow()){
for(int i=(start.getrow()+1); i<=end.getrow();)
{
if(ChessBoard.board[i][start.getcol()] != null)
{
return false;
}
i++;
}
}
//when the ending row is smaller than the starting row
if(start.getrow()>end.getrow()){
for(int i=(start.getrow()-1); i>=end.getrow();)
{
if(ChessBoard.board[i][start.getcol()] != null)
{
return false;
}
i--;
}
}
}
//for angular movement
if((start.getcol() - end.getcol()) == (start.getrow() - end.getrow())){ //positive slope high row to high col ot... high row to low col
if(start.getcol()<end.getcol()){
int j = start.getcol()+1;
for(int i=(start.getrow()-1); i>=end.getrow(); i--){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j++;
}
}
if(start.getcol()>end.getcol()){
int j = start.getcol()-1;
for(int i=(start.getrow()-1); i>=end.getrow(); i--){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j--;
}
}
}
if((start.getcol() - end.getcol()) * -1 == (start.getrow() - end.getcol())){ //negative slope, low row to high col or... low row to low col
if(start.getcol()<end.getcol()){
int j = start.getcol()+1;
for(int i=(start.getrow()+1); i<=end.getrow(); i++){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j++;
}
}
if(start.getcol()>end.getcol()){
int j = start.getcol()-1;
for(int i=(start.getrow()+1); i<=end.getrow(); i++){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j--;
}
}
}
return true;
}
public void setLocation(ChessLocation newlocation)
{
location = newlocation;
}
protected ChessLocation getLocation()
{
return location;
}
protected void setID(char ID)
{
id = ID;
}
public char getID()
{
return id;
}
public String getOwner()
{
return owner;
}
}
| UTF-8 | Java | 5,065 | java | ChessPiece.java | Java | [] | null | [] |
/**
* Write a description of class ChessPiece here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class ChessPiece
{
private ChessGame game;
private String owner;
private ChessLocation location;
protected char id;
public ChessPiece(String owner, ChessLocation initialLocation, ChessGame game)
{
this.owner = owner;
this.location = initialLocation;
this.game = game;
game.getBoard().placePieceAt(this, location);
}
/**
* Moves the chess piece to the location in the parameter.
*/
protected void moveTo(ChessLocation newLocation)
{
game.getBoard().removePiece(location);
location = newLocation;
game.getBoard().setBoard(this, location);
}
protected boolean checkLineOfSight(ChessLocation start, ChessLocation end)
{
//for horizontal movement in the same row
if(start.getrow() == end.getrow()){
//when the starting column is smaller than the ending column
if(start.getcol()<end.getcol()){
for(int i=(start.getcol()+1); i<=end.getcol();)
{
if(ChessBoard.board[start.getrow()][i] != null){
return false;
}
i++;
}
}
//when the ending column is smaller than the starting column
if(start.getcol()>end.getcol()){
for(int i=(start.getcol()-1); i>=end.getcol();)
{
if(ChessBoard.board[start.getrow()][i] != null){
return false;
}
i--;
}
}
}
//for vertival movement in the same colomn
if(start.getcol() == end.getcol()){
//when the starting row is smaller than the ending row
if(start.getrow()<end.getrow()){
for(int i=(start.getrow()+1); i<=end.getrow();)
{
if(ChessBoard.board[i][start.getcol()] != null)
{
return false;
}
i++;
}
}
//when the ending row is smaller than the starting row
if(start.getrow()>end.getrow()){
for(int i=(start.getrow()-1); i>=end.getrow();)
{
if(ChessBoard.board[i][start.getcol()] != null)
{
return false;
}
i--;
}
}
}
//for angular movement
if((start.getcol() - end.getcol()) == (start.getrow() - end.getrow())){ //positive slope high row to high col ot... high row to low col
if(start.getcol()<end.getcol()){
int j = start.getcol()+1;
for(int i=(start.getrow()-1); i>=end.getrow(); i--){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j++;
}
}
if(start.getcol()>end.getcol()){
int j = start.getcol()-1;
for(int i=(start.getrow()-1); i>=end.getrow(); i--){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j--;
}
}
}
if((start.getcol() - end.getcol()) * -1 == (start.getrow() - end.getcol())){ //negative slope, low row to high col or... low row to low col
if(start.getcol()<end.getcol()){
int j = start.getcol()+1;
for(int i=(start.getrow()+1); i<=end.getrow(); i++){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j++;
}
}
if(start.getcol()>end.getcol()){
int j = start.getcol()-1;
for(int i=(start.getrow()+1); i<=end.getrow(); i++){
if(ChessBoard.board[i][j] != null)
{
return false;
}
j--;
}
}
}
return true;
}
public void setLocation(ChessLocation newlocation)
{
location = newlocation;
}
protected ChessLocation getLocation()
{
return location;
}
protected void setID(char ID)
{
id = ID;
}
public char getID()
{
return id;
}
public String getOwner()
{
return owner;
}
}
| 5,065 | 0.407108 | 0.404541 | 164 | 28.871952 | 24.38541 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359756 | false | false | 9 |
9e9853a7707420e0b2e77edb4a5f6c166fd477b1 | 21,088,289,482,965 | 678d79d58d216b348baa06acf8c5b9e28e293fc6 | /ydems/src/main/java/com/yd/ems/code/data/vo/EMS_parameterVO.java | c1a73636c772745028d04d4e22913bd08ceb117d | [] | no_license | ydch10086/ydems2 | https://github.com/ydch10086/ydems2 | 03e39cc6898fa246045258af18496fda25b42885 | fda675d4bff132c1c81c00b7b7120f3c93758c29 | refs/heads/master | 2021-05-29T23:33:31.368000 | 2015-07-21T13:06:59 | 2015-07-21T13:06:59 | 39,450,220 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yd.ems.code.data.vo;
import com.yd.ems.code.data.po.EMS_parameterPO;
public class EMS_parameterVO {
public Object[] getKeys(){
return new Object[]{
equip_id
};
}
/*设备编码*/
private String equip_id;
/*设备名称*/
private String equip_name;
/*设备类型*/
private int equip_type;
/*设备描述*/
private String equip_description;
private String remark;
private int org_id;
/*供应商名称*/
private String sup_code;
/*设备状态*/
private int equip_status;
public String getEquip_id() {
return equip_id;
}
public void setEquip_id(String equip_id) {
this.equip_id = equip_id;
}
public String getEquip_name() {
return equip_name;
}
public void setEquip_name(String equip_name) {
this.equip_name = equip_name;
}
public int getEquip_type() {
return equip_type;
}
public int getOrg_id() {
return org_id;
}
public void setOrg_id(int org_id) {
this.org_id = org_id;
}
public void setEquip_type(int equip_type) {
this.equip_type = equip_type;
}
public String getEquip_description() {
return equip_description;
}
public void setEquip_description(String equip_description) {
this.equip_description = equip_description;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getSup_code() {
return sup_code;
}
public void setSup_code(String sup_code) {
this.sup_code = sup_code;
}
public int getEquip_status() {
return equip_status;
}
public void setEquip_status(int equip_status) {
this.equip_status = equip_status;
}
public EMS_parameterPO toPO(){
EMS_parameterPO po = new EMS_parameterPO();
po.setEquip_id(equip_id);
po.setEquip_name(equip_name);
po.setEquip_type(equip_type);
po.setEquip_description(equip_description);
po.setSup_code(sup_code);
po.setEquip_status(equip_status);
po.setOrg_id(org_id);
return po;
}
}
| UTF-8 | Java | 1,969 | java | EMS_parameterVO.java | Java | [] | null | [] | package com.yd.ems.code.data.vo;
import com.yd.ems.code.data.po.EMS_parameterPO;
public class EMS_parameterVO {
public Object[] getKeys(){
return new Object[]{
equip_id
};
}
/*设备编码*/
private String equip_id;
/*设备名称*/
private String equip_name;
/*设备类型*/
private int equip_type;
/*设备描述*/
private String equip_description;
private String remark;
private int org_id;
/*供应商名称*/
private String sup_code;
/*设备状态*/
private int equip_status;
public String getEquip_id() {
return equip_id;
}
public void setEquip_id(String equip_id) {
this.equip_id = equip_id;
}
public String getEquip_name() {
return equip_name;
}
public void setEquip_name(String equip_name) {
this.equip_name = equip_name;
}
public int getEquip_type() {
return equip_type;
}
public int getOrg_id() {
return org_id;
}
public void setOrg_id(int org_id) {
this.org_id = org_id;
}
public void setEquip_type(int equip_type) {
this.equip_type = equip_type;
}
public String getEquip_description() {
return equip_description;
}
public void setEquip_description(String equip_description) {
this.equip_description = equip_description;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getSup_code() {
return sup_code;
}
public void setSup_code(String sup_code) {
this.sup_code = sup_code;
}
public int getEquip_status() {
return equip_status;
}
public void setEquip_status(int equip_status) {
this.equip_status = equip_status;
}
public EMS_parameterPO toPO(){
EMS_parameterPO po = new EMS_parameterPO();
po.setEquip_id(equip_id);
po.setEquip_name(equip_name);
po.setEquip_type(equip_type);
po.setEquip_description(equip_description);
po.setSup_code(sup_code);
po.setEquip_status(equip_status);
po.setOrg_id(org_id);
return po;
}
}
| 1,969 | 0.677957 | 0.677957 | 113 | 15.982301 | 15.967878 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.238938 | false | false | 9 |
44e50f4d66688feea054c4b817afbc7a789378f7 | 18,897,856,108,409 | 768910140ab9238e773f3dac7b006f8523488cd4 | /src/main/java/arekkuusu/solar/client/util/helper/IModel.java | a6fd38b03976c90e43e098f06d6b15c9751da014 | [
"MIT"
] | permissive | TehNut/Improbable-plot-machine | https://github.com/TehNut/Improbable-plot-machine | e1dad595179b7eee213d53b4c6298ccb039a7765 | 71e33836985cb9bdf7f3c41d1be18581a0b6dd0d | refs/heads/master | 2020-03-30T08:06:10.492000 | 2018-09-08T22:10:09 | 2018-09-08T22:10:09 | 150,989,528 | 0 | 0 | MIT | true | 2018-09-30T17:31:05 | 2018-09-30T17:31:04 | 2018-09-08T22:10:27 | 2018-09-08T22:10:25 | 1,536 | 0 | 0 | 0 | null | false | null | /*
* Arekkuusu / Solar 2018
*
* This project is licensed under the MIT.
* The source code is available on github:
* https://github.com/ArekkuusuJerii/Solar#solar
*/
package arekkuusu.solar.client.util.helper;
/**
* Created by <Arekkuusu> on 21/06/2017.
* It's distributed as part of Solar.
*/
public interface IModel {
void registerModel();
}
| UTF-8 | Java | 355 | java | IModel.java | Java | [
{
"context": "/*\n * Arekkuusu / Solar 2018\n *\n * This project is licensed under",
"end": 15,
"score": 0.9346075654029846,
"start": 6,
"tag": "NAME",
"value": "Arekkuusu"
},
{
"context": "ode is available on github:\n * https://github.com/ArekkuusuJerii/Solar#solar\n */\npackage arekkuusu.solar.client.ut",
"end": 154,
"score": 0.9997337460517883,
"start": 140,
"tag": "USERNAME",
"value": "ArekkuusuJerii"
},
{
"context": "usu.solar.client.util.helper;\n\n/**\n * Created by <Arekkuusu> on 21/06/2017.\n * It's distributed as part of So",
"end": 244,
"score": 0.9997086524963379,
"start": 235,
"tag": "USERNAME",
"value": "Arekkuusu"
}
] | null | [] | /*
* Arekkuusu / Solar 2018
*
* This project is licensed under the MIT.
* The source code is available on github:
* https://github.com/ArekkuusuJerii/Solar#solar
*/
package arekkuusu.solar.client.util.helper;
/**
* Created by <Arekkuusu> on 21/06/2017.
* It's distributed as part of Solar.
*/
public interface IModel {
void registerModel();
}
| 355 | 0.704225 | 0.670423 | 17 | 19.882353 | 18.310659 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.176471 | false | false | 9 |
bece92c7e50f0abf7d718599155a0dfcbf20fe3c | 20,066,087,215,316 | 77fb9eb8a0d8fbe53072d3c31f341961b10f7108 | /src/main/java/com/websystique/springmvc/dao/RoleDao.java | ccc6a18cf9896abd6de81f8c414034cada79c6ae | [] | no_license | UfimtsevArtem/Spring4MVCApacheTiles3Example | https://github.com/UfimtsevArtem/Spring4MVCApacheTiles3Example | f1179952d38951aacb7f721f13ea9dbbf51df634 | f79e76fc22286acd1cc26d89b6fe0d2782ed26dc | refs/heads/master | 2021-01-21T03:34:01.143000 | 2017-09-24T23:33:29 | 2017-09-24T23:33:29 | 101,896,360 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.websystique.springmvc.dao;
import com.websystique.springmvc.domain.Role;
import java.sql.SQLException;
import java.util.Collection;
/**
* Created by ufimtsev on 29.08.2017.
*/
public interface RoleDao {
void addRole(Role role) throws SQLException;
void updateRole(Long role_id, Role role) throws SQLException;
Role getRoleById(Long role_id) throws SQLException;
Collection getAllRoles() throws SQLException;
void deleteRole(Role role) throws SQLException;
}
| UTF-8 | Java | 496 | java | RoleDao.java | Java | [
{
"context": "n;\nimport java.util.Collection;\n\n/**\n * Created by ufimtsev on 29.08.2017.\n */\npublic interface RoleDao {\n ",
"end": 174,
"score": 0.9996927380561829,
"start": 166,
"tag": "USERNAME",
"value": "ufimtsev"
}
] | null | [] | package com.websystique.springmvc.dao;
import com.websystique.springmvc.domain.Role;
import java.sql.SQLException;
import java.util.Collection;
/**
* Created by ufimtsev on 29.08.2017.
*/
public interface RoleDao {
void addRole(Role role) throws SQLException;
void updateRole(Long role_id, Role role) throws SQLException;
Role getRoleById(Long role_id) throws SQLException;
Collection getAllRoles() throws SQLException;
void deleteRole(Role role) throws SQLException;
}
| 496 | 0.764113 | 0.747984 | 18 | 26.555555 | 22.386063 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
f7db54d2f08c936a21281819b287cbd2e8cd9da5 | 20,564,303,422,543 | c9c5fbd03a42d9650dc1453198d0004d66010677 | / fully-automatic-cross-association --username huangpeng1009@gmail.com/mahout-core/src/main/java/org/apache/mahout/cf/taste/hadoop/faca/mapper/ItemPrefsMapper.java | 123a24fa7561e8a7d99aa1aaac44f346bf2febd2 | [] | no_license | alexchao2012/fully-automatic-cross-association | https://github.com/alexchao2012/fully-automatic-cross-association | 8b5e7b4608ebdd58a15de7d670ef25403815722b | b88c9c1acc551ee7a29d5996976622e538bcfde4 | refs/heads/master | 2020-05-31T13:32:16.876000 | 2013-01-23T15:43:16 | 2013-01-23T15:43:16 | 41,666,438 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.apache.mahout.cf.taste.hadoop.faca.mapper;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class ItemPrefsMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
@Override
protected void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException {
if(line.toString().length() != 0){
String[] tokens = line.toString().split("[,\t]");
//Input line MUST have at least 3 fields
long itemID = Long.parseLong(tokens[1]);
String userID = tokens[0];
String pref = tokens[2];
context.write(new LongWritable(itemID), new Text(userID + ":" + pref));
}
}
} | UTF-8 | Java | 736 | java | ItemPrefsMapper.java | Java | [] | null | [] | package org.apache.mahout.cf.taste.hadoop.faca.mapper;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class ItemPrefsMapper extends Mapper<LongWritable, Text, LongWritable, Text> {
@Override
protected void map(LongWritable offset, Text line, Context context) throws IOException, InterruptedException {
if(line.toString().length() != 0){
String[] tokens = line.toString().split("[,\t]");
//Input line MUST have at least 3 fields
long itemID = Long.parseLong(tokens[1]);
String userID = tokens[0];
String pref = tokens[2];
context.write(new LongWritable(itemID), new Text(userID + ":" + pref));
}
}
} | 736 | 0.728261 | 0.721467 | 22 | 32.5 | 29.882725 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.045455 | false | false | 9 |
df9f09d2a47a492a392fe4bc1557d0a1fe4ae402 | 22,892,175,696,359 | e0ba5007466b0b4e511abddd68d938baa146aeac | /src/main/java/com/sky/lli/config/aspect/LogAspectController.java | e4157673d8c7de10867b5d721be7e747b1300325 | [] | no_license | haohao1121/lli-basic | https://github.com/haohao1121/lli-basic | 13004b3a02e2d912ab1c8faba9939a7bd570ba43 | e476106657c3e7fd77d2993048a4f79dff60f57f | refs/heads/master | 2020-05-30T11:36:44.810000 | 2019-10-21T08:04:31 | 2019-10-21T08:04:31 | 189,708,823 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sky.lli.config.aspect;
import com.sky.lli.config.handlerfilter.MDCLogsNames;
import com.sky.lli.util.UUIDUtil;
import com.sky.lli.util.restful.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import static java.util.Objects.isNull;
/**
* 类名:LogAspectController
* 描述:
*/
@Slf4j
@Order(5)
@Aspect
@Component
public class LogAspectController {
//请求Token
private static final String TOKEN = "Token";
//MDC请求链路唯一标识
private static final String MDC_TAG = "MdcTag";
/**
* 环绕通知,决定真实的方法是否执行,而且必须有返回值。同时在所拦截方法的前后执行一段逻辑。
*
* @param pjp 连接点
* @return 执行方法的返回值
* @throws Throwable 抛出异常
*/
@Around("execution(public * com.sky.lli.controller..*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 请求计时
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 初始化MDC
HashMap<String, String> mdcParam = getMdcInitMap(pjp);
MDC.setContextMap(mdcParam);
Object result;
try {
result = pjp.proceed();
} catch (Throwable throwable) {
MDC.put(MDCLogsNames.REQUEST_RESULT_CODE.getMdczh(), "ERROR");
MDC.put(MDCLogsNames.REQUEST_RESULT_MESSAGE.getMdczh(), "抛出错误");
MDC.put(MDCLogsNames.COST_TIME.getMdczh(), String.valueOf(stopWatch.getTotalTimeMillis()));
log.error("请求异常", throwable);
MDC.clear();
throw throwable;
}
// 正常记录返回
stopWatch.stop();
if (result instanceof ResponseResult) {
markSuccessInMDC(stopWatch, (ResponseResult) result);
}
// 清空MDC
MDC.clear();
return result;
}
/**
* 标记请求成功
*
* @param stopWatch 计时器
* @param result 返回信息
*/
private void markSuccessInMDC(StopWatch stopWatch, ResponseResult result) {
MDC.put(MDCLogsNames.REQUEST_RESULT_CODE.getMdczh(), result.getCode());
MDC.put(MDCLogsNames.REQUEST_RESULT_MESSAGE.getMdczh(), result.getMessage());
MDC.put(MDCLogsNames.COST_TIME.getMdczh(), String.valueOf(stopWatch.getTotalTimeMillis()));
}
/**
* 初始化MDC信息
*
* @param pjp 切面
* @return 初始化的信息
*/
private HashMap<String, String> getMdcInitMap(ProceedingJoinPoint pjp) {
HashMap<String, String> mdcParam = new HashMap<>();
// 1.本次请求的UUID
mdcParam.put(MDCLogsNames.REQUEST_UUID.getMdczh(), UUIDUtil.getUUID());
// 2.controller的方法名称
mdcParam.put(MDCLogsNames.CONTROLLER_METHOD_NAME.getMdczh(),
pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
// 3.获取请求参数列表
Object[] args = pjp.getArgs();
if (args != null && args.length > 0) {
mdcParam.put(MDCLogsNames.REQUEST_PARAM.getMdczh(), Arrays.toString(args));
}
// 4.获取Token
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
if (!isNull(request.getHeader(TOKEN))) {
mdcParam.put(MDCLogsNames.REQUEST_TOKEN.getMdczh(), request.getHeader(TOKEN));
}
if (!isNull(request.getHeader(MDC_TAG))) {
mdcParam.put(MDCLogsNames.REQUEST_UUID.getMdczh(), request.getHeader(MDC_TAG));
}
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
// 返回MDC唯一标识,便于问题排查
response.setHeader(MDC_TAG, mdcParam.get(MDCLogsNames.REQUEST_UUID.getMdczh()));
// 5.获取请求路径
mdcParam.put(MDCLogsNames.REQUEST_URL.getMdczh(), request.getRequestURL().toString());
return mdcParam;
}
}
| UTF-8 | Java | 4,677 | java | LogAspectController.java | Java | [
{
"context": "/请求Token\n private static final String TOKEN = \"Token\";\n //MDC请求链路唯一标识\n private static final Stri",
"end": 1004,
"score": 0.6373284459114075,
"start": 999,
"tag": "KEY",
"value": "Token"
}
] | null | [] | package com.sky.lli.config.aspect;
import com.sky.lli.config.handlerfilter.MDCLogsNames;
import com.sky.lli.util.UUIDUtil;
import com.sky.lli.util.restful.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import static java.util.Objects.isNull;
/**
* 类名:LogAspectController
* 描述:
*/
@Slf4j
@Order(5)
@Aspect
@Component
public class LogAspectController {
//请求Token
private static final String TOKEN = "Token";
//MDC请求链路唯一标识
private static final String MDC_TAG = "MdcTag";
/**
* 环绕通知,决定真实的方法是否执行,而且必须有返回值。同时在所拦截方法的前后执行一段逻辑。
*
* @param pjp 连接点
* @return 执行方法的返回值
* @throws Throwable 抛出异常
*/
@Around("execution(public * com.sky.lli.controller..*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 请求计时
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 初始化MDC
HashMap<String, String> mdcParam = getMdcInitMap(pjp);
MDC.setContextMap(mdcParam);
Object result;
try {
result = pjp.proceed();
} catch (Throwable throwable) {
MDC.put(MDCLogsNames.REQUEST_RESULT_CODE.getMdczh(), "ERROR");
MDC.put(MDCLogsNames.REQUEST_RESULT_MESSAGE.getMdczh(), "抛出错误");
MDC.put(MDCLogsNames.COST_TIME.getMdczh(), String.valueOf(stopWatch.getTotalTimeMillis()));
log.error("请求异常", throwable);
MDC.clear();
throw throwable;
}
// 正常记录返回
stopWatch.stop();
if (result instanceof ResponseResult) {
markSuccessInMDC(stopWatch, (ResponseResult) result);
}
// 清空MDC
MDC.clear();
return result;
}
/**
* 标记请求成功
*
* @param stopWatch 计时器
* @param result 返回信息
*/
private void markSuccessInMDC(StopWatch stopWatch, ResponseResult result) {
MDC.put(MDCLogsNames.REQUEST_RESULT_CODE.getMdczh(), result.getCode());
MDC.put(MDCLogsNames.REQUEST_RESULT_MESSAGE.getMdczh(), result.getMessage());
MDC.put(MDCLogsNames.COST_TIME.getMdczh(), String.valueOf(stopWatch.getTotalTimeMillis()));
}
/**
* 初始化MDC信息
*
* @param pjp 切面
* @return 初始化的信息
*/
private HashMap<String, String> getMdcInitMap(ProceedingJoinPoint pjp) {
HashMap<String, String> mdcParam = new HashMap<>();
// 1.本次请求的UUID
mdcParam.put(MDCLogsNames.REQUEST_UUID.getMdczh(), UUIDUtil.getUUID());
// 2.controller的方法名称
mdcParam.put(MDCLogsNames.CONTROLLER_METHOD_NAME.getMdczh(),
pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
// 3.获取请求参数列表
Object[] args = pjp.getArgs();
if (args != null && args.length > 0) {
mdcParam.put(MDCLogsNames.REQUEST_PARAM.getMdczh(), Arrays.toString(args));
}
// 4.获取Token
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
if (!isNull(request.getHeader(TOKEN))) {
mdcParam.put(MDCLogsNames.REQUEST_TOKEN.getMdczh(), request.getHeader(TOKEN));
}
if (!isNull(request.getHeader(MDC_TAG))) {
mdcParam.put(MDCLogsNames.REQUEST_UUID.getMdczh(), request.getHeader(MDC_TAG));
}
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
// 返回MDC唯一标识,便于问题排查
response.setHeader(MDC_TAG, mdcParam.get(MDCLogsNames.REQUEST_UUID.getMdczh()));
// 5.获取请求路径
mdcParam.put(MDCLogsNames.REQUEST_URL.getMdczh(), request.getRequestURL().toString());
return mdcParam;
}
}
| 4,677 | 0.664599 | 0.662072 | 125 | 33.824001 | 29.51774 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.584 | false | false | 9 |
0a6cca89ac003a2ccfb2655154fb1a151e075aa6 | 25,254,407,705,488 | e9affefd4e89b3c7e2064fee8833d7838c0e0abc | /aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/model/DeleteBucketOwnershipControlsRequest.java | 9f1877719480dfd0d6865696fbddece699e58995 | [
"Apache-2.0"
] | permissive | aws/aws-sdk-java | https://github.com/aws/aws-sdk-java | 2c6199b12b47345b5d3c50e425dabba56e279190 | bab987ab604575f41a76864f755f49386e3264b4 | refs/heads/master | 2023-08-29T10:49:07.379000 | 2023-08-28T21:05:55 | 2023-08-28T21:05:55 | 574,877 | 3,695 | 3,092 | Apache-2.0 | false | 2023-09-13T23:35:28 | 2010-03-22T23:34:58 | 2023-09-13T22:30:40 | 2023-09-13T21:56:58 | 4,866,710 | 3,998 | 2,861 | 114 | null | false | false | /*
* Copyright 2011-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.services.s3.model;
import com.amazonaws.AmazonWebServiceRequest;
import java.io.Serializable;
/**
* <p>The Amazon S3 bucket whose <code>OwnershipControls</code> you want to delete. </p>
*/
public class DeleteBucketOwnershipControlsRequest extends AmazonWebServiceRequest implements Serializable, ExpectedBucketOwnerRequest {
private String bucketName;
private String expectedBucketOwner;
public DeleteBucketOwnershipControlsRequest() {
}
/**
* Returns the name of the bucket from which the ownership control is deleted.
*/
public String getBucketName() {
return bucketName;
}
/**
* Sets the name of the bucket from which the ownership control is deleted.
*/
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* Sets the name of the bucket from which the ownership control is deleted
* and returns this object for method chaining.
*/
public DeleteBucketOwnershipControlsRequest withBucketName(String bucketName) {
setBucketName(bucketName);
return this;
}
public String getExpectedBucketOwner() {
return expectedBucketOwner;
}
public DeleteBucketOwnershipControlsRequest withExpectedBucketOwner(String expectedBucketOwner) {
this.expectedBucketOwner = expectedBucketOwner;
return this;
}
public void setExpectedBucketOwner(String expectedBucketOwner) {
withExpectedBucketOwner(expectedBucketOwner);
}
}
| UTF-8 | Java | 2,088 | java | DeleteBucketOwnershipControlsRequest.java | Java | [] | null | [] | /*
* Copyright 2011-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.services.s3.model;
import com.amazonaws.AmazonWebServiceRequest;
import java.io.Serializable;
/**
* <p>The Amazon S3 bucket whose <code>OwnershipControls</code> you want to delete. </p>
*/
public class DeleteBucketOwnershipControlsRequest extends AmazonWebServiceRequest implements Serializable, ExpectedBucketOwnerRequest {
private String bucketName;
private String expectedBucketOwner;
public DeleteBucketOwnershipControlsRequest() {
}
/**
* Returns the name of the bucket from which the ownership control is deleted.
*/
public String getBucketName() {
return bucketName;
}
/**
* Sets the name of the bucket from which the ownership control is deleted.
*/
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* Sets the name of the bucket from which the ownership control is deleted
* and returns this object for method chaining.
*/
public DeleteBucketOwnershipControlsRequest withBucketName(String bucketName) {
setBucketName(bucketName);
return this;
}
public String getExpectedBucketOwner() {
return expectedBucketOwner;
}
public DeleteBucketOwnershipControlsRequest withExpectedBucketOwner(String expectedBucketOwner) {
this.expectedBucketOwner = expectedBucketOwner;
return this;
}
public void setExpectedBucketOwner(String expectedBucketOwner) {
withExpectedBucketOwner(expectedBucketOwner);
}
}
| 2,088 | 0.720785 | 0.71408 | 66 | 30.636364 | 31.592882 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.287879 | false | false | 9 |
84508e9f977b58c272fd2b7914ff8100dcd98dfe | 28,243,704,945,728 | cf9ffc9e7d3f99ca0490e09549a245872a74b532 | /strategy_demo/src/com/yannis/strategy/Demo2.java | 3d0ddede06d11e15e0adac97b68451b135962643 | [] | no_license | pigga/springdemo | https://github.com/pigga/springdemo | b53d8589259b63871c830ef2e9c45d84350776d9 | 80c4708d3b92cd9bef0883ddd18f922ac011b30d | refs/heads/master | 2020-04-27T01:04:47.733000 | 2019-08-14T10:31:02 | 2019-08-14T10:31:02 | 173,954,833 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yannis.strategy;
import com.yannis.strategy.factory.StrategyFactory;
import com.yannis.strategy.factory.StrategyTypeEnum;
public class Demo2 {
public static void main(String[] args) {
Strategy strategy = StrategyFactory.getStrategyById(StrategyTypeEnum.StrategyB.getId());
Context context = new Context(strategy);
context.contextFunc();
}
}
| UTF-8 | Java | 387 | java | Demo2.java | Java | [] | null | [] | package com.yannis.strategy;
import com.yannis.strategy.factory.StrategyFactory;
import com.yannis.strategy.factory.StrategyTypeEnum;
public class Demo2 {
public static void main(String[] args) {
Strategy strategy = StrategyFactory.getStrategyById(StrategyTypeEnum.StrategyB.getId());
Context context = new Context(strategy);
context.contextFunc();
}
}
| 387 | 0.741602 | 0.739018 | 12 | 31.25 | 27.616796 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
fa11a491011efb2631945e90d9f73f47eb031da2 | 28,243,704,947,922 | 427aa4da3ba9a81d74225f654142b1ad6e2375d7 | /Misc.java | e25003cc1dfc7bd3040545caf0952cccb7f67f84 | [
"Unlicense"
] | permissive | hermes-jr/school-project-acidpad | https://github.com/hermes-jr/school-project-acidpad | 8961f5e2b2f0ae7f71d52cd9d0a2814185a4c80e | 2650df4112e3bb8e4a443092232b593e4d852f59 | refs/heads/master | 2021-01-10T10:42:11.471000 | 2016-02-20T10:52:01 | 2016-02-20T10:52:01 | 52,148,598 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
import java.io.*;
class HelpWindow extends JPanel implements HyperlinkListener {
JEditorPane htmlPane = new JEditorPane();
Toolkit tk = Toolkit.getDefaultToolkit();
LanguagePack dict; LanguageChanger langChanger;
JLabel status;
public HelpWindow(LanguagePack dict, LanguageChanger langChanger) {
this.dict = dict; this.langChanger = langChanger;
status = new JLabel();
//--------------------- html pane... ---------------------
htmlPane.setMargin(new Insets(0, 0, 0, 0));
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
try { htmlPane.setPage(getFileUrl("./helps/" + dict.get("name") + "/index.html"));
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
JScrollPane scroll = new JScrollPane(htmlPane,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.setLayout(new BorderLayout());
this.add("South", status); this.add("Center", scroll);
status.setText(dict.get("dialogs_help_status_default"));
}
public void setLanguage(LanguagePack dict) {
this.dict = dict;
try { htmlPane.setPage(getFileUrl("./helps/" + dict.get("name") + "/index.html"));
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
}
//--------------------- private methods... ---------------------
private URL getFileUrl(String s) throws MalformedURLException {
File f = new File(s);
return f.toURL();
}
//--------------------- event listeners... ---------------------
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(evt.getURL());
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
}
}
}
class ImagePreview extends JPanel {
private String imageToShow;
private Toolkit kit = Toolkit.getDefaultToolkit();
private MediaTracker tracker; Image image;
public ImagePreview(String imageToShow) {
this.imageToShow = imageToShow; this.repaint(); this.setLayout(null); this.setSize(230, 190);
this.setPreferredSize(new Dimension(230, 190)); this.setMinimumSize(new Dimension(230, 190));
}
public void setImage(String imageToShow) { this.imageToShow = imageToShow; this.repaint(); }
public void paint(Graphics g) {
g.setColor(this.getBackground());
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
image = kit.getImage(imageToShow);
tracker = new MediaTracker(this); tracker.addImage(image, 0);
try { tracker.waitForID(0);
} catch (InterruptedException e) { }
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(image, 0, 0, this); }
}
}
class JColorSelector extends JPanel implements ActionListener {
protected Color color = new Color(0, 0, 0);
protected GridBagLayout gridbag;
protected GridBagConstraints constructor;
protected JPanel demo = new JPanel();
protected JButton picker;
protected LanguagePack dict;
public JColorSelector(JLabel label, LanguagePack dict) { this.dict = dict; createPane(label); }
public JColorSelector(JLabel label, Color color, LanguagePack dict) {
this.dict = dict; this.color = color; createPane(label);
}
//--------------------- private methods... ---------------------
private void createPane(JLabel label) {
JPanel freePane;
gridbag = new GridBagLayout(); constructor = new GridBagConstraints();
this.setLayout(gridbag);
//new component...
buildGrid(constructor, 0, 0, 1, 1, 100, 0, new Insets(0, 0, 0, 0));
constructor.fill = GridBagConstraints.HORIZONTAL;
constructor.anchor = GridBagConstraints.CENTER;
freePane = new JPanel();
gridbag.setConstraints(freePane, constructor);
this.add(freePane);
//new component...
buildGrid(constructor, 1, 0, 1, 1, 0, 100, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(label, constructor);
this.add(label);
//new component...
buildGrid(constructor, 2, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
demo.setBackground(color); demo.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
demo.setSize(40, 20); demo.setMinimumSize(new Dimension(40, 20)); demo.setPreferredSize(new Dimension(40, 20));
gridbag.setConstraints(demo, constructor);
this.add(demo);
//new component...
buildGrid(constructor, 3, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
picker = new JButton(new ImageIcon("images/icons/picker.gif")); picker.setSize(22, 22);
picker.setMinimumSize(new Dimension(22, 22)); picker.setPreferredSize(new Dimension(22, 22));
picker.addActionListener(JColorSelector.this);
gridbag.setConstraints(picker, constructor);
this.add(picker);
}
public void setColor(Color color) { this.color = color; demo.setBackground(color); demo.repaint(); }
public Color getColor() { return color; }
//--------------------- event listeners... ---------------------
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if(source == picker) {
JColorChooser cch = new JColorChooser(color);
Color c = cch.showDialog(JColorSelector.this.getParent().getParent(), dict.get("dialogs_choosecolor_title"), color);
if(c != null) { color = c; }
demo.setBackground(color);
}
repaint();
}
void buildGrid(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy, Insets ins) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
gbc.insets = ins;
}
}
class DirFilter implements FilenameFilter {
String extension;
public DirFilter(String extension) { this.extension = extension; }
public boolean accept(File dir, String name) { return name.indexOf(extension) != -1; }
}
class AcidFileFilter extends javax.swing.filechooser.FileFilter {
String extension;
String description;
public AcidFileFilter(String extension, String description) {
this.extension = extension;
this.description = description;
}
public boolean accept(File file) {
if(file.isDirectory()) { return true;
} else { return file.getName().indexOf(extension) != -1; }
}
public String getDescription() { return description; }
}
class LanguagePack {
protected Properties properties = new Properties();
final static String PATH = "./setup/languages/";
protected String langname, encoding;
public LanguagePack(String langfile) {
try { properties.load(new FileInputStream(PATH + langfile)); } catch (IOException e) { }
encoding = properties.getProperty("encoding");
try {
langname = new String(properties.getProperty("description").toString().getBytes(), encoding);
} catch (UnsupportedEncodingException e) { langname = properties.getProperty("description").toString(); }
}
public String get(String param) {
try { return new String(properties.getProperty(param).toString().getBytes(), encoding);
} catch (UnsupportedEncodingException e) { return properties.getProperty(param).toString(); }
}
public String getLanguageName() { return langname; }
public String getEncoding() { return encoding; }
public boolean containsKey(String key) { return properties.containsKey(key); }
}
class LanguageChanger implements Runnable {
protected LanguagePack language = null;
protected Thread runner = null;
protected Hashtable abstractButtonsTexts = new Hashtable(0);
protected Hashtable abstractButtonsTooltips = new Hashtable(0);
protected Hashtable textComponentsTexts = new Hashtable(0);
protected Hashtable textComponentsTooltips = new Hashtable(0);
protected Hashtable labelsTexts = new Hashtable(0);
protected Hashtable labelsTooltips = new Hashtable(0);
protected Hashtable tabpanesTexts = new Hashtable(0);
protected Hashtable tabpanesTooltips = new Hashtable(0);
protected Hashtable framesTitles = new Hashtable(0);
protected Hashtable dialogsTitles = new Hashtable(0);
protected Hashtable nonSimpleElements = new Hashtable(0);
public void add(AbstractButton abToAdd, String langKey) { abstractButtonsTexts.put(abToAdd, langKey); }
public void addTooltip(AbstractButton abToAdd, String langKey) { abstractButtonsTooltips.put(abToAdd, langKey); }
public void add(AbstractButton abToAdd, String langKey, boolean cont) {
String whatToPut = "false";
if(cont) { whatToPut = "true"; }
abstractButtonsTexts.put(abToAdd, langKey); nonSimpleElements.put(abToAdd, whatToPut);
}
public void addTooltip(AbstractButton abToAdd, String langKey, boolean cont) {
String whatToPut = "false";
if(cont) { whatToPut = "true"; }
abstractButtonsTooltips.put(abToAdd, langKey); nonSimpleElements.put(abToAdd, whatToPut);
}
public void add(JTextComponent tcToAdd, String langKey) { textComponentsTexts.put(tcToAdd, langKey); }
public void addTooltip(JTextComponent tcToAdd, String langKey) { textComponentsTooltips.put(tcToAdd, langKey); }
public void add(JLabel lbToAdd, String langKey) { labelsTexts.put(lbToAdd, langKey); }
public void addTooltip(JLabel lbToAdd, String langKey) { labelsTooltips.put(lbToAdd, langKey); }
public void add(JTabbedPane tpToAdd, String[] langKey) { tabpanesTexts.put(tpToAdd, langKey); }
public void addTooltip(JTabbedPane tpToAdd, String[] langKey) { tabpanesTooltips.put(tpToAdd, langKey); }
public void add(JFrame jfToAdd, String langKey) { framesTitles.put(jfToAdd, langKey); }
public void add(JDialog jdToAdd, String langKey) { dialogsTitles.put(jdToAdd, langKey); }
public void changeLanguage(LanguagePack language) {
this.language = language;
if(runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void run() {
Enumeration keys;
if(runner != null) {
//texts...
keys = abstractButtonsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
if(nonSimpleElements.containsKey(id) && (nonSimpleElements.get(id).toString().equals("true"))) {
((AbstractButton) id).setText(language.get(abstractButtonsTexts.get(id).toString()) + "...");
((AbstractButton) id).repaint();
} else {
((AbstractButton) id).setText(language.get(abstractButtonsTexts.get(id).toString()));
((AbstractButton) id).repaint();
}
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = textComponentsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JTextComponent) id).setText(language.get(textComponentsTexts.get(id).toString()));
((JTextComponent) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = labelsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JLabel) id).setText(language.get(labelsTexts.get(id).toString()));
((JLabel) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = tabpanesTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
for(int i = 0; i < ((String[])tabpanesTexts.get(id)).length; i++) {
((JTabbedPane) id).setTitleAt(i, language.get(((String[])tabpanesTexts.get(id))[i].toString()));
}
((JTabbedPane) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = dialogsTitles.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JDialog) id).setTitle(language.get(dialogsTitles.get(id).toString()));
((JDialog) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = framesTitles.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JFrame) id).setTitle(language.get(framesTitles.get(id).toString()));
((JFrame) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
//tooltips...
keys = abstractButtonsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
if(nonSimpleElements.containsKey(id) && (nonSimpleElements.get(id).toString().equals("true"))) {
((AbstractButton) id).setToolTipText(language.get(abstractButtonsTooltips.get(id).toString()) + "...");
((AbstractButton) id).repaint();
} else {
((AbstractButton) id).setToolTipText(language.get(abstractButtonsTooltips.get(id).toString()));
((AbstractButton) id).repaint();
}
}
keys = textComponentsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JTextComponent) id).setToolTipText(language.get(textComponentsTooltips.get(id).toString()));
((JTextComponent) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = labelsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JLabel) id).setToolTipText(language.get(labelsTooltips.get(id).toString()));
((JLabel) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = tabpanesTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
for(int i = 0; i < ((String[])tabpanesTooltips.get(id)).length; i++) {
((JTabbedPane) id).setToolTipTextAt(i, language.get(((String[])tabpanesTooltips.get(id))[i].toString()));
}
((JTabbedPane) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
}
runner = null;
}
}
class JDownloader implements ActionListener, WindowListener, Runnable {
protected JTextField url, sicl, sict, sidt, sipb, siex, silm, sisr;
protected JTextField[] fields = {sicl, sict, sidt, sipb, siex, silm, sisr};
protected String[] headers = {"Content-Length", "Content-Type", "Date", "Public", "Expires", "Last-Modified", "Server"};
protected JLabel status;
protected JPanel tf, downloadDialogPane;
protected JButton get, cancel;
protected JProgressBar pb;
protected URL page;
protected String source = "";
protected Thread runner = null;
protected JDialog downloadDialog;
int ret; LanguagePack dict;
public static final int SOMETHING_DOWNLOADED = 0;
public static final int NOTHING_DOWNLOADED = 1;
public JDownloader(LanguagePack dict) {
this.dict = dict;
//setting up components...
url = new JTextField(); url.addActionListener(JDownloader.this);
for(int i = 0; i < fields.length; i++) {
fields[i] = new JTextField();
}
status = new JLabel(dict.get("dialogs_download_status_default"));
pb = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
get = new JButton(dict.get("dialogs_download_buttons_get")); get.addActionListener(JDownloader.this);
cancel = new JButton(dict.get("dialogs_download_buttons_close")); cancel.addActionListener(JDownloader.this);
downloadDialogPane = new JPanel();
JPanel pane = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constr = new GridBagConstraints();
pane.setLayout(gridbag);
downloadDialogPane.setLayout(new BorderLayout());
JPanel infos = new JPanel();
infos.setBorder(new TitledBorder(dict.get("dialogs_download_about")));
infos.setLayout(new BoxLayout(infos, BoxLayout.Y_AXIS));
for(int i = 0; i < fields.length; i++) {
infos.add(titledField(headers[i] + ":", fields[i]));
}
//new component...
buildGrid(constr, 0, 0, 3, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
tf = titledField(dict.get("dialogs_download_labels_url"), url);
gridbag.setConstraints(tf, constr);
pane.add(tf);
//new component...
buildGrid(constr, 0, 1, 1, 1, 100, 0, new Insets(0, 0, 0, 0));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
JPanel freePane = new JPanel();
gridbag.setConstraints(freePane, constr);
pane.add(freePane);
//new component...
buildGrid(constr, 1, 1, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(get, constr);
pane.add(get);
//new component...
buildGrid(constr, 2, 1, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(cancel, constr);
pane.add(cancel);
//new component...
buildGrid(constr, 0, 2, 3, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(pb, constr);
pane.add(pb);
//new component...
buildGrid(constr, 0, 3, 3, 1, 100, 100, new Insets(0, 0, 0, 0));
constr.fill = GridBagConstraints.BOTH;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(infos, constr);
pane.add(infos);
downloadDialogPane.add("Center", pane);
downloadDialogPane.add("South", status);
pb.setStringPainted(true);
url.setText("http://"); url.setCaretPosition(url.getText().length());
}
public void run() {
URLConnection con = null;
InputStreamReader in;
BufferedReader data;
String line = null;
StringBuffer buf = new StringBuffer();
try {
pb.setValue(0);
//connecting to source...
con = page.openConnection();
con.connect();
//getting source info...
status.setText(dict.get("dialogs_download_status_conn_opened"));
try { runner.sleep(0); } catch(InterruptedException e) { }
for(int i = 0; i < fields.length; i++) {
fields[i].setText(con.getHeaderField(headers[i]));
}
try { runner.sleep(0); } catch(InterruptedException e) { }
if (fields[0].getText().length() != 0) {
pb.setMaximum(Integer.parseInt(con.getHeaderField("Content-Length")));
}
//getting source body...
in = new InputStreamReader(con.getInputStream()); data = new BufferedReader(in);
status.setText(dict.get("dialogs_download_status_loading"));
try { runner.sleep(0); } catch(InterruptedException e) { }
while(((line = data.readLine()) != null) && (runner != null)) {
buf.append(line + "\n");
pb.setValue(buf.toString().length()); downloadDialogPane.repaint();
try { runner.sleep(0); } catch(InterruptedException e) { }
}
if(runner != null) { pb.setValue(pb.getMaximum()); }
//safe reading...
if(buf.toString().length() <= 1) { source = buf.toString();
} else { source = buf.toString().substring(0, buf.toString().length() - 1); }
status.setText(dict.get("dialogs_download_status_done"));
try { runner.sleep(0); } catch(InterruptedException e) { }
con = null; runner = null;
} catch (IOException e) { status.setText(dict.get("dialogs_download_status_conn_failed")); runner = null; }
}
public String getSource() {
return source;
}
public int showDownloadDialog(JFrame parent) {
downloadDialog = new JDialog(parent); downloadDialog.setSize(450, 350);
downloadDialog.setResizable(true); downloadDialog.setModal(true);
downloadDialog.setTitle(dict.get("dialogs_download_title"));
downloadDialog.setLocationRelativeTo(parent); downloadDialog.addWindowListener(JDownloader.this);
downloadDialog.setContentPane(downloadDialogPane); downloadDialog.setVisible(true);
return ret;
}
//--------------------- event listeners... ---------------------
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if((source == get) || (source == url)) {
runner = null;
for(int i = 0; i < fields.length; i++) { fields[i].setText(""); }
try {
page = new URL(url.getText());
if(runner == null) {
runner = new Thread(JDownloader.this);
runner.start();
runner.setPriority(Thread.MAX_PRIORITY);
}
} catch (MalformedURLException e) { status.setText(dict.get("dialogs_download_status_badurl") + " " + url.getText()); }
}
else if(source == cancel) {
if (runner == null) {
downloadDialog.dispose();
if (pb.getValue() != pb.getMaximum()) { ret = NOTHING_DOWNLOADED; } else { ret = SOMETHING_DOWNLOADED; }
}
else { runner = null; }
}
downloadDialog.repaint();
}
public void windowOpened(WindowEvent evt) { }
public void windowClosed(WindowEvent evt) { }
public void windowClosing(WindowEvent evt) {
Object source = evt.getSource();
if(source == downloadDialog) {
downloadDialog.dispose();
if (pb.getValue() != pb.getMaximum()) { ret = NOTHING_DOWNLOADED; } else { ret = SOMETHING_DOWNLOADED; }
}
downloadDialog.repaint();
}
public void windowIconified(WindowEvent evt) { }
public void windowDeiconified(WindowEvent evt) { }
public void windowActivated(WindowEvent evt) { }
public void windowDeactivated(WindowEvent evt) { }
//--------------------- private methods... ---------------------
private JPanel titledField(String title, JTextField field) {
JPanel output = new JPanel();
JLabel lab = new JLabel(title);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constr = new GridBagConstraints();
output.setLayout(gridbag);
buildGrid(constr, 0, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.NONE;
constr.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(lab, constr);
output.add(lab);
buildGrid(constr, 1, 0, 1, 1, 100, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(field, constr);
output.add(field);
return output;
}
void buildGrid(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy, Insets ins) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
gbc.insets = ins;
}
}
class About extends JPanel {
private HeadLines hl;
private Toolkit kit = Toolkit.getDefaultToolkit();
private MediaTracker tracker; Image back;
public About() {
this.setBackground(Color.black); this.setSize(350, 250);
this.setPreferredSize(new Dimension(350, 250)); this.setMinimumSize(new Dimension(350, 250));
this.setLayout(null);
hl = new HeadLines(); this.add(hl); hl.setBounds(0, 120, 170, 130);
back = kit.getImage("./images/aback.jpg");
tracker = new MediaTracker(this); tracker.addImage(back, 0);
try { tracker.waitForID(0);
} catch (InterruptedException e) { }
}
public void setHeadlines(String[] headlines) { hl.setLines(headlines); hl.start(); }
public void stop() { hl.stop(); }
public void paint(Graphics g) {
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(back, 0, 0, this); }
}
}
class HeadLines extends JPanel implements Runnable {
private Thread runner;
private Image back;
private MediaTracker tracker;
String[] headlines = {"Sorry, no information..."};
int y = getSize().height + 15;
public HeadLines() {
Toolkit kit = Toolkit.getDefaultToolkit();
back = kit.getImage("images/abackt.jpg");
tracker = new MediaTracker(this);
tracker.addImage(back, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) { }
}
public void start() {
if(runner == null) { runner = new Thread(this); runner.start(); }
}
public void run() {
while(true) {
y = y - 1;
if(y < -(headlines.length * 15)) { y = getSize().height + 15; }
repaint();
try { Thread.sleep(100);
} catch(InterruptedException e){}
}
}
public void stop() { runner = null; y = getSize().height + 15; }
public void setLines(String[] headlines) { this.headlines = headlines; }
public void paint(Graphics g) {
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(back, 0, 0, this); }
g.setColor(Color.white);
for(int i = 0; i < headlines.length; i++) { g.drawString(headlines[i], 5, y + (15 * i)); }
}
}
| UTF-8 | Java | 23,838 | java | Misc.java | Java | [] | null | [] | import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
import java.io.*;
class HelpWindow extends JPanel implements HyperlinkListener {
JEditorPane htmlPane = new JEditorPane();
Toolkit tk = Toolkit.getDefaultToolkit();
LanguagePack dict; LanguageChanger langChanger;
JLabel status;
public HelpWindow(LanguagePack dict, LanguageChanger langChanger) {
this.dict = dict; this.langChanger = langChanger;
status = new JLabel();
//--------------------- html pane... ---------------------
htmlPane.setMargin(new Insets(0, 0, 0, 0));
htmlPane.setEditable(false);
htmlPane.addHyperlinkListener(this);
try { htmlPane.setPage(getFileUrl("./helps/" + dict.get("name") + "/index.html"));
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
JScrollPane scroll = new JScrollPane(htmlPane,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.setLayout(new BorderLayout());
this.add("South", status); this.add("Center", scroll);
status.setText(dict.get("dialogs_help_status_default"));
}
public void setLanguage(LanguagePack dict) {
this.dict = dict;
try { htmlPane.setPage(getFileUrl("./helps/" + dict.get("name") + "/index.html"));
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
}
//--------------------- private methods... ---------------------
private URL getFileUrl(String s) throws MalformedURLException {
File f = new File(s);
return f.toURL();
}
//--------------------- event listeners... ---------------------
public void hyperlinkUpdate(HyperlinkEvent evt) {
if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
htmlPane.setPage(evt.getURL());
} catch (IOException e) { status.setText(dict.get("dialogs_help_status_error")); }
}
}
}
class ImagePreview extends JPanel {
private String imageToShow;
private Toolkit kit = Toolkit.getDefaultToolkit();
private MediaTracker tracker; Image image;
public ImagePreview(String imageToShow) {
this.imageToShow = imageToShow; this.repaint(); this.setLayout(null); this.setSize(230, 190);
this.setPreferredSize(new Dimension(230, 190)); this.setMinimumSize(new Dimension(230, 190));
}
public void setImage(String imageToShow) { this.imageToShow = imageToShow; this.repaint(); }
public void paint(Graphics g) {
g.setColor(this.getBackground());
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
image = kit.getImage(imageToShow);
tracker = new MediaTracker(this); tracker.addImage(image, 0);
try { tracker.waitForID(0);
} catch (InterruptedException e) { }
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(image, 0, 0, this); }
}
}
class JColorSelector extends JPanel implements ActionListener {
protected Color color = new Color(0, 0, 0);
protected GridBagLayout gridbag;
protected GridBagConstraints constructor;
protected JPanel demo = new JPanel();
protected JButton picker;
protected LanguagePack dict;
public JColorSelector(JLabel label, LanguagePack dict) { this.dict = dict; createPane(label); }
public JColorSelector(JLabel label, Color color, LanguagePack dict) {
this.dict = dict; this.color = color; createPane(label);
}
//--------------------- private methods... ---------------------
private void createPane(JLabel label) {
JPanel freePane;
gridbag = new GridBagLayout(); constructor = new GridBagConstraints();
this.setLayout(gridbag);
//new component...
buildGrid(constructor, 0, 0, 1, 1, 100, 0, new Insets(0, 0, 0, 0));
constructor.fill = GridBagConstraints.HORIZONTAL;
constructor.anchor = GridBagConstraints.CENTER;
freePane = new JPanel();
gridbag.setConstraints(freePane, constructor);
this.add(freePane);
//new component...
buildGrid(constructor, 1, 0, 1, 1, 0, 100, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(label, constructor);
this.add(label);
//new component...
buildGrid(constructor, 2, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
demo.setBackground(color); demo.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
demo.setSize(40, 20); demo.setMinimumSize(new Dimension(40, 20)); demo.setPreferredSize(new Dimension(40, 20));
gridbag.setConstraints(demo, constructor);
this.add(demo);
//new component...
buildGrid(constructor, 3, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constructor.fill = GridBagConstraints.NONE;
constructor.anchor = GridBagConstraints.WEST;
picker = new JButton(new ImageIcon("images/icons/picker.gif")); picker.setSize(22, 22);
picker.setMinimumSize(new Dimension(22, 22)); picker.setPreferredSize(new Dimension(22, 22));
picker.addActionListener(JColorSelector.this);
gridbag.setConstraints(picker, constructor);
this.add(picker);
}
public void setColor(Color color) { this.color = color; demo.setBackground(color); demo.repaint(); }
public Color getColor() { return color; }
//--------------------- event listeners... ---------------------
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if(source == picker) {
JColorChooser cch = new JColorChooser(color);
Color c = cch.showDialog(JColorSelector.this.getParent().getParent(), dict.get("dialogs_choosecolor_title"), color);
if(c != null) { color = c; }
demo.setBackground(color);
}
repaint();
}
void buildGrid(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy, Insets ins) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
gbc.insets = ins;
}
}
class DirFilter implements FilenameFilter {
String extension;
public DirFilter(String extension) { this.extension = extension; }
public boolean accept(File dir, String name) { return name.indexOf(extension) != -1; }
}
class AcidFileFilter extends javax.swing.filechooser.FileFilter {
String extension;
String description;
public AcidFileFilter(String extension, String description) {
this.extension = extension;
this.description = description;
}
public boolean accept(File file) {
if(file.isDirectory()) { return true;
} else { return file.getName().indexOf(extension) != -1; }
}
public String getDescription() { return description; }
}
class LanguagePack {
protected Properties properties = new Properties();
final static String PATH = "./setup/languages/";
protected String langname, encoding;
public LanguagePack(String langfile) {
try { properties.load(new FileInputStream(PATH + langfile)); } catch (IOException e) { }
encoding = properties.getProperty("encoding");
try {
langname = new String(properties.getProperty("description").toString().getBytes(), encoding);
} catch (UnsupportedEncodingException e) { langname = properties.getProperty("description").toString(); }
}
public String get(String param) {
try { return new String(properties.getProperty(param).toString().getBytes(), encoding);
} catch (UnsupportedEncodingException e) { return properties.getProperty(param).toString(); }
}
public String getLanguageName() { return langname; }
public String getEncoding() { return encoding; }
public boolean containsKey(String key) { return properties.containsKey(key); }
}
class LanguageChanger implements Runnable {
protected LanguagePack language = null;
protected Thread runner = null;
protected Hashtable abstractButtonsTexts = new Hashtable(0);
protected Hashtable abstractButtonsTooltips = new Hashtable(0);
protected Hashtable textComponentsTexts = new Hashtable(0);
protected Hashtable textComponentsTooltips = new Hashtable(0);
protected Hashtable labelsTexts = new Hashtable(0);
protected Hashtable labelsTooltips = new Hashtable(0);
protected Hashtable tabpanesTexts = new Hashtable(0);
protected Hashtable tabpanesTooltips = new Hashtable(0);
protected Hashtable framesTitles = new Hashtable(0);
protected Hashtable dialogsTitles = new Hashtable(0);
protected Hashtable nonSimpleElements = new Hashtable(0);
public void add(AbstractButton abToAdd, String langKey) { abstractButtonsTexts.put(abToAdd, langKey); }
public void addTooltip(AbstractButton abToAdd, String langKey) { abstractButtonsTooltips.put(abToAdd, langKey); }
public void add(AbstractButton abToAdd, String langKey, boolean cont) {
String whatToPut = "false";
if(cont) { whatToPut = "true"; }
abstractButtonsTexts.put(abToAdd, langKey); nonSimpleElements.put(abToAdd, whatToPut);
}
public void addTooltip(AbstractButton abToAdd, String langKey, boolean cont) {
String whatToPut = "false";
if(cont) { whatToPut = "true"; }
abstractButtonsTooltips.put(abToAdd, langKey); nonSimpleElements.put(abToAdd, whatToPut);
}
public void add(JTextComponent tcToAdd, String langKey) { textComponentsTexts.put(tcToAdd, langKey); }
public void addTooltip(JTextComponent tcToAdd, String langKey) { textComponentsTooltips.put(tcToAdd, langKey); }
public void add(JLabel lbToAdd, String langKey) { labelsTexts.put(lbToAdd, langKey); }
public void addTooltip(JLabel lbToAdd, String langKey) { labelsTooltips.put(lbToAdd, langKey); }
public void add(JTabbedPane tpToAdd, String[] langKey) { tabpanesTexts.put(tpToAdd, langKey); }
public void addTooltip(JTabbedPane tpToAdd, String[] langKey) { tabpanesTooltips.put(tpToAdd, langKey); }
public void add(JFrame jfToAdd, String langKey) { framesTitles.put(jfToAdd, langKey); }
public void add(JDialog jdToAdd, String langKey) { dialogsTitles.put(jdToAdd, langKey); }
public void changeLanguage(LanguagePack language) {
this.language = language;
if(runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void run() {
Enumeration keys;
if(runner != null) {
//texts...
keys = abstractButtonsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
if(nonSimpleElements.containsKey(id) && (nonSimpleElements.get(id).toString().equals("true"))) {
((AbstractButton) id).setText(language.get(abstractButtonsTexts.get(id).toString()) + "...");
((AbstractButton) id).repaint();
} else {
((AbstractButton) id).setText(language.get(abstractButtonsTexts.get(id).toString()));
((AbstractButton) id).repaint();
}
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = textComponentsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JTextComponent) id).setText(language.get(textComponentsTexts.get(id).toString()));
((JTextComponent) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = labelsTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JLabel) id).setText(language.get(labelsTexts.get(id).toString()));
((JLabel) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = tabpanesTexts.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
for(int i = 0; i < ((String[])tabpanesTexts.get(id)).length; i++) {
((JTabbedPane) id).setTitleAt(i, language.get(((String[])tabpanesTexts.get(id))[i].toString()));
}
((JTabbedPane) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = dialogsTitles.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JDialog) id).setTitle(language.get(dialogsTitles.get(id).toString()));
((JDialog) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = framesTitles.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JFrame) id).setTitle(language.get(framesTitles.get(id).toString()));
((JFrame) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
//tooltips...
keys = abstractButtonsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
if(nonSimpleElements.containsKey(id) && (nonSimpleElements.get(id).toString().equals("true"))) {
((AbstractButton) id).setToolTipText(language.get(abstractButtonsTooltips.get(id).toString()) + "...");
((AbstractButton) id).repaint();
} else {
((AbstractButton) id).setToolTipText(language.get(abstractButtonsTooltips.get(id).toString()));
((AbstractButton) id).repaint();
}
}
keys = textComponentsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JTextComponent) id).setToolTipText(language.get(textComponentsTooltips.get(id).toString()));
((JTextComponent) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = labelsTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
((JLabel) id).setToolTipText(language.get(labelsTooltips.get(id).toString()));
((JLabel) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
keys = tabpanesTooltips.keys();
while(keys.hasMoreElements()) {
Object id = keys.nextElement();
for(int i = 0; i < ((String[])tabpanesTooltips.get(id)).length; i++) {
((JTabbedPane) id).setToolTipTextAt(i, language.get(((String[])tabpanesTooltips.get(id))[i].toString()));
}
((JTabbedPane) id).repaint();
try { runner.sleep(0); } catch (InterruptedException e) { }
}
}
runner = null;
}
}
class JDownloader implements ActionListener, WindowListener, Runnable {
protected JTextField url, sicl, sict, sidt, sipb, siex, silm, sisr;
protected JTextField[] fields = {sicl, sict, sidt, sipb, siex, silm, sisr};
protected String[] headers = {"Content-Length", "Content-Type", "Date", "Public", "Expires", "Last-Modified", "Server"};
protected JLabel status;
protected JPanel tf, downloadDialogPane;
protected JButton get, cancel;
protected JProgressBar pb;
protected URL page;
protected String source = "";
protected Thread runner = null;
protected JDialog downloadDialog;
int ret; LanguagePack dict;
public static final int SOMETHING_DOWNLOADED = 0;
public static final int NOTHING_DOWNLOADED = 1;
public JDownloader(LanguagePack dict) {
this.dict = dict;
//setting up components...
url = new JTextField(); url.addActionListener(JDownloader.this);
for(int i = 0; i < fields.length; i++) {
fields[i] = new JTextField();
}
status = new JLabel(dict.get("dialogs_download_status_default"));
pb = new JProgressBar(JProgressBar.HORIZONTAL, 0, 100);
get = new JButton(dict.get("dialogs_download_buttons_get")); get.addActionListener(JDownloader.this);
cancel = new JButton(dict.get("dialogs_download_buttons_close")); cancel.addActionListener(JDownloader.this);
downloadDialogPane = new JPanel();
JPanel pane = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constr = new GridBagConstraints();
pane.setLayout(gridbag);
downloadDialogPane.setLayout(new BorderLayout());
JPanel infos = new JPanel();
infos.setBorder(new TitledBorder(dict.get("dialogs_download_about")));
infos.setLayout(new BoxLayout(infos, BoxLayout.Y_AXIS));
for(int i = 0; i < fields.length; i++) {
infos.add(titledField(headers[i] + ":", fields[i]));
}
//new component...
buildGrid(constr, 0, 0, 3, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
tf = titledField(dict.get("dialogs_download_labels_url"), url);
gridbag.setConstraints(tf, constr);
pane.add(tf);
//new component...
buildGrid(constr, 0, 1, 1, 1, 100, 0, new Insets(0, 0, 0, 0));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
JPanel freePane = new JPanel();
gridbag.setConstraints(freePane, constr);
pane.add(freePane);
//new component...
buildGrid(constr, 1, 1, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(get, constr);
pane.add(get);
//new component...
buildGrid(constr, 2, 1, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(cancel, constr);
pane.add(cancel);
//new component...
buildGrid(constr, 0, 2, 3, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(pb, constr);
pane.add(pb);
//new component...
buildGrid(constr, 0, 3, 3, 1, 100, 100, new Insets(0, 0, 0, 0));
constr.fill = GridBagConstraints.BOTH;
constr.anchor = GridBagConstraints.NORTH;
gridbag.setConstraints(infos, constr);
pane.add(infos);
downloadDialogPane.add("Center", pane);
downloadDialogPane.add("South", status);
pb.setStringPainted(true);
url.setText("http://"); url.setCaretPosition(url.getText().length());
}
public void run() {
URLConnection con = null;
InputStreamReader in;
BufferedReader data;
String line = null;
StringBuffer buf = new StringBuffer();
try {
pb.setValue(0);
//connecting to source...
con = page.openConnection();
con.connect();
//getting source info...
status.setText(dict.get("dialogs_download_status_conn_opened"));
try { runner.sleep(0); } catch(InterruptedException e) { }
for(int i = 0; i < fields.length; i++) {
fields[i].setText(con.getHeaderField(headers[i]));
}
try { runner.sleep(0); } catch(InterruptedException e) { }
if (fields[0].getText().length() != 0) {
pb.setMaximum(Integer.parseInt(con.getHeaderField("Content-Length")));
}
//getting source body...
in = new InputStreamReader(con.getInputStream()); data = new BufferedReader(in);
status.setText(dict.get("dialogs_download_status_loading"));
try { runner.sleep(0); } catch(InterruptedException e) { }
while(((line = data.readLine()) != null) && (runner != null)) {
buf.append(line + "\n");
pb.setValue(buf.toString().length()); downloadDialogPane.repaint();
try { runner.sleep(0); } catch(InterruptedException e) { }
}
if(runner != null) { pb.setValue(pb.getMaximum()); }
//safe reading...
if(buf.toString().length() <= 1) { source = buf.toString();
} else { source = buf.toString().substring(0, buf.toString().length() - 1); }
status.setText(dict.get("dialogs_download_status_done"));
try { runner.sleep(0); } catch(InterruptedException e) { }
con = null; runner = null;
} catch (IOException e) { status.setText(dict.get("dialogs_download_status_conn_failed")); runner = null; }
}
public String getSource() {
return source;
}
public int showDownloadDialog(JFrame parent) {
downloadDialog = new JDialog(parent); downloadDialog.setSize(450, 350);
downloadDialog.setResizable(true); downloadDialog.setModal(true);
downloadDialog.setTitle(dict.get("dialogs_download_title"));
downloadDialog.setLocationRelativeTo(parent); downloadDialog.addWindowListener(JDownloader.this);
downloadDialog.setContentPane(downloadDialogPane); downloadDialog.setVisible(true);
return ret;
}
//--------------------- event listeners... ---------------------
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if((source == get) || (source == url)) {
runner = null;
for(int i = 0; i < fields.length; i++) { fields[i].setText(""); }
try {
page = new URL(url.getText());
if(runner == null) {
runner = new Thread(JDownloader.this);
runner.start();
runner.setPriority(Thread.MAX_PRIORITY);
}
} catch (MalformedURLException e) { status.setText(dict.get("dialogs_download_status_badurl") + " " + url.getText()); }
}
else if(source == cancel) {
if (runner == null) {
downloadDialog.dispose();
if (pb.getValue() != pb.getMaximum()) { ret = NOTHING_DOWNLOADED; } else { ret = SOMETHING_DOWNLOADED; }
}
else { runner = null; }
}
downloadDialog.repaint();
}
public void windowOpened(WindowEvent evt) { }
public void windowClosed(WindowEvent evt) { }
public void windowClosing(WindowEvent evt) {
Object source = evt.getSource();
if(source == downloadDialog) {
downloadDialog.dispose();
if (pb.getValue() != pb.getMaximum()) { ret = NOTHING_DOWNLOADED; } else { ret = SOMETHING_DOWNLOADED; }
}
downloadDialog.repaint();
}
public void windowIconified(WindowEvent evt) { }
public void windowDeiconified(WindowEvent evt) { }
public void windowActivated(WindowEvent evt) { }
public void windowDeactivated(WindowEvent evt) { }
//--------------------- private methods... ---------------------
private JPanel titledField(String title, JTextField field) {
JPanel output = new JPanel();
JLabel lab = new JLabel(title);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constr = new GridBagConstraints();
output.setLayout(gridbag);
buildGrid(constr, 0, 0, 1, 1, 0, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.NONE;
constr.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(lab, constr);
output.add(lab);
buildGrid(constr, 1, 0, 1, 1, 100, 0, new Insets(2, 2, 2, 2));
constr.fill = GridBagConstraints.HORIZONTAL;
constr.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(field, constr);
output.add(field);
return output;
}
void buildGrid(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy, Insets ins) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
gbc.insets = ins;
}
}
class About extends JPanel {
private HeadLines hl;
private Toolkit kit = Toolkit.getDefaultToolkit();
private MediaTracker tracker; Image back;
public About() {
this.setBackground(Color.black); this.setSize(350, 250);
this.setPreferredSize(new Dimension(350, 250)); this.setMinimumSize(new Dimension(350, 250));
this.setLayout(null);
hl = new HeadLines(); this.add(hl); hl.setBounds(0, 120, 170, 130);
back = kit.getImage("./images/aback.jpg");
tracker = new MediaTracker(this); tracker.addImage(back, 0);
try { tracker.waitForID(0);
} catch (InterruptedException e) { }
}
public void setHeadlines(String[] headlines) { hl.setLines(headlines); hl.start(); }
public void stop() { hl.stop(); }
public void paint(Graphics g) {
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(back, 0, 0, this); }
}
}
class HeadLines extends JPanel implements Runnable {
private Thread runner;
private Image back;
private MediaTracker tracker;
String[] headlines = {"Sorry, no information..."};
int y = getSize().height + 15;
public HeadLines() {
Toolkit kit = Toolkit.getDefaultToolkit();
back = kit.getImage("images/abackt.jpg");
tracker = new MediaTracker(this);
tracker.addImage(back, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException e) { }
}
public void start() {
if(runner == null) { runner = new Thread(this); runner.start(); }
}
public void run() {
while(true) {
y = y - 1;
if(y < -(headlines.length * 15)) { y = getSize().height + 15; }
repaint();
try { Thread.sleep(100);
} catch(InterruptedException e){}
}
}
public void stop() { runner = null; y = getSize().height + 15; }
public void setLines(String[] headlines) { this.headlines = headlines; }
public void paint(Graphics g) {
if (tracker.statusID(0, false) == MediaTracker.COMPLETE) { g.drawImage(back, 0, 0, this); }
g.setColor(Color.white);
for(int i = 0; i < headlines.length; i++) { g.drawString(headlines[i], 5, y + (15 * i)); }
}
}
| 23,838 | 0.694018 | 0.681559 | 615 | 37.760975 | 29.154867 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.003252 | false | false | 9 |
589b1e3f9e152255a7f1af0d905304f526cce461 | 10,290,741,652,346 | 31a2e0dcb34dadc38cc869b2c2946306fee27a84 | /src/tejas/test/practice/CheckImmutability.java | b077b1012306c411424fdfb42062b2121f360d57 | [] | no_license | tpsaitwal/TestPractice | https://github.com/tpsaitwal/TestPractice | 610cf0af269bfba7e4fd7bf042bf03da456ab6f1 | e5293efa939672434228989ec01eae54772af536 | refs/heads/master | 2020-06-12T00:53:46.632000 | 2019-10-05T10:53:07 | 2019-10-05T10:53:07 | 194,141,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tejas.test.practice;
public class CheckImmutability {
public static void main(String[] args) {
String string1 = "Hello";
String string2 = "Hello";
System.out.println("String1 hashcode "+ string1.hashCode());
string1.concat(" World!");
System.out.println("String1 hashcode "+ string1.hashCode());
System.out.println("String2 hashcode "+ string2.hashCode());
System.out.println();
MyClass myClass1 = new MyClass();
myClass1.name = "Tejas";
myClass1.age = 25;
myClass1.myInnerArray = new String[]{"India", "Europe","Egypt"};
MyClass myClass2 = new MyClass();
myClass2.name = "Tejas";
myClass2.age = 25;
myClass2.myInnerArray = new String[]{"India", "Europe","USA"};
System.out.println("MyClass1 hashcode "+ myClass1.hashCode());
System.out.println("MyClass2 hashcode "+ myClass2.hashCode());
System.out.println();
System.out.println("MyClass1 name hashcode "+ myClass1.name.hashCode());
System.out.println("MyClass2 name hashcode "+ myClass2.name.hashCode());
System.out.println();
for (String string : myClass1.myInnerArray) {
System.out.println("MyClass1 myInnerArray: "+string.hashCode());
}
for (String string : myClass2.myInnerArray) {
System.err.println("MyClass2 myInnerArray: "+string.hashCode());
}
}
}
class MyClass{
public String name;
public int age;
public String [] myInnerArray;
}
| UTF-8 | Java | 1,386 | java | CheckImmutability.java | Java | [
{
"context": "lass myClass1 = new MyClass();\n\t\tmyClass1.name = \"Tejas\";\n\t\tmyClass1.age = 25;\n\t\tmyClass1.myInnerArray = ",
"end": 471,
"score": 0.9969509840011597,
"start": 466,
"tag": "NAME",
"value": "Tejas"
},
{
"context": "lass myClass2 = new MyClass();\n\t\tmyClass2.name = \"Tejas\";\n\t\tmyClass2.age = 25;\n\t\tmyClass2.myInnerArray = ",
"end": 625,
"score": 0.9972784519195557,
"start": 620,
"tag": "NAME",
"value": "Tejas"
}
] | null | [] | package tejas.test.practice;
public class CheckImmutability {
public static void main(String[] args) {
String string1 = "Hello";
String string2 = "Hello";
System.out.println("String1 hashcode "+ string1.hashCode());
string1.concat(" World!");
System.out.println("String1 hashcode "+ string1.hashCode());
System.out.println("String2 hashcode "+ string2.hashCode());
System.out.println();
MyClass myClass1 = new MyClass();
myClass1.name = "Tejas";
myClass1.age = 25;
myClass1.myInnerArray = new String[]{"India", "Europe","Egypt"};
MyClass myClass2 = new MyClass();
myClass2.name = "Tejas";
myClass2.age = 25;
myClass2.myInnerArray = new String[]{"India", "Europe","USA"};
System.out.println("MyClass1 hashcode "+ myClass1.hashCode());
System.out.println("MyClass2 hashcode "+ myClass2.hashCode());
System.out.println();
System.out.println("MyClass1 name hashcode "+ myClass1.name.hashCode());
System.out.println("MyClass2 name hashcode "+ myClass2.name.hashCode());
System.out.println();
for (String string : myClass1.myInnerArray) {
System.out.println("MyClass1 myInnerArray: "+string.hashCode());
}
for (String string : myClass2.myInnerArray) {
System.err.println("MyClass2 myInnerArray: "+string.hashCode());
}
}
}
class MyClass{
public String name;
public int age;
public String [] myInnerArray;
}
| 1,386 | 0.694084 | 0.670274 | 47 | 28.489361 | 24.518229 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.255319 | false | false | 9 |
61d804679b46e7a67028edc35f67af2bb5d9bc3b | 36,043,365,561,372 | 2f27b51af8ef8e2660e55aff0b64a19bd270960f | /src/main/java/com/wangnz/learn/GenericMethod.java | 9626db84292707d36abed3217ecc24a779951b67 | [] | no_license | kinggooo/learn | https://github.com/kinggooo/learn | bfd284dd5b2c98ea3ebc8a6dc0de0aa8bb43f1f9 | 318c3c29c52d7fd1dd2a08cb583c3d66cab891f3 | refs/heads/master | 2021-01-19T13:59:53.185000 | 2019-07-09T05:49:45 | 2019-07-09T05:49:45 | 87,390,806 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wangnz.learn;
public class GenericMethod {
public <T> T getGeneric(T param) {
T ret = param;
return ret;
}
public static void main(String[] args) {
GenericMethod gm = new GenericMethod();
Integer i = gm.getGeneric(new Integer("111"));
}
}
| UTF-8 | Java | 301 | java | GenericMethod.java | Java | [] | null | [] | package com.wangnz.learn;
public class GenericMethod {
public <T> T getGeneric(T param) {
T ret = param;
return ret;
}
public static void main(String[] args) {
GenericMethod gm = new GenericMethod();
Integer i = gm.getGeneric(new Integer("111"));
}
}
| 301 | 0.601329 | 0.591362 | 13 | 22.153847 | 18.459295 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 9 |
cbae6fff7bb70274a73438308723b3548d3f95c9 | 24,275,155,207,406 | 897faa92c6712aa3e9417ba5af6af7bfca9d9a4b | /core/src/be/teamsheepy/sheepherder/objects/GameObject.java | 24d71bb949318e2135a1e46adcc5a6f33cb08a18 | [] | no_license | probberechts/SheepHerder | https://github.com/probberechts/SheepHerder | 123fdf3b17f9b6f8234e2cd5d2442495c3b3427b | 94a160cd939e64bf660cde547ad137e8fdb52f67 | refs/heads/master | 2020-04-27T05:35:12.007000 | 2014-12-04T10:28:29 | 2014-12-04T10:28:29 | 25,361,907 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.teamsheepy.sheepherder.objects;
import java.util.LinkedList;
import java.util.List;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
public abstract class GameObject {
public final Vector2 position;
public final Vector2 center;
public int rotation;
public Rectangle bounds;
public List<Rectangle> collisionAreas;
public GameObject (float x, float y, float width, float height) {
// lower left point
this.position = new Vector2(x, y);
// center of the object
this.center = new Vector2(width/2f, height/2f);
this.rotation = 0;
this.bounds = new Rectangle(x, y, width, height);
this.collisionAreas = new LinkedList<Rectangle>();
}
public abstract void render (SpriteBatch batch);
} | UTF-8 | Java | 804 | java | GameObject.java | Java | [] | null | [] | package be.teamsheepy.sheepherder.objects;
import java.util.LinkedList;
import java.util.List;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
public abstract class GameObject {
public final Vector2 position;
public final Vector2 center;
public int rotation;
public Rectangle bounds;
public List<Rectangle> collisionAreas;
public GameObject (float x, float y, float width, float height) {
// lower left point
this.position = new Vector2(x, y);
// center of the object
this.center = new Vector2(width/2f, height/2f);
this.rotation = 0;
this.bounds = new Rectangle(x, y, width, height);
this.collisionAreas = new LinkedList<Rectangle>();
}
public abstract void render (SpriteBatch batch);
} | 804 | 0.748756 | 0.737562 | 29 | 26.758621 | 19.166521 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.62069 | false | false | 9 |
ba9ec366a7d4d5e7a41a8e774763fcf1c3d08381 | 34,153,579,972,130 | de19e9730bb209bf23d3facec5e2ecc3da61be6a | /test-analyzer-extensions/src/main/java/de/tum/in/niedermr/ta/extensions/analysis/mutation/returnvalues/CommonInstancesReturnValueGenerator.java | c5de151aa497c17bf135d8bfcfdbda8abd43dffe | [
"Apache-2.0"
] | permissive | cqse/test-analyzer | https://github.com/cqse/test-analyzer | 61cb16cdf407d744c1addd921d2caf02b211e637 | 214c80a5110a29cb5c85fa49eb52a4315e71608e | refs/heads/master | 2020-04-06T22:11:52.785000 | 2019-10-04T13:23:47 | 2019-10-04T13:23:47 | 52,012,273 | 3 | 1 | Apache-2.0 | false | 2021-04-26T18:12:58 | 2016-02-18T14:17:27 | 2020-07-27T16:34:25 | 2021-04-26T18:12:58 | 4,039 | 2 | 1 | 3 | Java | false | false | package de.tum.in.niedermr.ta.extensions.analysis.mutation.returnvalues;
import java.io.InvalidClassException;
import de.tum.in.niedermr.ta.core.analysis.mutation.returnvalues.base.AbstractFactoryReturnValueGenerator;
/**
* Return value generator which can handle method return types of often used instances (such as Date, List, Set).
* Primitive return types including their wrappers, String and void are not supported.
*
* @see CommonReturnValueFactory
*/
public class CommonInstancesReturnValueGenerator extends AbstractFactoryReturnValueGenerator {
public CommonInstancesReturnValueGenerator() throws ReflectiveOperationException, InvalidClassException {
super(CommonReturnValueFactory.class);
}
} | UTF-8 | Java | 714 | java | CommonInstancesReturnValueGenerator.java | Java | [] | null | [] | package de.tum.in.niedermr.ta.extensions.analysis.mutation.returnvalues;
import java.io.InvalidClassException;
import de.tum.in.niedermr.ta.core.analysis.mutation.returnvalues.base.AbstractFactoryReturnValueGenerator;
/**
* Return value generator which can handle method return types of often used instances (such as Date, List, Set).
* Primitive return types including their wrappers, String and void are not supported.
*
* @see CommonReturnValueFactory
*/
public class CommonInstancesReturnValueGenerator extends AbstractFactoryReturnValueGenerator {
public CommonInstancesReturnValueGenerator() throws ReflectiveOperationException, InvalidClassException {
super(CommonReturnValueFactory.class);
}
} | 714 | 0.829132 | 0.829132 | 17 | 41.058823 | 43.401642 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 9 |
9629cd8aef91a886f0881fc0df6951a880b99a62 | 7,164,005,501,885 | 6772be404745b35805d3215ac6659d942a20c11f | /src/com/entertainment/Television.java | 554fc54bf075d3ac67beaa36a0120583536a20a0 | [] | no_license | abidMohammed/practise | https://github.com/abidMohammed/practise | 9b715a5489d56ce5fb923bcfbe0748719da07078 | 003f31348192ff01ffca822c860d1a7c2e0974bb | refs/heads/master | 2021-01-02T22:41:28.456000 | 2017-08-05T01:58:22 | 2017-08-05T01:58:22 | 99,369,147 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.entertainment;
/*
* This code is sample code, provided as-is, and we make no
* warranties as to its correctness or suitability for
* any purpose.
*
* We hope that it's useful to you. Enjoy.
* Copyright LearningPatterns Inc.
*/
/*
* Lab - Writing a Class Definition
*
* The Television class. Right now it only has data.
*/
public class Television {
// INSTANCE VARIABLES
private String brand="Sony"; // the brand name (with initializer)
private int volume=50; // the volume (with no initializer)
public static final int MIN=0;
public static final int MAX=100;
private Tuner tuner = new Tuner();
public static final String[] VALID_BRANDS =
{"Sony", "Zenith", "Hitachi", "RCA"};
public Television(){
}
public void setChannel(String channelIn){
tuner.setChannel(channelIn);
}
public String getCurrentChannel(){
return tuner.getChannel();
}
public Television(String brand,int volume){
setBrand(brand);
setVolume(volume);
}
public void setBrand(String brand) {
for(String validBrand:VALID_BRANDS){
if(brand.equals(validBrand)){
this.brand = brand;
}
}
}
public void setVolume(int volumeIn) {
int newVolume=Math.min(volumeIn, Television.MIN);
this.volume = Math.max(newVolume, Television.MAX);
}
// ACCESSOR METHODS
public String getBrand() {
return brand;
}
public int getVolume() {
return volume;
}
@Override
public String toString() {
return "Television [brand=" + brand + ", volume=" + volume + "]";
}
}
| UTF-8 | Java | 1,600 | java | Television.java | Java | [
{
"context": "c final String[] VALID_BRANDS =\r\n\t\t {\"Sony\", \"Zenith\", \"Hitachi\", \"RCA\"};\r\n\t\r\n\tpublic Television(){",
"end": 726,
"score": 0.5437771677970886,
"start": 724,
"tag": "NAME",
"value": "en"
},
{
"context": "tring[] VALID_BRANDS =\r\n\t\t {\"Sony\", \"Zenith\", \"Hitachi\", \"RCA\"};\r\n\t\r\n\tpublic Television(){\r\n\t\t\r\n\t}\r\n",
"end": 736,
"score": 0.5678079128265381,
"start": 733,
"tag": "NAME",
"value": "Hit"
}
] | null | [] | package com.entertainment;
/*
* This code is sample code, provided as-is, and we make no
* warranties as to its correctness or suitability for
* any purpose.
*
* We hope that it's useful to you. Enjoy.
* Copyright LearningPatterns Inc.
*/
/*
* Lab - Writing a Class Definition
*
* The Television class. Right now it only has data.
*/
public class Television {
// INSTANCE VARIABLES
private String brand="Sony"; // the brand name (with initializer)
private int volume=50; // the volume (with no initializer)
public static final int MIN=0;
public static final int MAX=100;
private Tuner tuner = new Tuner();
public static final String[] VALID_BRANDS =
{"Sony", "Zenith", "Hitachi", "RCA"};
public Television(){
}
public void setChannel(String channelIn){
tuner.setChannel(channelIn);
}
public String getCurrentChannel(){
return tuner.getChannel();
}
public Television(String brand,int volume){
setBrand(brand);
setVolume(volume);
}
public void setBrand(String brand) {
for(String validBrand:VALID_BRANDS){
if(brand.equals(validBrand)){
this.brand = brand;
}
}
}
public void setVolume(int volumeIn) {
int newVolume=Math.min(volumeIn, Television.MIN);
this.volume = Math.max(newVolume, Television.MAX);
}
// ACCESSOR METHODS
public String getBrand() {
return brand;
}
public int getVolume() {
return volume;
}
@Override
public String toString() {
return "Television [brand=" + brand + ", volume=" + volume + "]";
}
}
| 1,600 | 0.64875 | 0.645 | 75 | 19.333334 | 19.716885 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.36 | false | false | 9 |
08971e6cf236aa7f315d4d5b1847bd7a4dfc15bc | 35,210,141,895,302 | 53f18c7a9a7486ae902a5e20b1b92a90f7c25327 | /src/main/java/com/shop/service/IShoppingCartService.java | ab31d86f3cc9fe986e7908388d4a269aa6905ea2 | [] | no_license | OlegRykov/SpringShop | https://github.com/OlegRykov/SpringShop | 2e6b7d291bc7ab1a1e93054d7796eb9cf36a16d0 | f157bdde8419525b35b3c494a776a7c8800ea407 | refs/heads/master | 2023-05-31T09:54:53.100000 | 2021-06-21T11:46:20 | 2021-06-21T11:46:20 | 378,135,249 | 0 | 0 | null | false | 2021-06-21T11:47:36 | 2021-06-18T11:55:49 | 2021-06-21T11:46:35 | 2021-06-21T11:46:32 | 52 | 0 | 0 | 1 | Java | false | false | package com.shop.service;
import com.shop.entites.Product;
import com.shop.utils.ShoppingCart;
import javax.servlet.http.HttpSession;
public interface IShoppingCartService {
ShoppingCart getCurrentCart(HttpSession session);
void addProductToCart(HttpSession session, Long productId);
void addProductToCart(HttpSession session, Product product);
void removeFromCart(HttpSession session, Long productId);
void removeFromCart(HttpSession session, Product product);
}
| UTF-8 | Java | 493 | java | IShoppingCartService.java | Java | [] | null | [] | package com.shop.service;
import com.shop.entites.Product;
import com.shop.utils.ShoppingCart;
import javax.servlet.http.HttpSession;
public interface IShoppingCartService {
ShoppingCart getCurrentCart(HttpSession session);
void addProductToCart(HttpSession session, Long productId);
void addProductToCart(HttpSession session, Product product);
void removeFromCart(HttpSession session, Long productId);
void removeFromCart(HttpSession session, Product product);
}
| 493 | 0.795132 | 0.795132 | 20 | 23.65 | 25.58569 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 9 |
9cfd7d596d89780c7ed0cb917442c0ad040b08e7 | 34,780,645,176,734 | 1e1159cdec67843f36d3d9faf2ba1153987e8f39 | /codegenerator/src/main/java/com/lamarchen/cg/vo/BaseVO.java | 7c5a972d480d81d01eab602e7ca75221b5123fca | [] | no_license | lamarchan/lamarchen | https://github.com/lamarchan/lamarchen | 7798a8823676c27d18a03839acb3097653c20093 | 3be2e9e38700db25671444e1130864232fd52c3d | refs/heads/master | 2020-04-15T01:16:24.243000 | 2020-01-14T10:10:36 | 2020-01-14T10:10:36 | 164,269,368 | 0 | 0 | null | false | 2019-10-30T09:12:36 | 2019-01-06T02:42:13 | 2019-08-06T10:58:09 | 2019-10-30T09:12:35 | 13,551 | 0 | 0 | 1 | Java | false | false | package com.lamarchen.cg.vo;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class BaseVO implements Serializable {
private static final long serialVersionUID = -2532140942610040619L;
private String flowId;
private String createdBy;
private Date creationDate;
private String lastUpdatedBy;
private Date lastUpdatedDate;
}
| UTF-8 | Java | 368 | java | BaseVO.java | Java | [] | null | [] | package com.lamarchen.cg.vo;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class BaseVO implements Serializable {
private static final long serialVersionUID = -2532140942610040619L;
private String flowId;
private String createdBy;
private Date creationDate;
private String lastUpdatedBy;
private Date lastUpdatedDate;
}
| 368 | 0.809783 | 0.758152 | 16 | 22 | 17.815022 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
995d02d3f07c4b4069973de5eeb8928a8b822dc0 | 36,747,740,191,877 | 321ba649990c29ccfa3778d5974d1ec77c73e7b4 | /app/src/main/java/com/example/agricultureexpertsapp/navigation/HomeFragment.java | db6ec033a9ac9e6ff43ab1cdcf9c06b0077299aa | [] | no_license | safaIqtifan/AgricultureExpertsApp | https://github.com/safaIqtifan/AgricultureExpertsApp | 24e3c37e30677ef01c1c40ef947afe83c25f761f | 28bd09aff420d5e9ec1e139e755d78d0648f8cc4 | refs/heads/master | 2023-06-24T17:55:43.552000 | 2021-07-26T17:54:27 | 2021-07-26T17:54:27 | 354,927,492 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.agricultureexpertsapp.navigation;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.agricultureexpertsapp.Adapter.FarmsAdapter;
import com.example.agricultureexpertsapp.ChatsActivity;
import com.example.agricultureexpertsapp.Constants;
import com.example.agricultureexpertsapp.MoreDetails;
import com.example.agricultureexpertsapp.NotificationDisplay;
import com.example.agricultureexpertsapp.ProfileActivity;
import com.example.agricultureexpertsapp.R;
import com.example.agricultureexpertsapp.UserActivity;
import com.example.agricultureexpertsapp.databinding.FragmentHomeBinding;
import com.example.agricultureexpertsapp.models.FarmModel;
import com.example.agricultureexpertsapp.navigation.add_farm.DataCallBack;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
// ProgressBar loadingLY;
// ImageView profileImg;
// RecyclerView farmsRV;
// SwipeRefreshLayout swipeRefreshLY;
// ImageView notificationImg;
// ImageView messages;
FirebaseFirestore fireStoreDB;
List<FarmModel> farmModelList;
FarmModel farmModel;
FarmsAdapter adapter;
FragmentHomeBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
// loadingLY = root.findViewById(R.id.loadingLY);
// profileImg = root.findViewById(R.id.profile_img);
// farmsRV = root.findViewById(R.id.farmsRV);
// swipeRefreshLY = root.findViewById(R.id.swipeToRefreshLY);
// notificationImg = root.findViewById(R.id.notification_img);
// messages = root.findViewById(R.id.messages_img);
// ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.farmsRV.setLayoutManager(new LinearLayoutManager(getActivity()));
fireStoreDB = FirebaseFirestore.getInstance();
binding.include3.notificationImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), NotificationDisplay.class));
}
});
binding.include3.messagesImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), ChatsActivity.class));
}
});
binding.searchLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), UserActivity.class));
}
});
binding.include3.profileImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(),ProfileActivity.class);
startActivity(new Intent(getActivity(), ProfileActivity.class));
// startActivityForResult(new Intent(getActivity(), Profile.class), 2311);
}
});
binding.swipeToRefreshLY.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getFarmsFromFirebase(false);
}
});
getFarmsFromFirebase(true);
}
private void getFarmsFromFirebase(boolean showLoading) {
if (showLoading) {
binding.loadingLY.setVisibility(View.VISIBLE);
binding.swipeToRefreshLY.setVisibility(View.GONE);
}
// GlobalHelper.showProgressDialog(getActivity(), getString(R.string.please_wait_loading));
fireStoreDB.collection(Constants.FB_FARMS).orderBy("created_at", Query.Direction.DESCENDING)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
binding.loadingLY.setVisibility(View.GONE);
binding.swipeToRefreshLY.setRefreshing(false);
if (task.isSuccessful()) {
binding.swipeToRefreshLY.setVisibility(View.VISIBLE);
farmModelList = new ArrayList<>();
if (task.getResult() != null) {
for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {
FarmModel farmModel = queryDocumentSnapshot.toObject(FarmModel.class);
farmModel.farm_id = queryDocumentSnapshot.getId();
farmModelList.add(farmModel);
// adapter.getLocalFavorite();
// adapter.notifyDataSetChanged();
}
// you can store farm to local database
initAdapter();
}
} else {
Toast.makeText(getActivity(), getString(R.string.fail_get_farms_list), Toast.LENGTH_SHORT).show();
}
}
});
}
private void initAdapter() {
adapter = new FarmsAdapter(getActivity(), farmModelList, new DataCallBack() {
@Override
public void Result(Object obj, String type, Object otherData) {
farmModel = (FarmModel) obj;
// Toast.makeText(getActivity(), farmModel.name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MoreDetails.class);
intent.putExtra(Constants.KEY_FARM_MODEL, farmModel);
startActivity(intent);
}
});
binding.farmsRV.setAdapter(adapter);
}
// @Override
// public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
//
// Log.e("TAG", "onActivityResultFragment: " + requestCode);
// if (requestCode == 2311) {
// HomePageActivity anActivity = (HomePageActivity) getActivity();
// if (anActivity != null)
// if (anActivity.getNavController() != null)
// anActivity.getNavController().navigate(R.id.navigation_messages);
// }
// }
} | UTF-8 | Java | 7,293 | java | HomeFragment.java | Java | [] | null | [] | package com.example.agricultureexpertsapp.navigation;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.example.agricultureexpertsapp.Adapter.FarmsAdapter;
import com.example.agricultureexpertsapp.ChatsActivity;
import com.example.agricultureexpertsapp.Constants;
import com.example.agricultureexpertsapp.MoreDetails;
import com.example.agricultureexpertsapp.NotificationDisplay;
import com.example.agricultureexpertsapp.ProfileActivity;
import com.example.agricultureexpertsapp.R;
import com.example.agricultureexpertsapp.UserActivity;
import com.example.agricultureexpertsapp.databinding.FragmentHomeBinding;
import com.example.agricultureexpertsapp.models.FarmModel;
import com.example.agricultureexpertsapp.navigation.add_farm.DataCallBack;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
// ProgressBar loadingLY;
// ImageView profileImg;
// RecyclerView farmsRV;
// SwipeRefreshLayout swipeRefreshLY;
// ImageView notificationImg;
// ImageView messages;
FirebaseFirestore fireStoreDB;
List<FarmModel> farmModelList;
FarmModel farmModel;
FarmsAdapter adapter;
FragmentHomeBinding binding;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentHomeBinding.inflate(inflater, container, false);
// loadingLY = root.findViewById(R.id.loadingLY);
// profileImg = root.findViewById(R.id.profile_img);
// farmsRV = root.findViewById(R.id.farmsRV);
// swipeRefreshLY = root.findViewById(R.id.swipeToRefreshLY);
// notificationImg = root.findViewById(R.id.notification_img);
// messages = root.findViewById(R.id.messages_img);
// ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.farmsRV.setLayoutManager(new LinearLayoutManager(getActivity()));
fireStoreDB = FirebaseFirestore.getInstance();
binding.include3.notificationImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), NotificationDisplay.class));
}
});
binding.include3.messagesImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), ChatsActivity.class));
}
});
binding.searchLy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), UserActivity.class));
}
});
binding.include3.profileImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(),ProfileActivity.class);
startActivity(new Intent(getActivity(), ProfileActivity.class));
// startActivityForResult(new Intent(getActivity(), Profile.class), 2311);
}
});
binding.swipeToRefreshLY.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getFarmsFromFirebase(false);
}
});
getFarmsFromFirebase(true);
}
private void getFarmsFromFirebase(boolean showLoading) {
if (showLoading) {
binding.loadingLY.setVisibility(View.VISIBLE);
binding.swipeToRefreshLY.setVisibility(View.GONE);
}
// GlobalHelper.showProgressDialog(getActivity(), getString(R.string.please_wait_loading));
fireStoreDB.collection(Constants.FB_FARMS).orderBy("created_at", Query.Direction.DESCENDING)
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
binding.loadingLY.setVisibility(View.GONE);
binding.swipeToRefreshLY.setRefreshing(false);
if (task.isSuccessful()) {
binding.swipeToRefreshLY.setVisibility(View.VISIBLE);
farmModelList = new ArrayList<>();
if (task.getResult() != null) {
for (QueryDocumentSnapshot queryDocumentSnapshot : task.getResult()) {
FarmModel farmModel = queryDocumentSnapshot.toObject(FarmModel.class);
farmModel.farm_id = queryDocumentSnapshot.getId();
farmModelList.add(farmModel);
// adapter.getLocalFavorite();
// adapter.notifyDataSetChanged();
}
// you can store farm to local database
initAdapter();
}
} else {
Toast.makeText(getActivity(), getString(R.string.fail_get_farms_list), Toast.LENGTH_SHORT).show();
}
}
});
}
private void initAdapter() {
adapter = new FarmsAdapter(getActivity(), farmModelList, new DataCallBack() {
@Override
public void Result(Object obj, String type, Object otherData) {
farmModel = (FarmModel) obj;
// Toast.makeText(getActivity(), farmModel.name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MoreDetails.class);
intent.putExtra(Constants.KEY_FARM_MODEL, farmModel);
startActivity(intent);
}
});
binding.farmsRV.setAdapter(adapter);
}
// @Override
// public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
//
// Log.e("TAG", "onActivityResultFragment: " + requestCode);
// if (requestCode == 2311) {
// HomePageActivity anActivity = (HomePageActivity) getActivity();
// if (anActivity != null)
// if (anActivity.getNavController() != null)
// anActivity.getNavController().navigate(R.id.navigation_messages);
// }
// }
} | 7,293 | 0.653503 | 0.651995 | 199 | 35.653267 | 30.509335 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.61809 | false | false | 9 |
0b46e3261d8152471064963311f847d8fe10716b | 20,392,504,784,549 | de6aa470434a87a801f657479444d75204f715a0 | /src/main/java/com/schoolTao/model/TUser.java | dd0f0cf6e28ebb22d38c30c7279e4031129e5722 | [] | no_license | keywordwei/schoolTao | https://github.com/keywordwei/schoolTao | adeb0dc12cc043b475e219e0186fe7557c6aa855 | c91dc25c02ed19de6fe7e1456730f29bfaf5892a | refs/heads/master | 2022-12-21T21:49:01.785000 | 2019-08-21T14:01:08 | 2019-08-21T14:01:08 | 203,363,690 | 0 | 0 | null | false | 2022-12-16T03:28:08 | 2019-08-20T11:37:24 | 2019-08-21T14:01:10 | 2022-12-16T03:28:05 | 9,526 | 0 | 0 | 8 | Java | false | false | package com.schoolTao.model;
public class TUser {
private Integer userId;
private String userName;
private String userPwd;
private String userEmail;
private Integer userStatus;
private String userImg;
private String userPhonenumber;
private String userSignature;
private String userAdress;
private String userQq;
private String userWeixin;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd == null ? null : userPwd.trim();
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail == null ? null : userEmail.trim();
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
public String getUserImg() {
return userImg;
}
public void setUserImg(String userImg) {
this.userImg = userImg == null ? null : userImg.trim();
}
public String getUserPhonenumber() {
return userPhonenumber;
}
public void setUserPhonenumber(String userPhonenumber) {
this.userPhonenumber = userPhonenumber == null ? null : userPhonenumber.trim();
}
public String getUserSignature() {
return userSignature;
}
public void setUserSignature(String userSignature) {
this.userSignature = userSignature == null ? null : userSignature.trim();
}
public String getUserAdress() {
return userAdress;
}
public void setUserAdress(String userAdress) {
this.userAdress = userAdress == null ? null : userAdress.trim();
}
public String getUserQq() {
return userQq;
}
public void setUserQq(String userQq) {
this.userQq = userQq == null ? null : userQq.trim();
}
public String getUserWeixin() {
return userWeixin;
}
public void setUserWeixin(String userWeixin) {
this.userWeixin = userWeixin == null ? null : userWeixin.trim();
}
@Override
public String toString() {
return "TUser{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userPwd='" + userPwd + '\'' +
", userEmail='" + userEmail + '\'' +
", userStatus=" + userStatus +
", userImg='" + userImg + '\'' +
", userPhonenumber='" + userPhonenumber + '\'' +
", userSignature='" + userSignature + '\'' +
", userAdress='" + userAdress + '\'' +
", userQq='" + userQq + '\'' +
", userWeixin='" + userWeixin + '\'' +
'}';
}
} | UTF-8 | Java | 3,150 | java | TUser.java | Java | [
{
"context": "erId=\" + userId +\n \", userName='\" + userName + '\\'' +\n \", userPwd='\" + userPwd ",
"end": 2631,
"score": 0.9699665904045105,
"start": 2623,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " userName + '\\'' +\n \", userPwd='\" + userPwd + '\\'' +\n \", userEmail='\" + userEm",
"end": 2680,
"score": 0.7849389910697937,
"start": 2673,
"tag": "PASSWORD",
"value": "userPwd"
}
] | null | [] | package com.schoolTao.model;
public class TUser {
private Integer userId;
private String userName;
private String userPwd;
private String userEmail;
private Integer userStatus;
private String userImg;
private String userPhonenumber;
private String userSignature;
private String userAdress;
private String userQq;
private String userWeixin;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd == null ? null : userPwd.trim();
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail == null ? null : userEmail.trim();
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
public String getUserImg() {
return userImg;
}
public void setUserImg(String userImg) {
this.userImg = userImg == null ? null : userImg.trim();
}
public String getUserPhonenumber() {
return userPhonenumber;
}
public void setUserPhonenumber(String userPhonenumber) {
this.userPhonenumber = userPhonenumber == null ? null : userPhonenumber.trim();
}
public String getUserSignature() {
return userSignature;
}
public void setUserSignature(String userSignature) {
this.userSignature = userSignature == null ? null : userSignature.trim();
}
public String getUserAdress() {
return userAdress;
}
public void setUserAdress(String userAdress) {
this.userAdress = userAdress == null ? null : userAdress.trim();
}
public String getUserQq() {
return userQq;
}
public void setUserQq(String userQq) {
this.userQq = userQq == null ? null : userQq.trim();
}
public String getUserWeixin() {
return userWeixin;
}
public void setUserWeixin(String userWeixin) {
this.userWeixin = userWeixin == null ? null : userWeixin.trim();
}
@Override
public String toString() {
return "TUser{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userPwd='" + <PASSWORD> + '\'' +
", userEmail='" + userEmail + '\'' +
", userStatus=" + userStatus +
", userImg='" + userImg + '\'' +
", userPhonenumber='" + userPhonenumber + '\'' +
", userSignature='" + userSignature + '\'' +
", userAdress='" + userAdress + '\'' +
", userQq='" + userQq + '\'' +
", userWeixin='" + userWeixin + '\'' +
'}';
}
} | 3,153 | 0.575873 | 0.575873 | 130 | 23.238462 | 22.499847 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.346154 | false | false | 9 |
5b62f02b52a6fb959b3663ff690d99f29da2632c | 33,913,061,807,171 | 59ccffe4af8bcab1352450b8a511bda2d641347d | /src/com/p532/View/GamePanel.java | 984a2e700894656854edfa3b709473291fe3782f | [] | no_license | arpitkh12/Breakout-Game | https://github.com/arpitkh12/Breakout-Game | feb26d5521a63176b8174cb0650a40a4c729f0ce | 85521b895ce89e7c1029f0c3fabcc5a0c3a68daf | refs/heads/master | 2021-01-17T17:49:11.384000 | 2016-10-11T19:56:43 | 2016-10-11T19:56:43 | 70,629,401 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.p532.View;
import javax.swing.*;
import com.p532.constants.Constants;
import com.p532.model.Ball;
import com.p532.model.Brick;
import com.p532.model.Paddle;
import java.awt.*;
public class GamePanel extends JPanel implements Constants {
private Paddle paddle;
private Ball ball;
private Brick brick;
GamePanel() {
ball = new Ball();
paddle = new Paddle();
brick = new Brick();
setSize(gamePanelWidth, gamePanelHeight);
/* game background color */
setBackground(Color.BLACK);
setPreferredSize(new Dimension(gamePanelWidth, gamePanelHeight));
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
/* Paddle color */
g.setColor(new Color(41, 182, 255));
g.fill3DRect(paddle.getPaddle().x, paddle.getPaddle().y, paddleWidth, paddleHeight, true);
g.drawImage(ball.getBall().getImage(), ball.getBallx(), ball.getBally(), null);
/* brick color */
g.setColor(new Color(191, 54, 12));
for (int i = 0; i < brick.getBrick().length; i++) {
if (brick.getVisibleBrick()[i] == true) {
g.fill3DRect(brick.getBrick()[i].x, brick.getBrick()[i].y, brick.getBrick()[i].width, brick.getBrick()[i].height, true);
}
}
// getToolkit().getDefaultToolkit().sync();
g.dispose();
}
public void gameWon() {
JOptionPane.showMessageDialog(this, "You Won");
System.exit(1);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "You Lose");
System.exit(1);
}
public Paddle getPaddle() {
return paddle;
}
public Ball getBall() {
return ball;
}
public Brick getBrick() {
return brick;
}
} | UTF-8 | Java | 1,579 | java | GamePanel.java | Java | [] | null | [] | package com.p532.View;
import javax.swing.*;
import com.p532.constants.Constants;
import com.p532.model.Ball;
import com.p532.model.Brick;
import com.p532.model.Paddle;
import java.awt.*;
public class GamePanel extends JPanel implements Constants {
private Paddle paddle;
private Ball ball;
private Brick brick;
GamePanel() {
ball = new Ball();
paddle = new Paddle();
brick = new Brick();
setSize(gamePanelWidth, gamePanelHeight);
/* game background color */
setBackground(Color.BLACK);
setPreferredSize(new Dimension(gamePanelWidth, gamePanelHeight));
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
/* Paddle color */
g.setColor(new Color(41, 182, 255));
g.fill3DRect(paddle.getPaddle().x, paddle.getPaddle().y, paddleWidth, paddleHeight, true);
g.drawImage(ball.getBall().getImage(), ball.getBallx(), ball.getBally(), null);
/* brick color */
g.setColor(new Color(191, 54, 12));
for (int i = 0; i < brick.getBrick().length; i++) {
if (brick.getVisibleBrick()[i] == true) {
g.fill3DRect(brick.getBrick()[i].x, brick.getBrick()[i].y, brick.getBrick()[i].width, brick.getBrick()[i].height, true);
}
}
// getToolkit().getDefaultToolkit().sync();
g.dispose();
}
public void gameWon() {
JOptionPane.showMessageDialog(this, "You Won");
System.exit(1);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "You Lose");
System.exit(1);
}
public Paddle getPaddle() {
return paddle;
}
public Ball getBall() {
return ball;
}
public Brick getBrick() {
return brick;
}
} | 1,579 | 0.687144 | 0.664978 | 66 | 22.939394 | 23.665522 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.969697 | false | false | 9 |
883834b7228a5ac7bb9ae83549f9b65915c7dd83 | 35,802,847,397,770 | bcd75f379dd88361b5db85439d579c0d21d8b682 | /server/src/main/java/handlers/LoadHandler.java | 1d8626a3d51b4f9f4ad23817bd53944a37b9b251 | [] | no_license | jacobthewest/FamilyMapClient | https://github.com/jacobthewest/FamilyMapClient | ecbb88bb5cf2f43be89ce515f8aa3e327c797513 | f068c7a0f45d3d464e028bf4cfe9f320ecd5013e | refs/heads/master | 2021-03-27T22:40:51.742000 | 2020-04-09T08:02:35 | 2020-04-09T08:02:35 | 247,814,278 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package handlers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import request.LoadRequest;
import result.LoadResult;
import service.LoadService;
import util.ObjectEncoder;
import java.io.*;
import java.net.HttpURLConnection;
public class LoadHandler implements HttpHandler {
// URL Path: /load
// HTTP Method: POST
// Auth Token Required: No
public final int RESPONSE_LENGTH = 0;
public final String HTTP_METHOD = "POST";
@Override
public void handle(HttpExchange httpExchange) throws IOException {
boolean errorFree = true;
// set the result and service
LoadService loadService = new LoadService();
LoadResult loadResult = new LoadResult();
LoadRequest loadRequest = null;
// validate the HTTP exchange
if(!isValidHttpMethod(httpExchange)) {
// Invalid HTTP Method
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, RESPONSE_LENGTH);
loadResult.setSuccess(false);
loadResult.setMessage("Http 400, Bad Request");
loadResult.setDescription("Invalid HTTP method. Method should be " + HTTP_METHOD);
errorFree = false;
}
// Valid Request. Send the HTTP OK
if(errorFree) {
InputStream inputStream = httpExchange.getRequestBody();
ObjectEncoder objectEncoder = new ObjectEncoder();
loadRequest = (LoadRequest) objectEncoder.deserialize(inputStream, LoadRequest.class);
loadResult = loadService.load(loadRequest);
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, RESPONSE_LENGTH);
}
try {
// Serialize the Result Object
ObjectEncoder objectEncoder = new ObjectEncoder();
String json = objectEncoder.serialize(loadResult);
// Get response body from HTTP Exchange
OutputStream outputStream = httpExchange.getResponseBody();
// Create an OutputStreamWriter from the outputStream we get from httpExchange.getResponseBody()
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
// Write to response body with the serialized json we made using the OutputStreamWriter
outputStreamWriter.write(json);
// Flush the outputStreamWriter
outputStreamWriter.flush();
// Close the outputStream
outputStream.close();
// Close the Http Exchange.getResponseBody
httpExchange.getResponseBody().close();
} catch(IOException e) {
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, RESPONSE_LENGTH);
loadResult.setSuccess(false);
loadResult.setMessage("Internal Server Error");
loadResult.setDescription("Error: " + e.getMessage());
ObjectEncoder objectEncoder = new ObjectEncoder();
String json = objectEncoder.serialize(loadResult);
OutputStream outputStream = httpExchange.getResponseBody();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(json);
outputStreamWriter.flush();
outputStream.close();
httpExchange.getResponseBody().close();
}
}
/**
*
* @param exchange An HttpExchange object
* @return If the method in the request matches the method of the handler
*/
private boolean isValidHttpMethod(HttpExchange exchange) {
if(getHttpMethod(exchange).equals(HTTP_METHOD)) return true;
return false;
}
/**
* Gets the http method used (post, get, put, etc.)
* @param exchange An HttpExchange object
* @return All-caps String of the http method
*/
private String getHttpMethod(HttpExchange exchange) {
String httpMethod = exchange.getRequestMethod().toUpperCase();
return httpMethod;
}
}
| UTF-8 | Java | 4,043 | java | LoadHandler.java | Java | [] | null | [] | package handlers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import request.LoadRequest;
import result.LoadResult;
import service.LoadService;
import util.ObjectEncoder;
import java.io.*;
import java.net.HttpURLConnection;
public class LoadHandler implements HttpHandler {
// URL Path: /load
// HTTP Method: POST
// Auth Token Required: No
public final int RESPONSE_LENGTH = 0;
public final String HTTP_METHOD = "POST";
@Override
public void handle(HttpExchange httpExchange) throws IOException {
boolean errorFree = true;
// set the result and service
LoadService loadService = new LoadService();
LoadResult loadResult = new LoadResult();
LoadRequest loadRequest = null;
// validate the HTTP exchange
if(!isValidHttpMethod(httpExchange)) {
// Invalid HTTP Method
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, RESPONSE_LENGTH);
loadResult.setSuccess(false);
loadResult.setMessage("Http 400, Bad Request");
loadResult.setDescription("Invalid HTTP method. Method should be " + HTTP_METHOD);
errorFree = false;
}
// Valid Request. Send the HTTP OK
if(errorFree) {
InputStream inputStream = httpExchange.getRequestBody();
ObjectEncoder objectEncoder = new ObjectEncoder();
loadRequest = (LoadRequest) objectEncoder.deserialize(inputStream, LoadRequest.class);
loadResult = loadService.load(loadRequest);
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, RESPONSE_LENGTH);
}
try {
// Serialize the Result Object
ObjectEncoder objectEncoder = new ObjectEncoder();
String json = objectEncoder.serialize(loadResult);
// Get response body from HTTP Exchange
OutputStream outputStream = httpExchange.getResponseBody();
// Create an OutputStreamWriter from the outputStream we get from httpExchange.getResponseBody()
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
// Write to response body with the serialized json we made using the OutputStreamWriter
outputStreamWriter.write(json);
// Flush the outputStreamWriter
outputStreamWriter.flush();
// Close the outputStream
outputStream.close();
// Close the Http Exchange.getResponseBody
httpExchange.getResponseBody().close();
} catch(IOException e) {
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, RESPONSE_LENGTH);
loadResult.setSuccess(false);
loadResult.setMessage("Internal Server Error");
loadResult.setDescription("Error: " + e.getMessage());
ObjectEncoder objectEncoder = new ObjectEncoder();
String json = objectEncoder.serialize(loadResult);
OutputStream outputStream = httpExchange.getResponseBody();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(json);
outputStreamWriter.flush();
outputStream.close();
httpExchange.getResponseBody().close();
}
}
/**
*
* @param exchange An HttpExchange object
* @return If the method in the request matches the method of the handler
*/
private boolean isValidHttpMethod(HttpExchange exchange) {
if(getHttpMethod(exchange).equals(HTTP_METHOD)) return true;
return false;
}
/**
* Gets the http method used (post, get, put, etc.)
* @param exchange An HttpExchange object
* @return All-caps String of the http method
*/
private String getHttpMethod(HttpExchange exchange) {
String httpMethod = exchange.getRequestMethod().toUpperCase();
return httpMethod;
}
}
| 4,043 | 0.661885 | 0.660895 | 107 | 36.785046 | 28.674789 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53271 | false | false | 9 |
ed98470aad5135e27938a97a98affac1fe31becb | 21,835,613,784,733 | 7dab1631cb99e7b148694ce9053dc0dcd8936bde | /bofc/src/main/java/net/buchlese/bofc/jdbi/bofc/PosInvoiceMapper.java | a0546bd00b601ebc7a652128eee63573bebc7dec | [] | no_license | blaurockm/posa | https://github.com/blaurockm/posa | da9d5248735446c2aee6d4a0bfe71aed13c73eb5 | e7fab42d8fb049759c355c740e30b1dfa9c3b2c5 | refs/heads/master | 2021-01-23T17:30:33.706000 | 2019-01-05T09:43:24 | 2019-01-05T09:43:24 | 25,125,235 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.buchlese.bofc.jdbi.bofc;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jackson.Jackson;
import net.buchlese.bofc.api.bofc.PosInvoice;
public class PosInvoiceMapper implements ResultSetMapper<PosInvoice> {
public PosInvoice map(int arg0, ResultSet rs, StatementContext ctx) throws SQLException {
PosInvoice inv = new PosInvoice();
ObjectMapper om = Jackson.newObjectMapper();
try {
String x = rs.getString("complJson");
if (x != null && x.isEmpty() == false) {
inv = om.readValue(rs.getString("complJson"), PosInvoice.class);
}
} catch (IOException e) {
throw new SQLException(e);
}
inv.setId(rs.getLong("id"));
inv.setNumber(rs.getString("number"));
inv.setCustomerId(rs.getInt("customer"));
inv.setPointid(rs.getInt("pointid"));
inv.setDebitorId(rs.getInt("debitor"));
inv.setAmount(rs.getLong("amount"));
inv.setAmountFull(rs.getLong("amountFull"));
inv.setAmountHalf(rs.getLong("amountHalf"));
inv.setAmountNone(rs.getLong("amountNone"));
inv.setDate(rs.getDate("invDate"));
inv.setCreationTime(rs.getTimestamp("creationtime"));
inv.setPrintTime(rs.getTimestamp("printdate"));
inv.setName1(rs.getString("name1"));
inv.setName2(rs.getString("name2"));
inv.setName3(rs.getString("name3"));
inv.setStreet(rs.getString("street"));
inv.setCity(rs.getString("city"));
inv.setPayed(rs.getBoolean("payed"));
inv.setCancelled(rs.getBoolean("cancelled"));
inv.setActionum(rs.getInt("actionum"));
inv.setRebate(0d);
inv.setRebateAmount(0L);
return inv;
}
}
| UTF-8 | Java | 1,798 | java | PosInvoiceMapper.java | Java | [] | null | [] | package net.buchlese.bofc.jdbi.bofc;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jackson.Jackson;
import net.buchlese.bofc.api.bofc.PosInvoice;
public class PosInvoiceMapper implements ResultSetMapper<PosInvoice> {
public PosInvoice map(int arg0, ResultSet rs, StatementContext ctx) throws SQLException {
PosInvoice inv = new PosInvoice();
ObjectMapper om = Jackson.newObjectMapper();
try {
String x = rs.getString("complJson");
if (x != null && x.isEmpty() == false) {
inv = om.readValue(rs.getString("complJson"), PosInvoice.class);
}
} catch (IOException e) {
throw new SQLException(e);
}
inv.setId(rs.getLong("id"));
inv.setNumber(rs.getString("number"));
inv.setCustomerId(rs.getInt("customer"));
inv.setPointid(rs.getInt("pointid"));
inv.setDebitorId(rs.getInt("debitor"));
inv.setAmount(rs.getLong("amount"));
inv.setAmountFull(rs.getLong("amountFull"));
inv.setAmountHalf(rs.getLong("amountHalf"));
inv.setAmountNone(rs.getLong("amountNone"));
inv.setDate(rs.getDate("invDate"));
inv.setCreationTime(rs.getTimestamp("creationtime"));
inv.setPrintTime(rs.getTimestamp("printdate"));
inv.setName1(rs.getString("name1"));
inv.setName2(rs.getString("name2"));
inv.setName3(rs.getString("name3"));
inv.setStreet(rs.getString("street"));
inv.setCity(rs.getString("city"));
inv.setPayed(rs.getBoolean("payed"));
inv.setCancelled(rs.getBoolean("cancelled"));
inv.setActionum(rs.getInt("actionum"));
inv.setRebate(0d);
inv.setRebateAmount(0L);
return inv;
}
}
| 1,798 | 0.709677 | 0.70356 | 53 | 31.924528 | 20.211008 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.150943 | false | false | 9 |
6c700e8db2911cd36feefedd92e633b44567b6d4 | 23,974,507,498,674 | a229e98185273e78e3c544d6351b416871cd912f | /summerb-users/src/test/java/org/summerb/users/api/dto/PasswordFactory.java | a2555a0c9bddd3481c7b8d988437f5451f9607a4 | [
"Apache-2.0"
] | permissive | skarpushin/summerb | https://github.com/skarpushin/summerb | c1751986c79b8218edbff8c7ef5796ba15d63d45 | bc63a1c401e79518d7f48487780236763d6036df | refs/heads/master | 2023-06-06T23:21:04.282000 | 2023-06-02T19:08:42 | 2023-06-02T19:08:42 | 36,518,071 | 8 | 5 | Apache-2.0 | false | 2023-04-21T13:00:19 | 2015-05-29T17:10:39 | 2021-12-15T11:39:16 | 2023-04-21T12:54:49 | 2,739 | 7 | 2 | 9 | Java | false | false | /*******************************************************************************
* Copyright 2015-2023 Sergey Karpushin
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.summerb.users.api.dto;
import java.util.UUID;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.summerb.users.impl.dom.Password;
@SuppressWarnings("deprecation")
public class PasswordFactory {
public static PasswordEncoder passwordEncoder = new StandardPasswordEncoder("test");
public static final String RIGHT_PASSWORD_FOR_EXISTENT_USER = "passwordRight";
public static String RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH;
public static final String TOKEN_FOR_EXISTENT_USER = UUID.randomUUID().toString();
public static final String NOT_EXISTENT_RESTORATION_TOKEN = UUID.randomUUID().toString();
static {
RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH =
passwordEncoder.encode(RIGHT_PASSWORD_FOR_EXISTENT_USER);
}
private PasswordFactory() {}
public static Password createExistentUserPassword() {
Password ret = new Password();
ret.setUserUuid(UserFactory.EXISTENT_USER);
ret.setPasswordHash(RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH);
ret.setRestorationToken(TOKEN_FOR_EXISTENT_USER);
return ret;
}
}
| UTF-8 | Java | 1,920 | java | PasswordFactory.java | Java | [
{
"context": "***************************\n * Copyright 2015-2023 Sergey Karpushin\n *\n * Licensed under the Apache License, Version ",
"end": 120,
"score": 0.9998762011528015,
"start": 104,
"tag": "NAME",
"value": "Sergey Karpushin"
}
] | null | [] | /*******************************************************************************
* Copyright 2015-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package org.summerb.users.api.dto;
import java.util.UUID;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.summerb.users.impl.dom.Password;
@SuppressWarnings("deprecation")
public class PasswordFactory {
public static PasswordEncoder passwordEncoder = new StandardPasswordEncoder("test");
public static final String RIGHT_PASSWORD_FOR_EXISTENT_USER = "passwordRight";
public static String RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH;
public static final String TOKEN_FOR_EXISTENT_USER = UUID.randomUUID().toString();
public static final String NOT_EXISTENT_RESTORATION_TOKEN = UUID.randomUUID().toString();
static {
RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH =
passwordEncoder.encode(RIGHT_PASSWORD_FOR_EXISTENT_USER);
}
private PasswordFactory() {}
public static Password createExistentUserPassword() {
Password ret = new Password();
ret.setUserUuid(UserFactory.EXISTENT_USER);
ret.setPasswordHash(RIGHT_PASSWORD_FOR_EXISTENT_USER_HASH);
ret.setRestorationToken(TOKEN_FOR_EXISTENT_USER);
return ret;
}
}
| 1,910 | 0.703646 | 0.697396 | 46 | 40.739132 | 31.275379 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 9 |
d34d2a78601c5e63c64a9b0532874ba3db1887b6 | 28,604,482,199,589 | f7d42dd5fbb76ff64e2d443d04bbbcdf2f9f59f2 | /codes/rpc/local/src/main/java/com/example/Main.java | 7acb6017966c4948cd16df5001edbd1453160068 | [] | no_license | CodingWorker/rpc_study | https://github.com/CodingWorker/rpc_study | 8ad88e2628ba59bf358e93b21fbfde7bff650b79 | 1f28f5576937ba2c6e9138558c567a9c73918b05 | refs/heads/master | 2021-01-06T20:39:42.033000 | 2017-11-24T09:36:04 | 2017-11-24T09:36:04 | 99,538,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example;
import com.example.rpc.*;
import java.net.InetSocketAddress;
/**
* Created by daiya on 2017/8/7.
*/
public class Main {
public static void main(String[] args){
//调用代理
Hello helloProxy = RPCClient.getRemoteProxyObj(Hello.class, new InetSocketAddress("localhost", 8090));
System.out.println(helloProxy.getIP());
}
}
| UTF-8 | Java | 380 | java | Main.java | Java | [
{
"context": "ort java.net.InetSocketAddress;\n\n/**\n * Created by daiya on 2017/8/7.\n */\npublic class Main {\n public s",
"end": 108,
"score": 0.9996020793914795,
"start": 103,
"tag": "USERNAME",
"value": "daiya"
}
] | null | [] | package com.example;
import com.example.rpc.*;
import java.net.InetSocketAddress;
/**
* Created by daiya on 2017/8/7.
*/
public class Main {
public static void main(String[] args){
//调用代理
Hello helloProxy = RPCClient.getRemoteProxyObj(Hello.class, new InetSocketAddress("localhost", 8090));
System.out.println(helloProxy.getIP());
}
}
| 380 | 0.677419 | 0.650538 | 16 | 22.25 | 27.43515 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 9 |
3036261cf9d6f26d8d8b9114ff8adba71bb84be6 | 19,533,511,281,623 | 87ba506762ca2574436a6426acc55164f930e3a5 | /ForLoops.java | 31994216dc8b78c2df00fa156dd974bea8d94e04 | [] | no_license | WozJava-01182021/Core-Java | https://github.com/WozJava-01182021/Core-Java | e8c71ac290690c1761e48bee883a3223b08be652 | d50b3c8c910e51731aae831f8eb998de64f56028 | refs/heads/main | 2023-02-26T08:04:42.591000 | 2021-02-07T00:29:12 | 2021-02-07T00:29:12 | 331,381,072 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*
* The basic for loop:
* The declaration has three parts:
* 1. initialization sets up the loop control variable: int i = 0
* 2. conditional test determines when loop terminates: i < 4
* 3. iterator increments the loop control variable: i++
* A fourth part is the body of the for loop
*
* Enhanced for loop introduced in Java 5:
* Designed for ease of use with arrays and collections
* Two parts to setting up the enhanced for loop:
* 1. declaration - a block variable of the same type as the array element
* 2. expression - the array itself
*
* If you do not use curly braces, the loop body consists of just one statement
*
*/
package robertd.core_java.lesson05;
import robertd.core_java.common.animal.mammals.Lion;
public class ForLoops {
public void inClassWork() {
System.out.println(this.getClass().getSimpleName() + ".inClassWork()");
testBasicForLoop();
System.out.println("-------------------------------------------------------\n\n");
}
private void testBasicForLoop() {
System.out.println();
System.out.println("1. Basic old style for loop:");
for (int i = 0; i < 4; i++) {// loop body
System.out.print("i=" + i + ", ");
}
// i++;
System.out.println('\n');
// STUDENT EXERCISE: change i<4 to i>4: what happens
// Loop will only execute when the conditional express returns true
System.out.println("1a. The iteration expression can be anything");
System.out.println();
for (int j = 10; j > 4; j -= 2) {
System.out.print("j=" + j + ", ");
}
System.out.println('\n');
System.out.println("1b. The loop control variable can be anything");
System.out.println();
for (double j = 100; j > 4; j = j / 2) {
System.out.print("j=" + j + ", ");
}
System.out.println('\n');
System.out.println();
System.out.println("1c. Loop expressions can literally be anything");
for (Lion a = new Lion(); a.getAge() < 5; a.grow()) {
System.out.println(a);
a.move();
}
System.out.println('\n');
// a.move();
System.out.println("1d. All declaration parts are optional");
System.out.println();
int count = 0;
// This behaves just like while(count < 6)
for (; count < 6;) {
System.out.println("count = " + count++);
}
System.out.println();
System.out.println("1e. Declaring the loop control variable outside the loop");
System.out.println();
int k = 1;
for (; k <= 3;) {
System.out.println("Inside loop k=" + k++);
}
System.out.println("Outside loop k= " + k);
System.out.println();
System.out.println("1f. Multiple variables in loop expressions");
System.out.println();
for (long i = 1, j = 2; i <= 16 && j <= 10000; i++, j *= 2) {
System.out.println("2 to the " + i + " power = " + j);
}
System.out.println();
}
}
| UTF-8 | Java | 2,891 | java | ForLoops.java | Java | [] | null | [] | /*
*
* The basic for loop:
* The declaration has three parts:
* 1. initialization sets up the loop control variable: int i = 0
* 2. conditional test determines when loop terminates: i < 4
* 3. iterator increments the loop control variable: i++
* A fourth part is the body of the for loop
*
* Enhanced for loop introduced in Java 5:
* Designed for ease of use with arrays and collections
* Two parts to setting up the enhanced for loop:
* 1. declaration - a block variable of the same type as the array element
* 2. expression - the array itself
*
* If you do not use curly braces, the loop body consists of just one statement
*
*/
package robertd.core_java.lesson05;
import robertd.core_java.common.animal.mammals.Lion;
public class ForLoops {
public void inClassWork() {
System.out.println(this.getClass().getSimpleName() + ".inClassWork()");
testBasicForLoop();
System.out.println("-------------------------------------------------------\n\n");
}
private void testBasicForLoop() {
System.out.println();
System.out.println("1. Basic old style for loop:");
for (int i = 0; i < 4; i++) {// loop body
System.out.print("i=" + i + ", ");
}
// i++;
System.out.println('\n');
// STUDENT EXERCISE: change i<4 to i>4: what happens
// Loop will only execute when the conditional express returns true
System.out.println("1a. The iteration expression can be anything");
System.out.println();
for (int j = 10; j > 4; j -= 2) {
System.out.print("j=" + j + ", ");
}
System.out.println('\n');
System.out.println("1b. The loop control variable can be anything");
System.out.println();
for (double j = 100; j > 4; j = j / 2) {
System.out.print("j=" + j + ", ");
}
System.out.println('\n');
System.out.println();
System.out.println("1c. Loop expressions can literally be anything");
for (Lion a = new Lion(); a.getAge() < 5; a.grow()) {
System.out.println(a);
a.move();
}
System.out.println('\n');
// a.move();
System.out.println("1d. All declaration parts are optional");
System.out.println();
int count = 0;
// This behaves just like while(count < 6)
for (; count < 6;) {
System.out.println("count = " + count++);
}
System.out.println();
System.out.println("1e. Declaring the loop control variable outside the loop");
System.out.println();
int k = 1;
for (; k <= 3;) {
System.out.println("Inside loop k=" + k++);
}
System.out.println("Outside loop k= " + k);
System.out.println();
System.out.println("1f. Multiple variables in loop expressions");
System.out.println();
for (long i = 1, j = 2; i <= 16 && j <= 10000; i++, j *= 2) {
System.out.println("2 to the " + i + " power = " + j);
}
System.out.println();
}
}
| 2,891 | 0.595296 | 0.579038 | 97 | 27.804123 | 25.324955 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.845361 | false | false | 9 |
20bf9b213739ec951832449992725846b8209f5f | 3,307,124,870,754 | a036052e1b1deb000d9889d1741baaa62967fd2b | /app/src/main/java/com/example/getmygif/models/GifResponse.java | 04931e8c39a30c966b801a365f87fdc4e8998648 | [] | no_license | Ivan7771998/GetMyGif | https://github.com/Ivan7771998/GetMyGif | a2821e2b56481260c7d8d1878a799a07b9f07b6d | 92d5a691e8a6b07a1fe9acdb51083d88f73095d5 | refs/heads/master | 2021-04-11T11:23:40.676000 | 2020-03-21T16:28:27 | 2020-03-21T16:28:27 | 249,015,556 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.getmygif.models;
import java.util.List;
public class GifResponse {
private List<GigDTO> data;
public List<GigDTO> getData() {
return data;
}
}
| UTF-8 | Java | 187 | java | GifResponse.java | Java | [] | null | [] | package com.example.getmygif.models;
import java.util.List;
public class GifResponse {
private List<GigDTO> data;
public List<GigDTO> getData() {
return data;
}
}
| 187 | 0.668449 | 0.668449 | 12 | 14.583333 | 14.30302 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
e5bacade371653da8d114b7d80a1c8e0d962c6e7 | 22,041,772,176,895 | b288a75873c201eb1fb5c0484dd444c1a7212534 | /tifoon-plugin-api/src/main/java/com/elixlogic/tifoon/domain/model/scanner/Port.java | 14398452dbc33a31332ee84693e1078590240cdb | [
"MIT"
] | permissive | jonfryd/tifoon | https://github.com/jonfryd/tifoon | efd9f1708821c86e17e6a43e388dca6d43c9b0cf | 9cc2bc1db4fe0f3c25496ebb53749559ec02e51f | refs/heads/master | 2020-05-24T11:11:27.825000 | 2017-06-07T05:48:59 | 2017-06-07T05:48:59 | 84,850,667 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.elixlogic.tifoon.domain.model.scanner;
import com.elixlogic.tifoon.domain.model.object.ReflectionObjectTreeAware;
import lombok.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.Comparator;
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Port extends ReflectionObjectTreeAware implements Serializable {
public static Comparator<Port> BY_PROTOCOL_THEN_PORT_NUMBER = Comparator.comparing(Port::getProtocol)
.thenComparing(Comparator.comparing(Port::getPortNumber));
private Protocol protocol;
private int portNumber;
// don't use auto-generation here, enforce use of setters
public static Port from(@NonNull final Protocol _protocol, final int _portNumber) {
final Port port = new Port();
port.setProtocol(_protocol);
port.setPortNumber(_portNumber);
return port;
}
public void setPortNumber(final int _portNumber) {
Assert.isTrue(_portNumber >= 0 && _portNumber <= 65535, String.format("port number %d not within 0-65535 range", _portNumber));
this.portNumber = _portNumber;
}
@Override
public boolean equals(final Object _o) {
if (this == _o) {
return true;
}
if (_o == null || getClass() != _o.getClass()) {
return false;
}
final Port port = (Port) _o;
return new EqualsBuilder()
.append(portNumber, port.portNumber)
.append(protocol, port.protocol)
.isEquals();
}
@Override
public int hashCode() {
return portNumber + protocol.ordinal() * 100000;
}
}
| UTF-8 | Java | 1,735 | java | Port.java | Java | [] | null | [] | package com.elixlogic.tifoon.domain.model.scanner;
import com.elixlogic.tifoon.domain.model.object.ReflectionObjectTreeAware;
import lombok.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.Comparator;
@Data
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Port extends ReflectionObjectTreeAware implements Serializable {
public static Comparator<Port> BY_PROTOCOL_THEN_PORT_NUMBER = Comparator.comparing(Port::getProtocol)
.thenComparing(Comparator.comparing(Port::getPortNumber));
private Protocol protocol;
private int portNumber;
// don't use auto-generation here, enforce use of setters
public static Port from(@NonNull final Protocol _protocol, final int _portNumber) {
final Port port = new Port();
port.setProtocol(_protocol);
port.setPortNumber(_portNumber);
return port;
}
public void setPortNumber(final int _portNumber) {
Assert.isTrue(_portNumber >= 0 && _portNumber <= 65535, String.format("port number %d not within 0-65535 range", _portNumber));
this.portNumber = _portNumber;
}
@Override
public boolean equals(final Object _o) {
if (this == _o) {
return true;
}
if (_o == null || getClass() != _o.getClass()) {
return false;
}
final Port port = (Port) _o;
return new EqualsBuilder()
.append(portNumber, port.portNumber)
.append(protocol, port.protocol)
.isEquals();
}
@Override
public int hashCode() {
return portNumber + protocol.ordinal() * 100000;
}
}
| 1,735 | 0.65879 | 0.647839 | 56 | 29.982143 | 29.233355 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.517857 | false | false | 9 |
dda5bb404bcd494b67367781e5aafe71c10e41fe | 5,806,795,792,409 | bbc1b6e349ecafddc2d7cc76c6b6f5fc06ba237b | /com.io7m.jaffirm.tests/src/test/java/com/io7m/jaffirm/tests/core/ContractsTest.java | b268bc022c072b252b3069fdc000053b46d6cadf | [
"ISC"
] | permissive | io7m/jaffirm | https://github.com/io7m/jaffirm | 9e14c510d8c2884fd3b75adfb882ff507e40a4d0 | f1826b239332e229fb0af9bcf589c822ffc66d4c | refs/heads/master | 2023-09-01T11:23:54.504000 | 2022-04-09T12:45:11 | 2022-04-09T12:45:11 | 65,097,563 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright © 2016 Mark Raynsford <code@io7m.com> https://www.io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jaffirm.tests.core;
import com.io7m.jaffirm.core.ContractCondition;
import com.io7m.jaffirm.core.ContractDoubleCondition;
import com.io7m.jaffirm.core.ContractIntCondition;
import com.io7m.jaffirm.core.ContractLongCondition;
import com.io7m.jaffirm.core.Contracts;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.function.DoubleFunction;
import java.util.function.DoublePredicate;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
public final class ContractsTest
{
@Test
public void testContractUnreachable()
throws Exception
{
final Constructor<Contracts> c = Contracts.class.getDeclaredConstructor();
c.setAccessible(true);
Assertions.assertThrows(InvocationTargetException.class, c::newInstance);
}
@Test
public void testContractCondition()
{
final Predicate<Object> predicate = x -> true;
final Function<Object, String> describer = x -> "x";
Assertions.assertEquals(
ContractCondition.of(predicate, describer),
Contracts.condition(predicate, describer));
}
@Test
public void testContractConditionInt()
{
final IntPredicate predicate = x -> true;
final IntFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractIntCondition.of(predicate, describer),
Contracts.conditionI(predicate, describer));
}
@Test
public void testContractConditionLong()
{
final LongPredicate predicate = x -> true;
final LongFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractLongCondition.of(predicate, describer),
Contracts.conditionL(predicate, describer));
}
@Test
public void testContractConditionDouble()
{
final DoublePredicate predicate = x -> true;
final DoubleFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractDoubleCondition.of(predicate, describer),
Contracts.conditionD(predicate, describer));
}
}
| UTF-8 | Java | 3,060 | java | ContractsTest.java | Java | [
{
"context": "/*\n * Copyright © 2016 Mark Raynsford <code@io7m.com> https://www.io7m.com\n *\n * Permis",
"end": 37,
"score": 0.9997994303703308,
"start": 23,
"tag": "NAME",
"value": "Mark Raynsford"
},
{
"context": "/*\n * Copyright © 2016 Mark Raynsford <code@io7m.com> https://www.io7m.com\n *\n * Permission to use, co",
"end": 52,
"score": 0.9999261498451233,
"start": 39,
"tag": "EMAIL",
"value": "code@io7m.com"
}
] | null | [] | /*
* Copyright © 2016 <NAME> <<EMAIL>> https://www.io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jaffirm.tests.core;
import com.io7m.jaffirm.core.ContractCondition;
import com.io7m.jaffirm.core.ContractDoubleCondition;
import com.io7m.jaffirm.core.ContractIntCondition;
import com.io7m.jaffirm.core.ContractLongCondition;
import com.io7m.jaffirm.core.Contracts;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.function.DoubleFunction;
import java.util.function.DoublePredicate;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
public final class ContractsTest
{
@Test
public void testContractUnreachable()
throws Exception
{
final Constructor<Contracts> c = Contracts.class.getDeclaredConstructor();
c.setAccessible(true);
Assertions.assertThrows(InvocationTargetException.class, c::newInstance);
}
@Test
public void testContractCondition()
{
final Predicate<Object> predicate = x -> true;
final Function<Object, String> describer = x -> "x";
Assertions.assertEquals(
ContractCondition.of(predicate, describer),
Contracts.condition(predicate, describer));
}
@Test
public void testContractConditionInt()
{
final IntPredicate predicate = x -> true;
final IntFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractIntCondition.of(predicate, describer),
Contracts.conditionI(predicate, describer));
}
@Test
public void testContractConditionLong()
{
final LongPredicate predicate = x -> true;
final LongFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractLongCondition.of(predicate, describer),
Contracts.conditionL(predicate, describer));
}
@Test
public void testContractConditionDouble()
{
final DoublePredicate predicate = x -> true;
final DoubleFunction<String> describer = x -> "x";
Assertions.assertEquals(
ContractDoubleCondition.of(predicate, describer),
Contracts.conditionD(predicate, describer));
}
}
| 3,046 | 0.756456 | 0.752533 | 93 | 31.892473 | 25.489809 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623656 | false | false | 9 |
7b98573be2080bca458aa136a6468b73c237fbe9 | 14,602,888,814,502 | c7c5d731a32e8bd7baf008ee28a62e4d0f396f96 | /src/utils/ExeStack.java | ad9f5b7a9080373f679d636e8c3f343195f739f1 | [] | no_license | mihaitopan/Interpreter | https://github.com/mihaitopan/Interpreter | 02fdb38fe30780b6a696c6f0a6e86a6b2d22552e | 4a7c3bbf431883cdf0076bdca9ab76c9f81429f7 | refs/heads/master | 2020-05-23T02:11:27.809000 | 2017-03-12T17:46:36 | 2017-03-12T17:46:36 | 84,741,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
import java.util.*;
public class ExeStack<E> implements IExeStack<E>, java.io.Serializable {
private Deque<E> deque;
private Stack<E> stack;
public ExeStack() {
this.deque = new ArrayDeque<E>();
this.stack = new Stack<E>();
}
@Override
public void push(E elem) {
this.stack.push(elem);
}
@Override
public E top() {
return this.stack.peek();
}
@Override
public E pop() {
return this.stack.pop();
}
@Override
public boolean isEmpty() {
return this.stack.empty();
}
@Override
public Iterable<E> getAll() {
return this.stack;
}
@Override
public String toString() {
return "ExeStack\n\t" + stack.toString() + "\n";
}
}
| UTF-8 | Java | 725 | java | ExeStack.java | Java | [] | null | [] | package utils;
import java.util.*;
public class ExeStack<E> implements IExeStack<E>, java.io.Serializable {
private Deque<E> deque;
private Stack<E> stack;
public ExeStack() {
this.deque = new ArrayDeque<E>();
this.stack = new Stack<E>();
}
@Override
public void push(E elem) {
this.stack.push(elem);
}
@Override
public E top() {
return this.stack.peek();
}
@Override
public E pop() {
return this.stack.pop();
}
@Override
public boolean isEmpty() {
return this.stack.empty();
}
@Override
public Iterable<E> getAll() {
return this.stack;
}
@Override
public String toString() {
return "ExeStack\n\t" + stack.toString() + "\n";
}
}
| 725 | 0.609655 | 0.609655 | 42 | 16.261906 | 15.131267 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.97619 | false | false | 9 |
fcc26fc04892c275f852572be2ef1eadf9d59fab | 6,141,803,238,199 | 4ba9821b3679b36e1182fadfb0a212eb8bbfdac4 | /momoscoffee/src/com/jimmyzip/momos/model/domain/admin/BankAcc.java | 09efd7f2d0a76f26a480c5aeb054e0e7fe0e55b5 | [] | no_license | jimmyZip/momos | https://github.com/jimmyZip/momos | 38a1ac31342b1523ce81d3c7380cc0dbd53e9f73 | f6cff782a1bc9a759974a518fb3f0993c124180e | refs/heads/master | 2022-12-22T17:01:26.070000 | 2019-09-10T07:57:10 | 2019-09-10T07:57:10 | 202,797,927 | 1 | 0 | null | false | 2022-12-16T09:58:01 | 2019-08-16T20:54:56 | 2019-09-10T07:57:12 | 2022-12-16T09:57:57 | 96,697 | 1 | 0 | 5 | Java | false | false | package com.jimmyzip.momos.model.domain.admin;
public class BankAcc {//무통장 입금 받을 계좌 관리
private int bank_acc_id;
private String bank_name;
private String acc_num;
//getter and setter
public int getBank_acc_id() {
return bank_acc_id;
}
public void setBank_acc_id(int bank_acc_id) {
this.bank_acc_id = bank_acc_id;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public String getAcc_num() {
return acc_num;
}
public void setAcc_num(String acc_num) {
this.acc_num = acc_num;
}
}
| UTF-8 | Java | 609 | java | BankAcc.java | Java | [] | null | [] | package com.jimmyzip.momos.model.domain.admin;
public class BankAcc {//무통장 입금 받을 계좌 관리
private int bank_acc_id;
private String bank_name;
private String acc_num;
//getter and setter
public int getBank_acc_id() {
return bank_acc_id;
}
public void setBank_acc_id(int bank_acc_id) {
this.bank_acc_id = bank_acc_id;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public String getAcc_num() {
return acc_num;
}
public void setAcc_num(String acc_num) {
this.acc_num = acc_num;
}
}
| 609 | 0.691652 | 0.691652 | 27 | 20.74074 | 15.510075 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 9 |
054450bb0c7b212944ebbc27354c984a122d5a1f | 3,831,110,832,826 | d45b6ce686702e3a1481eeb6eaf937cd4b0abff5 | /SchoolMgmtW1_d3/src/pojoclass/Student.java | 744312e4361a6ace23a74995187fd75dc8558770 | [] | no_license | mrphuyal/SchoolMgmt7Apr | https://github.com/mrphuyal/SchoolMgmt7Apr | 185717da43708164a4eaec634dd8a6b237c9e456 | 8db44c080b3e20c9664262b5ce495eb17292d4b3 | refs/heads/master | 2021-05-25T08:04:22.546000 | 2020-04-08T16:49:27 | 2020-04-08T16:49:27 | 253,731,125 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pojoclass;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student {
private List<StudentPojo> allStudents = new ArrayList<StudentPojo>();
private int studentId;
Scanner in = new Scanner(System.in);
String studentLocation = "C:\\Users\\Sudip\\Desktop\\JavaClass\\data\\student.csv";
public Student() {
readFromFile(studentLocation);
}
public void addStudent(StudentPojo studentpojo) throws Exception {
this.allStudents.add(studentpojo);
writeToFile(allStudents);
}
public void updateStudents(List<StudentPojo> updatedstudents) throws Exception {
writeToFile(updatedstudents);
this.allStudents = updatedstudents;
}
public List<StudentPojo> getAll() {
return this.allStudents;
}
public int getId() {
for (int i = 0; i < this.allStudents.size(); i++) {
int x = Integer.valueOf(this.allStudents.get(i).getId());
if (x >= studentId) {
studentId = x + 1;
}
}
return studentId;
}
public void writeToFile(List<StudentPojo> updatedstudents) throws Exception {
BufferedWriter bw = new BufferedWriter(new FileWriter(studentLocation));
for (int i = 0; i < updatedstudents.size(); i++) {
String valueToWrite = updatedstudents.get(i).getId() + "," + updatedstudents.get(i).getfName() + ","
+ updatedstudents.get(i).getlName() + "," + updatedstudents.get(i).getPhNumber();
bw.write(valueToWrite);
bw.newLine();
}
bw.flush();
bw.close();
}
public void readFromFile(String StudentLocation) {
try {
BufferedReader br = new BufferedReader(new FileReader(studentLocation));
String line;
while ((line = br.readLine()) != null) {
StudentPojo studentpojo= new StudentPojo();
String[] arr = line.split(",");
studentpojo.setId(arr[0]);
studentpojo.setfName(arr[1]);
studentpojo.setlName(arr[2]);
studentpojo.setPhNumber(arr[3]);
this.allStudents.add(studentpojo);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,121 | java | Student.java | Java | [
{
"context": "System.in);\n\tString studentLocation = \"C:\\\\Users\\\\Sudip\\\\Desktop\\\\JavaClass\\\\data\\\\student.csv\";\n\n\tpublic",
"end": 414,
"score": 0.6826381683349609,
"start": 409,
"tag": "NAME",
"value": "Sudip"
}
] | null | [] | package pojoclass;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Student {
private List<StudentPojo> allStudents = new ArrayList<StudentPojo>();
private int studentId;
Scanner in = new Scanner(System.in);
String studentLocation = "C:\\Users\\Sudip\\Desktop\\JavaClass\\data\\student.csv";
public Student() {
readFromFile(studentLocation);
}
public void addStudent(StudentPojo studentpojo) throws Exception {
this.allStudents.add(studentpojo);
writeToFile(allStudents);
}
public void updateStudents(List<StudentPojo> updatedstudents) throws Exception {
writeToFile(updatedstudents);
this.allStudents = updatedstudents;
}
public List<StudentPojo> getAll() {
return this.allStudents;
}
public int getId() {
for (int i = 0; i < this.allStudents.size(); i++) {
int x = Integer.valueOf(this.allStudents.get(i).getId());
if (x >= studentId) {
studentId = x + 1;
}
}
return studentId;
}
public void writeToFile(List<StudentPojo> updatedstudents) throws Exception {
BufferedWriter bw = new BufferedWriter(new FileWriter(studentLocation));
for (int i = 0; i < updatedstudents.size(); i++) {
String valueToWrite = updatedstudents.get(i).getId() + "," + updatedstudents.get(i).getfName() + ","
+ updatedstudents.get(i).getlName() + "," + updatedstudents.get(i).getPhNumber();
bw.write(valueToWrite);
bw.newLine();
}
bw.flush();
bw.close();
}
public void readFromFile(String StudentLocation) {
try {
BufferedReader br = new BufferedReader(new FileReader(studentLocation));
String line;
while ((line = br.readLine()) != null) {
StudentPojo studentpojo= new StudentPojo();
String[] arr = line.split(",");
studentpojo.setId(arr[0]);
studentpojo.setfName(arr[1]);
studentpojo.setlName(arr[2]);
studentpojo.setPhNumber(arr[3]);
this.allStudents.add(studentpojo);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 2,121 | 0.69637 | 0.693069 | 79 | 25.848101 | 24.941496 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.329114 | false | false | 9 |
59f0bfb33490ad5d51a28de9814ae10c55a09f07 | 3,186,865,782,867 | abfa0958ee5f4b9dcf67ec822096403695b55783 | /parkinfo-dao/src/main/java/com/parkinfo/repository/parkCulture/AnswerSheetRepository.java | fb47dcf29eb8da1160f3f06d0824933fc346c36d | [
"Apache-2.0"
] | permissive | zhang-hwl/parkinfo | https://github.com/zhang-hwl/parkinfo | 582763845b158add41e36391aa4dc6b462a29f9a | dae51fedbbb2972e04494de49eb785c328a992bd | refs/heads/master | 2023-03-09T09:24:28.089000 | 2020-01-05T05:20:41 | 2020-01-05T05:20:41 | 231,868,396 | 0 | 0 | Apache-2.0 | false | 2023-02-22T08:19:24 | 2020-01-05T04:44:27 | 2020-01-05T05:20:43 | 2023-02-22T08:19:22 | 1,152 | 0 | 0 | 5 | Java | false | false | package com.parkinfo.repository.parkCulture;
import com.parkinfo.entity.parkCulture.AnswerSheet;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AnswerSheetRepository extends JpaRepository<AnswerSheet,String> {
Page<AnswerSheet> findAll(Specification<AnswerSheet> answerSheetSpecification, Pageable pageable);
}
| UTF-8 | Java | 501 | java | AnswerSheetRepository.java | Java | [] | null | [] | package com.parkinfo.repository.parkCulture;
import com.parkinfo.entity.parkCulture.AnswerSheet;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AnswerSheetRepository extends JpaRepository<AnswerSheet,String> {
Page<AnswerSheet> findAll(Specification<AnswerSheet> answerSheetSpecification, Pageable pageable);
}
| 501 | 0.852295 | 0.852295 | 11 | 44.545456 | 31.692739 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.818182 | false | false | 9 |
315fcbca8a26ecbda8f1292d061c5601f2331f10 | 11,905,649,345,904 | e73767dd207a632b98d6ee6ba44bf8714ec42bf5 | /src/main/java/com/dao/assignmentMapper.java | 37bebb01a60b45f6a9ab96ef81e33fda473b2cfe | [] | no_license | Phillss/project | https://github.com/Phillss/project | e7a8e1e275c172160136a20b8a32f9177bc5fd73 | 07bcd2397b03987fe65cdddb6782757f9c9ffea5 | refs/heads/master | 2022-12-20T10:25:04.225000 | 2020-06-10T13:36:46 | 2020-06-10T13:36:46 | 252,154,846 | 0 | 0 | null | false | 2022-12-15T23:33:16 | 2020-04-01T11:25:07 | 2020-06-10T13:42:46 | 2022-12-15T23:33:16 | 1,973 | 0 | 0 | 10 | JavaScript | false | false | package com.dao;
import com.Domains.Assignment;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface assignmentMapper {
Assignment selectAssignById(int index);
List<Assignment> selectAssignFromPb(String index);
}
| UTF-8 | Java | 275 | java | assignmentMapper.java | Java | [] | null | [] | package com.dao;
import com.Domains.Assignment;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface assignmentMapper {
Assignment selectAssignById(int index);
List<Assignment> selectAssignFromPb(String index);
}
| 275 | 0.796364 | 0.796364 | 14 | 18.642857 | 19.43343 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
a931281d98d942cc35b216e1f4436f5504c49fd3 | 27,178,553,052,311 | b462da7c390a352fd10291ed040f2ac765f28487 | /Project/src/class3/com/admin/IWarningDAO.java | e206cb930aae1c93d870099d4cbad10cd230ce8c | [] | no_license | Kim-Jin-ho/sistproject | https://github.com/Kim-Jin-ho/sistproject | cb3bd612dac6cfbb29bd9ef57cca90bd4fdc0a4f | 462f90923e41e746f15cf2e4efe8f6c7f722536c | refs/heads/master | 2020-03-20T04:54:16.537000 | 2017-07-17T07:23:49 | 2017-07-17T07:23:49 | 75,152,139 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package class3.com.admin;
import java.sql.SQLException;
public interface IWarningDAO
{
public int add1(Warning warning) throws SQLException;
public int add2(Warning warning) throws SQLException;
public int add3(Warning warning) throws SQLException;
public int remove1(String cmpny_id) throws SQLException;
public int remove2(String cmpny_id) throws SQLException;
public int remove3(String cmpny_id) throws SQLException;
public int add4(Warning warning) throws SQLException;
public int add5(Warning warning) throws SQLException;
public int add6(Warning warning) throws SQLException;
public int remove4(String cmpny_id) throws SQLException;
public int remove5(String cmpny_id) throws SQLException;
public int remove6(String cmpny_id) throws SQLException;
}
| UTF-8 | Java | 777 | java | IWarningDAO.java | Java | [] | null | [] | package class3.com.admin;
import java.sql.SQLException;
public interface IWarningDAO
{
public int add1(Warning warning) throws SQLException;
public int add2(Warning warning) throws SQLException;
public int add3(Warning warning) throws SQLException;
public int remove1(String cmpny_id) throws SQLException;
public int remove2(String cmpny_id) throws SQLException;
public int remove3(String cmpny_id) throws SQLException;
public int add4(Warning warning) throws SQLException;
public int add5(Warning warning) throws SQLException;
public int add6(Warning warning) throws SQLException;
public int remove4(String cmpny_id) throws SQLException;
public int remove5(String cmpny_id) throws SQLException;
public int remove6(String cmpny_id) throws SQLException;
}
| 777 | 0.803089 | 0.786358 | 23 | 32.782608 | 25.132616 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.304348 | false | false | 9 |
2daf2e1da77ee0a94b9f192ea39b327feccd8cea | 27,178,553,049,953 | 05e57060f8faffb7097ff9d814afb91ff4148b56 | /yundian.toolkit/src/main/java/com/yundian/toolkit/utils/PropFieldItem.java | f82bebc77263b3f32ba9383a515d01a1e922cd3a | [] | no_license | moutainhigh/insurance-1 | https://github.com/moutainhigh/insurance-1 | befad4dc18f2e81230a00a03053ee9207b44f6c2 | e2fdf17279b709ac2ebb2355bc3e2385914a61a6 | refs/heads/master | 2021-09-20T23:50:13.778000 | 2018-08-17T04:38:01 | 2018-08-17T04:38:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yundian.toolkit.utils;
public class PropFieldItem {
public Object value;
public PropFieldItem(Object _value){
this.value = _value;
}
} | UTF-8 | Java | 189 | java | PropFieldItem.java | Java | [] | null | [] | package com.yundian.toolkit.utils;
public class PropFieldItem {
public Object value;
public PropFieldItem(Object _value){
this.value = _value;
}
} | 189 | 0.603175 | 0.603175 | 10 | 18 | 15.968719 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
b007aa526171b16a1bd298c1b04fae5bb0231678 | 11,227,044,553,637 | 2143aad0c3d39be0b240591d62f0af377eca144e | /app/src/main/java/com/clorderclientapp/httpClient/VolleyRequest.java | 22aa395efe7ce7733ff29a761aeef3f0d85c3895 | [] | no_license | udaykumar857/android_clorder_client_app | https://github.com/udaykumar857/android_clorder_client_app | aa24b76a272b41b9b540debfe6be7dcc06a81f64 | 29146744e12d392f1149975c07223fd5f1b0a798 | refs/heads/master | 2020-12-02T06:15:01.611000 | 2019-12-30T13:27:51 | 2019-12-30T13:27:51 | 230,919,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.clorderclientapp.httpClient;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
public class VolleyRequest extends Request {
private final String TAG = "VolleyRequest";
protected static final String PROTOCOL_CHARSET = "utf-8";
private static final String PROTOCOL_CONTENT_TYPE =
String.format("application/json; charset=%s", PROTOCOL_CHARSET);
private String mRequestBody;
private static Response.ErrorListener errorListener;
private onSuccess responseListener;
private onFailure failureListener;
private int successCode = 0, failureCode = -1;
private Map<String, String> requestHeaders;
static {
errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
};
}
/**
* Callback Interface for delivering success responses
* <p class="note"><strong>Note:</strong> See {@link #onResponse(int, Object)} for more info</p>
**/
public interface onSuccess {
/**
* Callback method fired after successful request
*
* @param statusCode The status code received on request completion
* @param response The body of the HTTP response from the server
*/
void onResponse(int statusCode, Object response);
}
/**
* Callback Interface for delivering error responses
* <p class="note"><strong>Note:</strong> See {@link #onError(int, Object)} for more info</p>
**/
public interface onFailure {
/**
* Callback method fired when a request fails to complete
*
* @param statusCode The status code received on request completion
* @param errorResponse A description on underlying cause for the request failure
*/
void onError(int statusCode, Object errorResponse);
}
public VolleyRequest(int method,
String url,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
}
/**
* Creates a new VolleyRequest Object for GET Requests
*
* @param url The url of the request to be made
* @param responseListener Listener for handling success responses {@link onSuccess}
* @param failureListener Listener for handling error responses {@link onFailure}
* @see #VolleyRequest(int, String, JSONObject, onSuccess, onFailure)
*/
public VolleyRequest(String url,
onSuccess responseListener,
onFailure failureListener) {
this(Method.GET, url, errorListener);
this.responseListener = responseListener;
this.failureListener = failureListener;
}
/**
* Creates a new VolleyRequest Object for GET/POST Requests
*
* @param method Any one of the values from {@link com.android.volley.Request.Method}
* @param url The url of the request to be made
* @param requestBody Raw data to be sent along with the request.
* Can be null if no data needs to be sent
* @param responseListener Listener for handling success responses {@link onSuccess}
* @param failureListener Listener for handling error responses {@link onFailure}
*/
public VolleyRequest(int method,
String url,
JSONObject requestBody,
onSuccess responseListener,
onFailure failureListener) {
this(method, url, errorListener);
mRequestBody = requestBody.toString();
this.responseListener = responseListener;
this.failureListener = failureListener;
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
Log.d(TAG, "ParseNetworkResponse" + "\t" + response.statusCode);
successCode = response.statusCode;
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(json,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (this.requestHeaders != null && this.requestHeaders.size() > 0) {
return this.requestHeaders;
}
return new HashMap<>();
}
public void setRequestHeaders(Map<String, String> requestHeaders) {
this.requestHeaders = requestHeaders;
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
@Override
protected void deliverResponse(Object response) {
Log.d(TAG, " Response" + "\t" + response);
this.responseListener.onResponse(successCode, response);
}
@Override
public void deliverError(VolleyError error) {
Log.d(TAG, " Failure" + "\t" + error);
failureCode = parseVolleyError(error);
this.failureListener.onError(failureCode, error);
}
@Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
@Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}
private int parseVolleyError(final VolleyError error) {
int statusCode = -1;
if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError) {
statusCode = HttpURLConnection.HTTP_CLIENT_TIMEOUT;
} else if (error instanceof AuthFailureError) {
statusCode = HttpURLConnection.HTTP_UNAUTHORIZED;
} else if (error instanceof ServerError) {
statusCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
} else if (error instanceof ParseError) {
statusCode = HttpURLConnection.HTTP_BAD_REQUEST;
}
return statusCode;
}
} | UTF-8 | Java | 7,072 | java | VolleyRequest.java | Java | [] | null | [] | package com.clorderclientapp.httpClient;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
public class VolleyRequest extends Request {
private final String TAG = "VolleyRequest";
protected static final String PROTOCOL_CHARSET = "utf-8";
private static final String PROTOCOL_CONTENT_TYPE =
String.format("application/json; charset=%s", PROTOCOL_CHARSET);
private String mRequestBody;
private static Response.ErrorListener errorListener;
private onSuccess responseListener;
private onFailure failureListener;
private int successCode = 0, failureCode = -1;
private Map<String, String> requestHeaders;
static {
errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
};
}
/**
* Callback Interface for delivering success responses
* <p class="note"><strong>Note:</strong> See {@link #onResponse(int, Object)} for more info</p>
**/
public interface onSuccess {
/**
* Callback method fired after successful request
*
* @param statusCode The status code received on request completion
* @param response The body of the HTTP response from the server
*/
void onResponse(int statusCode, Object response);
}
/**
* Callback Interface for delivering error responses
* <p class="note"><strong>Note:</strong> See {@link #onError(int, Object)} for more info</p>
**/
public interface onFailure {
/**
* Callback method fired when a request fails to complete
*
* @param statusCode The status code received on request completion
* @param errorResponse A description on underlying cause for the request failure
*/
void onError(int statusCode, Object errorResponse);
}
public VolleyRequest(int method,
String url,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
}
/**
* Creates a new VolleyRequest Object for GET Requests
*
* @param url The url of the request to be made
* @param responseListener Listener for handling success responses {@link onSuccess}
* @param failureListener Listener for handling error responses {@link onFailure}
* @see #VolleyRequest(int, String, JSONObject, onSuccess, onFailure)
*/
public VolleyRequest(String url,
onSuccess responseListener,
onFailure failureListener) {
this(Method.GET, url, errorListener);
this.responseListener = responseListener;
this.failureListener = failureListener;
}
/**
* Creates a new VolleyRequest Object for GET/POST Requests
*
* @param method Any one of the values from {@link com.android.volley.Request.Method}
* @param url The url of the request to be made
* @param requestBody Raw data to be sent along with the request.
* Can be null if no data needs to be sent
* @param responseListener Listener for handling success responses {@link onSuccess}
* @param failureListener Listener for handling error responses {@link onFailure}
*/
public VolleyRequest(int method,
String url,
JSONObject requestBody,
onSuccess responseListener,
onFailure failureListener) {
this(method, url, errorListener);
mRequestBody = requestBody.toString();
this.responseListener = responseListener;
this.failureListener = failureListener;
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
Log.d(TAG, "ParseNetworkResponse" + "\t" + response.statusCode);
successCode = response.statusCode;
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(json,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
if (this.requestHeaders != null && this.requestHeaders.size() > 0) {
return this.requestHeaders;
}
return new HashMap<>();
}
public void setRequestHeaders(Map<String, String> requestHeaders) {
this.requestHeaders = requestHeaders;
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
@Override
protected void deliverResponse(Object response) {
Log.d(TAG, " Response" + "\t" + response);
this.responseListener.onResponse(successCode, response);
}
@Override
public void deliverError(VolleyError error) {
Log.d(TAG, " Failure" + "\t" + error);
failureCode = parseVolleyError(error);
this.failureListener.onError(failureCode, error);
}
@Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
@Override
public byte[] getBody() {
try {
return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, PROTOCOL_CHARSET);
return null;
}
}
private int parseVolleyError(final VolleyError error) {
int statusCode = -1;
if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError) {
statusCode = HttpURLConnection.HTTP_CLIENT_TIMEOUT;
} else if (error instanceof AuthFailureError) {
statusCode = HttpURLConnection.HTTP_UNAUTHORIZED;
} else if (error instanceof ServerError) {
statusCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
} else if (error instanceof ParseError) {
statusCode = HttpURLConnection.HTTP_BAD_REQUEST;
}
return statusCode;
}
} | 7,072 | 0.6472 | 0.646493 | 196 | 35.086735 | 27.66025 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.530612 | false | false | 9 |
5592376eee35a61838e7829c806bab43f9036f78 | 21,414,706,953,418 | bdf0f079bcc9e4f007aac7c1816f00174062a2f9 | /src/edu/mirek/Duck.java | 8d6563597b50f401d70949c274636282cfa9edd4 | [] | no_license | mlatka/StrategyPattern | https://github.com/mlatka/StrategyPattern | 90d23605cc0fde7a0803eec623d945c6adef6655 | 815fb6c5a4f9900732dd248669743f6e1ee5b8de | refs/heads/master | 2020-03-23T06:03:28.513000 | 2018-07-16T20:24:45 | 2018-07-16T20:24:45 | 141,110,407 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.mirek;
public abstract class Duck {
private FlyInterface flyInterface;
private SoundInterface soundInterface;
public Duck() {
}
public Duck(FlyInterface flyInterface, SoundInterface soundInterface) {
this.flyInterface = flyInterface;
this.soundInterface = soundInterface;
}
public void setFlyInterface(FlyInterface flyInterface) {
this.flyInterface = flyInterface;
}
public void setSoundInterface(SoundInterface soundInterface) {
this.soundInterface = soundInterface;
}
public void swim(){
System.out.println("I'm swimming in the rain...");
}
public void makeSound(){
soundInterface.makeSound();
}
public void fly(){
flyInterface.fly();
}
public abstract void display();
}
| UTF-8 | Java | 829 | java | Duck.java | Java | [] | null | [] | package edu.mirek;
public abstract class Duck {
private FlyInterface flyInterface;
private SoundInterface soundInterface;
public Duck() {
}
public Duck(FlyInterface flyInterface, SoundInterface soundInterface) {
this.flyInterface = flyInterface;
this.soundInterface = soundInterface;
}
public void setFlyInterface(FlyInterface flyInterface) {
this.flyInterface = flyInterface;
}
public void setSoundInterface(SoundInterface soundInterface) {
this.soundInterface = soundInterface;
}
public void swim(){
System.out.println("I'm swimming in the rain...");
}
public void makeSound(){
soundInterface.makeSound();
}
public void fly(){
flyInterface.fly();
}
public abstract void display();
}
| 829 | 0.656212 | 0.656212 | 44 | 17.84091 | 21.507866 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 9 |
7806a45567a9a855d34867a3872fb84fb5457eaf | 20,933,670,645,246 | 912e9efee608dda6c7175f9a5fbd23152688ef11 | /src/lexical/exception/IncompleteException.java | fc3b0eab8503e4c5ad4fcca83f54a0ad3602c72b | [] | no_license | amabouei/Compiler | https://github.com/amabouei/Compiler | 1c74355832a070174162c1883c9c4e950277c119 | 2149943c7643f58bca3d3eaf51e72fae9fc27461 | refs/heads/master | 2023-06-26T21:28:15.243000 | 2019-07-02T23:46:12 | 2019-07-02T23:46:12 | 180,425,638 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lexical.exception;
public class IncompleteException extends LexicalException {
public IncompleteException(String str) {
this.str = str;
}
public IncompleteException(String str, int line) {
this.str = str;
this.line = line;
}
public int getLine() {
return line;
}
@Override
public String toString() {
return super.toString() + "incomplete)";
}
}
| UTF-8 | Java | 435 | java | IncompleteException.java | Java | [] | null | [] | package lexical.exception;
public class IncompleteException extends LexicalException {
public IncompleteException(String str) {
this.str = str;
}
public IncompleteException(String str, int line) {
this.str = str;
this.line = line;
}
public int getLine() {
return line;
}
@Override
public String toString() {
return super.toString() + "incomplete)";
}
}
| 435 | 0.611494 | 0.611494 | 22 | 18.772728 | 18.59602 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 9 |
3e498e484f4bbbc2656ad818dadc860d515deb0d | 7,395,933,732,029 | 77fb90c41fd2844cc4350400d786df99e14fa4ca | /com/facebook/ProgressOutputStream.java | 5fd53b97a6f2cff38cd5de510f420e7a4eee6b50 | [] | no_license | highnes7/umaang_decompiled | https://github.com/highnes7/umaang_decompiled | 341193b25351188d69b4413ebe7f0cde6525c8fb | bcfd90dffe81db012599278928cdcc6207632c56 | refs/heads/master | 2020-06-19T07:47:18.630000 | 2019-07-12T17:16:13 | 2019-07-12T17:16:13 | 196,615,053 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.facebook;
import android.os.Handler;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ProgressOutputStream
extends FilterOutputStream
implements RequestOutputStream
{
public long batchProgress;
public RequestProgress currentRequestProgress;
public long lastReportedProgress;
public long maxProgress;
public final Map<GraphRequest, RequestProgress> progressMap;
public final GraphRequestBatch requests;
public final long threshold;
public ProgressOutputStream(OutputStream paramOutputStream, GraphRequestBatch paramGraphRequestBatch, Map paramMap, long paramLong)
{
super(paramOutputStream);
requests = paramGraphRequestBatch;
progressMap = paramMap;
maxProgress = paramLong;
threshold = FacebookSdk.getOnProgressThreshold();
}
private void addProgress(long paramLong)
{
RequestProgress localRequestProgress = currentRequestProgress;
if (localRequestProgress != null) {
localRequestProgress.addProgress(paramLong);
}
batchProgress += paramLong;
paramLong = batchProgress;
if ((paramLong >= lastReportedProgress + threshold) || (paramLong >= maxProgress)) {
reportBatchProgress();
}
}
private void reportBatchProgress()
{
if (batchProgress > lastReportedProgress)
{
Iterator localIterator = requests.getCallbacks().iterator();
while (localIterator.hasNext())
{
Object localObject = (GraphRequestBatch.Callback)localIterator.next();
if ((localObject instanceof GraphRequestBatch.OnProgressCallback))
{
Handler localHandler = requests.getCallbackHandler();
localObject = (GraphRequestBatch.OnProgressCallback)localObject;
if (localHandler == null) {
((GraphRequestBatch.OnProgressCallback)localObject).onBatchProgress(requests, batchProgress, maxProgress);
} else {
localHandler.post(new Runnable()
{
public void run()
{
val$progressCallback.onBatchProgress(ProgressOutputStream.access$000(ProgressOutputStream.this), ProgressOutputStream.access$100(ProgressOutputStream.this), ProgressOutputStream.access$200(ProgressOutputStream.this));
}
});
}
}
}
lastReportedProgress = batchProgress;
}
}
public void close()
throws IOException
{
super.close();
Iterator localIterator = progressMap.values().iterator();
while (localIterator.hasNext()) {
((RequestProgress)localIterator.next()).reportProgress();
}
reportBatchProgress();
}
public long getBatchProgress()
{
return batchProgress;
}
public long getMaxProgress()
{
return maxProgress;
}
public void setCurrentRequest(GraphRequest paramGraphRequest)
{
if (paramGraphRequest != null) {
paramGraphRequest = (RequestProgress)progressMap.get(paramGraphRequest);
} else {
paramGraphRequest = null;
}
currentRequestProgress = paramGraphRequest;
}
public void write(int paramInt)
throws IOException
{
out.write(paramInt);
addProgress(1L);
}
public void write(byte[] paramArrayOfByte)
throws IOException
{
out.write(paramArrayOfByte);
addProgress(paramArrayOfByte.length);
}
public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws IOException
{
out.write(paramArrayOfByte, paramInt1, paramInt2);
addProgress(paramInt2);
}
}
| UTF-8 | Java | 3,655 | java | ProgressOutputStream.java | Java | [] | null | [] | package com.facebook;
import android.os.Handler;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ProgressOutputStream
extends FilterOutputStream
implements RequestOutputStream
{
public long batchProgress;
public RequestProgress currentRequestProgress;
public long lastReportedProgress;
public long maxProgress;
public final Map<GraphRequest, RequestProgress> progressMap;
public final GraphRequestBatch requests;
public final long threshold;
public ProgressOutputStream(OutputStream paramOutputStream, GraphRequestBatch paramGraphRequestBatch, Map paramMap, long paramLong)
{
super(paramOutputStream);
requests = paramGraphRequestBatch;
progressMap = paramMap;
maxProgress = paramLong;
threshold = FacebookSdk.getOnProgressThreshold();
}
private void addProgress(long paramLong)
{
RequestProgress localRequestProgress = currentRequestProgress;
if (localRequestProgress != null) {
localRequestProgress.addProgress(paramLong);
}
batchProgress += paramLong;
paramLong = batchProgress;
if ((paramLong >= lastReportedProgress + threshold) || (paramLong >= maxProgress)) {
reportBatchProgress();
}
}
private void reportBatchProgress()
{
if (batchProgress > lastReportedProgress)
{
Iterator localIterator = requests.getCallbacks().iterator();
while (localIterator.hasNext())
{
Object localObject = (GraphRequestBatch.Callback)localIterator.next();
if ((localObject instanceof GraphRequestBatch.OnProgressCallback))
{
Handler localHandler = requests.getCallbackHandler();
localObject = (GraphRequestBatch.OnProgressCallback)localObject;
if (localHandler == null) {
((GraphRequestBatch.OnProgressCallback)localObject).onBatchProgress(requests, batchProgress, maxProgress);
} else {
localHandler.post(new Runnable()
{
public void run()
{
val$progressCallback.onBatchProgress(ProgressOutputStream.access$000(ProgressOutputStream.this), ProgressOutputStream.access$100(ProgressOutputStream.this), ProgressOutputStream.access$200(ProgressOutputStream.this));
}
});
}
}
}
lastReportedProgress = batchProgress;
}
}
public void close()
throws IOException
{
super.close();
Iterator localIterator = progressMap.values().iterator();
while (localIterator.hasNext()) {
((RequestProgress)localIterator.next()).reportProgress();
}
reportBatchProgress();
}
public long getBatchProgress()
{
return batchProgress;
}
public long getMaxProgress()
{
return maxProgress;
}
public void setCurrentRequest(GraphRequest paramGraphRequest)
{
if (paramGraphRequest != null) {
paramGraphRequest = (RequestProgress)progressMap.get(paramGraphRequest);
} else {
paramGraphRequest = null;
}
currentRequestProgress = paramGraphRequest;
}
public void write(int paramInt)
throws IOException
{
out.write(paramInt);
addProgress(1L);
}
public void write(byte[] paramArrayOfByte)
throws IOException
{
out.write(paramArrayOfByte);
addProgress(paramArrayOfByte.length);
}
public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws IOException
{
out.write(paramArrayOfByte, paramInt1, paramInt2);
addProgress(paramInt2);
}
}
| 3,655 | 0.703694 | 0.69959 | 126 | 28.007936 | 30.713085 | 233 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
3cbd0f057007f72dfb7544c9affb03d0e3894269 | 17,480,516,938,137 | 7a33307595592bc59eefe5d798aa98227a1fbe53 | /src/main/java/com/udacity/jwdnd/course1/cloudstorage/controller/SignupController.java | a7fbfc893ce57b332078565a2430b8debcea18bd | [] | no_license | leedMx/Drive | https://github.com/leedMx/Drive | 767e3fe12c437963578e856ce260db8baafda2b6 | 708c036189a486b26484a9726d3cf64dd0fbb79a | refs/heads/master | 2023-03-26T17:58:34.833000 | 2021-03-30T23:27:34 | 2021-03-30T23:27:34 | 320,582,277 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.udacity.jwdnd.course1.cloudstorage.controller;
import com.udacity.jwdnd.course1.cloudstorage.Model.UserModel;
import com.udacity.jwdnd.course1.cloudstorage.services.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/signup")
public class SignupController {
UserService userService;
public SignupController(UserService userService) {
this.userService = userService;
}
@GetMapping
String get(){
return "signup";
}
@PostMapping
String post(@ModelAttribute UserModel user, Model model){
if (userService.isUsernameAvailable(user.getUsername())) {
createUser(user, model);
return "redirect:/login?signup=true";
}
else
model.addAttribute("signupError","Username not available");
return "signup";
}
private void createUser(@ModelAttribute UserModel user, Model model) {
if (userService.createUser(user) > 0)
model.addAttribute("signupSuccess", "success");
else
model.addAttribute("signupError","error creating user");
}
}
| UTF-8 | Java | 1,424 | java | SignupController.java | Java | [] | null | [] | package com.udacity.jwdnd.course1.cloudstorage.controller;
import com.udacity.jwdnd.course1.cloudstorage.Model.UserModel;
import com.udacity.jwdnd.course1.cloudstorage.services.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/signup")
public class SignupController {
UserService userService;
public SignupController(UserService userService) {
this.userService = userService;
}
@GetMapping
String get(){
return "signup";
}
@PostMapping
String post(@ModelAttribute UserModel user, Model model){
if (userService.isUsernameAvailable(user.getUsername())) {
createUser(user, model);
return "redirect:/login?signup=true";
}
else
model.addAttribute("signupError","Username not available");
return "signup";
}
private void createUser(@ModelAttribute UserModel user, Model model) {
if (userService.createUser(user) > 0)
model.addAttribute("signupSuccess", "success");
else
model.addAttribute("signupError","error creating user");
}
}
| 1,424 | 0.716994 | 0.714185 | 43 | 32.11628 | 25.227531 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55814 | false | false | 9 |
0a73eea6834d1ab49234b5bc3b73d96c552542d5 | 17,188,459,175,285 | 4abe1a779d44566ff65971366b7d39f8f9b959d1 | /dbs-scheduled-custom-integration/src/main/java/com/backbase/training/beans/Metadata_.java | 9ae4c5ce7e31fbec81b71681ca10f5a07c33bfe8 | [] | no_license | jouergagner75/bb | https://github.com/jouergagner75/bb | 4f0c4367dde214648363f2ec5c0ea22ba6d935f1 | 111ae9a50b7a45777f8844d3b8acffb71f11bd09 | refs/heads/master | 2020-08-01T02:21:49.735000 | 2019-09-25T11:30:19 | 2019-09-25T11:30:19 | 210,826,463 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.backbase.training.beans;
import com.fasterxml.jackson.annotation.*;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"narrative",
"comments",
"tags",
"images",
"where"
})
public class Metadata_ {
@JsonProperty("narrative")
private Object narrative;
@JsonProperty("comments")
private List<Object> comments = null;
@JsonProperty("tags")
private List<Object> tags = null;
@JsonProperty("images")
private List<Object> images = null;
@JsonProperty("where")
private Object where;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("narrative")
public Object getNarrative() {
return narrative;
}
@JsonProperty("narrative")
public void setNarrative(Object narrative) {
this.narrative = narrative;
}
@JsonProperty("comments")
public List<Object> getComments() {
return comments;
}
@JsonProperty("comments")
public void setComments(List<Object> comments) {
this.comments = comments;
}
@JsonProperty("tags")
public List<Object> getTags() {
return tags;
}
@JsonProperty("tags")
public void setTags(List<Object> tags) {
this.tags = tags;
}
@JsonProperty("images")
public List<Object> getImages() {
return images;
}
@JsonProperty("images")
public void setImages(List<Object> images) {
this.images = images;
}
@JsonProperty("where")
public Object getWhere() {
return where;
}
@JsonProperty("where")
public void setWhere(Object where) {
this.where = where;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return new ToStringBuilder(this).append("narrative", narrative).append("comments", comments).append("tags", tags).append("images", images).append("where", where).append("additionalProperties", additionalProperties).toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(tags).append(additionalProperties).append(narrative).append(images).append(where).append(comments).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Metadata_) == false) {
return false;
}
Metadata_ rhs = ((Metadata_) other);
return new EqualsBuilder().append(tags, rhs.tags).append(additionalProperties, rhs.additionalProperties).append(narrative, rhs.narrative).append(images, rhs.images).append(where, rhs.where).append(comments, rhs.comments).isEquals();
}
}
| UTF-8 | Java | 3,217 | java | Metadata_.java | Java | [] | null | [] |
package com.backbase.training.beans;
import com.fasterxml.jackson.annotation.*;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"narrative",
"comments",
"tags",
"images",
"where"
})
public class Metadata_ {
@JsonProperty("narrative")
private Object narrative;
@JsonProperty("comments")
private List<Object> comments = null;
@JsonProperty("tags")
private List<Object> tags = null;
@JsonProperty("images")
private List<Object> images = null;
@JsonProperty("where")
private Object where;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("narrative")
public Object getNarrative() {
return narrative;
}
@JsonProperty("narrative")
public void setNarrative(Object narrative) {
this.narrative = narrative;
}
@JsonProperty("comments")
public List<Object> getComments() {
return comments;
}
@JsonProperty("comments")
public void setComments(List<Object> comments) {
this.comments = comments;
}
@JsonProperty("tags")
public List<Object> getTags() {
return tags;
}
@JsonProperty("tags")
public void setTags(List<Object> tags) {
this.tags = tags;
}
@JsonProperty("images")
public List<Object> getImages() {
return images;
}
@JsonProperty("images")
public void setImages(List<Object> images) {
this.images = images;
}
@JsonProperty("where")
public Object getWhere() {
return where;
}
@JsonProperty("where")
public void setWhere(Object where) {
this.where = where;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return new ToStringBuilder(this).append("narrative", narrative).append("comments", comments).append("tags", tags).append("images", images).append("where", where).append("additionalProperties", additionalProperties).toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(tags).append(additionalProperties).append(narrative).append(images).append(where).append(comments).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Metadata_) == false) {
return false;
}
Metadata_ rhs = ((Metadata_) other);
return new EqualsBuilder().append(tags, rhs.tags).append(additionalProperties, rhs.additionalProperties).append(narrative, rhs.narrative).append(images, rhs.images).append(where, rhs.where).append(comments, rhs.comments).isEquals();
}
}
| 3,217 | 0.660864 | 0.660864 | 117 | 26.487179 | 35.106339 | 240 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452991 | false | false | 9 |
a4039e82bffbcabf4be516713a115ee45a32b0fc | 9,328,669,012,277 | 7d5920809b5628e775d34c4b09315c135fdbcf1f | /transportable-udfs-codegen/src/main/java/com/linkedin/transport/codegen/CodegenUtils.java | 3588ba18bfc93d649ce91248f99a4a5e2b7ff7cf | [
"Apache-2.0",
"BSD-2-Clause"
] | permissive | linkedin/transport | https://github.com/linkedin/transport | 124d54f2232709ae755edb99c47b0a7f0c736c8e | 1adf4f4a7d38a5a46d9f57f38e1d68f348b9ad44 | refs/heads/master | 2023-09-06T09:09:45.627000 | 2023-06-08T12:26:38 | 2023-06-08T12:26:38 | 157,273,136 | 285 | 79 | BSD-2-Clause | false | 2023-06-08T20:41:00 | 2018-11-12T20:34:12 | 2023-06-08T07:58:10 | 2023-06-08T20:41:00 | 1,183 | 278 | 73 | 37 | Java | false | false | /**
* Copyright 2019 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.transport.codegen;
import com.google.common.base.Preconditions;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import org.apache.commons.lang3.StringUtils;
class CodegenUtils {
private CodegenUtils() {
}
/**
* Writes a source code file for a class to the provided output directory creating package directories if required
*
* @param outputDir Output directory
* @param packageName Package name of the class (can be {@code null} for the default package)
* @param className Class name
* @param extension Extension of the file (can be {@code null} for no extension)
* @param code Source code of the class
* @throws IOException
*/
static void writeCodeFile(Path outputDir, String packageName, String className, String extension,
String code) throws IOException {
Preconditions.checkArgument(Files.notExists(outputDir) || Files.isDirectory(outputDir),
"Output directory should not exist or must be a directory", outputDir);
Preconditions.checkArgument(!StringUtils.isBlank(className), "Class name should not be null or an empty string");
Preconditions.checkNotNull(code, "Code should not be null");
final Path packageDir;
if (!StringUtils.isBlank(packageName)) {
packageDir = Paths.get(outputDir.toString(), packageName.split("\\."));
} else {
packageDir = outputDir;
}
Files.createDirectories(packageDir);
String fileName = className + (StringUtils.isBlank(extension) ? "" : "." + extension);
Path outputPath = packageDir.resolve(fileName);
Files.write(outputPath, code.getBytes());
}
/**
* Writes a list of services to a specified service file
*
* @param outputDir Output directory
* @param serviceFilePath Path of the service file relative to the output directory
* @param services List of services
* @throws IOException
*/
static void writeServiceFile(Path outputDir, Path serviceFilePath, Collection<String> services)
throws IOException {
Preconditions.checkArgument(Files.notExists(outputDir) || Files.isDirectory(outputDir),
"Output directory should not exist or must be a directory", outputDir);
Preconditions.checkNotNull(serviceFilePath, "Service file path should not be null");
Path resolvedServiceFilePath = outputDir.resolve(serviceFilePath);
Files.createDirectories(resolvedServiceFilePath.getParent());
try (BufferedWriter writer = Files.newBufferedWriter(resolvedServiceFilePath)) {
for (String service : services) {
writer.write(service + "\n");
}
}
}
}
| UTF-8 | Java | 2,886 | java | CodegenUtils.java | Java | [] | null | [] | /**
* Copyright 2019 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.transport.codegen;
import com.google.common.base.Preconditions;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import org.apache.commons.lang3.StringUtils;
class CodegenUtils {
private CodegenUtils() {
}
/**
* Writes a source code file for a class to the provided output directory creating package directories if required
*
* @param outputDir Output directory
* @param packageName Package name of the class (can be {@code null} for the default package)
* @param className Class name
* @param extension Extension of the file (can be {@code null} for no extension)
* @param code Source code of the class
* @throws IOException
*/
static void writeCodeFile(Path outputDir, String packageName, String className, String extension,
String code) throws IOException {
Preconditions.checkArgument(Files.notExists(outputDir) || Files.isDirectory(outputDir),
"Output directory should not exist or must be a directory", outputDir);
Preconditions.checkArgument(!StringUtils.isBlank(className), "Class name should not be null or an empty string");
Preconditions.checkNotNull(code, "Code should not be null");
final Path packageDir;
if (!StringUtils.isBlank(packageName)) {
packageDir = Paths.get(outputDir.toString(), packageName.split("\\."));
} else {
packageDir = outputDir;
}
Files.createDirectories(packageDir);
String fileName = className + (StringUtils.isBlank(extension) ? "" : "." + extension);
Path outputPath = packageDir.resolve(fileName);
Files.write(outputPath, code.getBytes());
}
/**
* Writes a list of services to a specified service file
*
* @param outputDir Output directory
* @param serviceFilePath Path of the service file relative to the output directory
* @param services List of services
* @throws IOException
*/
static void writeServiceFile(Path outputDir, Path serviceFilePath, Collection<String> services)
throws IOException {
Preconditions.checkArgument(Files.notExists(outputDir) || Files.isDirectory(outputDir),
"Output directory should not exist or must be a directory", outputDir);
Preconditions.checkNotNull(serviceFilePath, "Service file path should not be null");
Path resolvedServiceFilePath = outputDir.resolve(serviceFilePath);
Files.createDirectories(resolvedServiceFilePath.getParent());
try (BufferedWriter writer = Files.newBufferedWriter(resolvedServiceFilePath)) {
for (String service : services) {
writer.write(service + "\n");
}
}
}
}
| 2,886 | 0.730076 | 0.727997 | 76 | 36.973682 | 33.074467 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565789 | false | false | 9 |
f9eaaa2f6bacd9b7ea3a16fb1f626d345dbd7926 | 31,799,937,911,744 | 0517ae9ad164038cc6e6be0509ac9bf23d7ec44c | /hazelcast/src/test/java/com/hazelcast/internal/networking/nonblocking/SelectorOptimizerTest.java | 3fdfc7510fa0c847a1529cf90767c4c167db2c78 | [
"Apache-2.0"
] | permissive | atlassian/hazelcast | https://github.com/atlassian/hazelcast | 1c8e5ec58f626102d4de0dc97b6f2f4dfd946b9d | 174b3db30e001c2a1b60d870cfcc3138f10edecc | refs/heads/master | 2023-07-08T07:23:49.811000 | 2016-11-28T15:01:28 | 2016-11-28T19:16:15 | 24,581,214 | 4 | 4 | null | true | 2023-03-23T23:55:52 | 2014-09-29T05:33:05 | 2019-07-22T16:36:59 | 2023-03-23T23:55:52 | 100,300 | 5 | 4 | 8 | Java | false | false | package com.hazelcast.internal.networking.nonblocking;
import com.hazelcast.internal.networking.nonblocking.SelectionKeysSetTest;
import com.hazelcast.internal.networking.nonblocking.SelectorOptimizer;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.nio.channels.Selector;
import static com.hazelcast.internal.networking.nonblocking.SelectorOptimizer.findOptimizableSelectorClass;
import static com.hazelcast.test.HazelcastTestSupport.assertUtilityConstructor;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class SelectorOptimizerTest {
private ILogger logger = Logger.getLogger(SelectionKeysSetTest.class);
@Test
public void testConstructor() {
assertUtilityConstructor(SelectorOptimizer.class);
}
@Test
public void optimize() throws Exception {
Selector selector = Selector.open();
assumeTrue(findOptimizableSelectorClass(selector) != null);
SelectorOptimizer.SelectionKeysSet keys = SelectorOptimizer.optimize(selector, logger);
assertNotNull(keys);
}
}
| UTF-8 | Java | 1,403 | java | SelectorOptimizerTest.java | Java | [] | null | [] | package com.hazelcast.internal.networking.nonblocking;
import com.hazelcast.internal.networking.nonblocking.SelectionKeysSetTest;
import com.hazelcast.internal.networking.nonblocking.SelectorOptimizer;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.nio.channels.Selector;
import static com.hazelcast.internal.networking.nonblocking.SelectorOptimizer.findOptimizableSelectorClass;
import static com.hazelcast.test.HazelcastTestSupport.assertUtilityConstructor;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class SelectorOptimizerTest {
private ILogger logger = Logger.getLogger(SelectionKeysSetTest.class);
@Test
public void testConstructor() {
assertUtilityConstructor(SelectorOptimizer.class);
}
@Test
public void optimize() throws Exception {
Selector selector = Selector.open();
assumeTrue(findOptimizableSelectorClass(selector) != null);
SelectorOptimizer.SelectionKeysSet keys = SelectorOptimizer.optimize(selector, logger);
assertNotNull(keys);
}
}
| 1,403 | 0.807555 | 0.807555 | 37 | 36.918919 | 28.469404 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594595 | false | false | 9 |
2397525af1431cfa0920f8dcc2c42fcce3b7c56a | 24,154,896,125,415 | 204d2214e7c9a0bda5e2161f840d3330d8730974 | /progr1/Esercizi/arg8/ArrMaggioriMinoriRec.java | a67d71bf6f8a2184052e487dca4ab1889206b331 | [] | no_license | andreadlm/unito | https://github.com/andreadlm/unito | dd8135e1c47f1100d2fcbec9d7215c79547f4c60 | fa3e74b0de96dbd3098bfdbdc2537caea7651000 | refs/heads/master | 2022-02-28T17:43:47.039000 | 2022-02-16T09:42:28 | 2022-02-16T09:42:28 | 213,619,211 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package arg8;
public class ArrMaggioriMinoriRec {
// tutti minori di x o tutti maggiori di y
public static boolean tuttiMaggioriOMinori(int[] arr, int x, int y) {
if(arr != null && arr.length > 0)
return tuttiMaggioriCon(arr, y, 0) || tuttiMinoriCon(arr, x, 0);
else
return false;
}
/*private static boolean tuttiMaggioriCo(int[] arr, int y, int i) {
if(i == 0) return arr[i] > y;
return arr[i] > y && tuttiMaggioriCo(arr, y, i - 1);
}
private static boolean tuttiMinoriCo(int[] arr, int x, int i) {
if(i == 0) return arr[i] < x;
return arr[i] < x && tuttiMinoriCo(arr, x, i - 1);
}*/
private static boolean tuttiMaggioriCon(int[] arr, int y, int i) {
if(i == arr.length - 1) return arr[i] > y;
return arr[i] > y && tuttiMaggioriCon(arr, y, i + 1);
}
private static boolean tuttiMinoriCon(int[] arr, int x, int i) {
if(i == arr.length - 1) return arr[i] < x;
return arr[i] < x && tuttiMinoriCon(arr, x, i + 1);
}
} | UTF-8 | Java | 1,069 | java | ArrMaggioriMinoriRec.java | Java | [] | null | [] | package arg8;
public class ArrMaggioriMinoriRec {
// tutti minori di x o tutti maggiori di y
public static boolean tuttiMaggioriOMinori(int[] arr, int x, int y) {
if(arr != null && arr.length > 0)
return tuttiMaggioriCon(arr, y, 0) || tuttiMinoriCon(arr, x, 0);
else
return false;
}
/*private static boolean tuttiMaggioriCo(int[] arr, int y, int i) {
if(i == 0) return arr[i] > y;
return arr[i] > y && tuttiMaggioriCo(arr, y, i - 1);
}
private static boolean tuttiMinoriCo(int[] arr, int x, int i) {
if(i == 0) return arr[i] < x;
return arr[i] < x && tuttiMinoriCo(arr, x, i - 1);
}*/
private static boolean tuttiMaggioriCon(int[] arr, int y, int i) {
if(i == arr.length - 1) return arr[i] > y;
return arr[i] > y && tuttiMaggioriCon(arr, y, i + 1);
}
private static boolean tuttiMinoriCon(int[] arr, int x, int i) {
if(i == arr.length - 1) return arr[i] < x;
return arr[i] < x && tuttiMinoriCon(arr, x, i + 1);
}
} | 1,069 | 0.565014 | 0.553789 | 33 | 31.424242 | 27.844841 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.060606 | false | false | 9 |
7bfc2309ca4869363e9a68df23d1f5598b1a278c | 27,573,690,090,127 | 046aa16c531e00d6c114fdbeacc19f8b196827d7 | /src/net/liujian/cheer/LearnStudy/FengzhuangJichengDuotai/KaiPhone/Phone.java | 575d19544edf2a3c3c294f7bfd72bce25fd0eced | [] | no_license | liujian1989/liujian | https://github.com/liujian1989/liujian | 92032847b47c4599609ef2a6c62a03913f58ea6a | bb1193763c2be7e3e8152f2c50dabd8c69a00901 | refs/heads/master | 2021-01-19T18:59:04.963000 | 2017-06-25T01:42:59 | 2017-06-25T01:49:27 | 88,392,831 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.liujian.cheer.LearnStudy.FengzhuangJichengDuotai.KaiPhone;
public class Phone extends KaiPhone3{
public static void main(String[] args) {
KaiPhone kai1=new KaiPhone();
kai1.dadianhua();
kai1.jiedianhua();
kai1.xianshi();
KaiPhone2 kai2=new KaiPhone2();
kai2.dadianhua();
kai2.jiedianhua();
kai2.fasongduanxin();
kai2.chakanduanxin();
kai2.xianshi();
KaiPhone3 kai3=new KaiPhone3();
kai3.jiedianhua();
kai3.dadianhua();
kai3.fasongduanxin();
kai3.chakanduanxin();
kai3.naozhong();
kai3.rili();
kai3.genghuanlingsheng();
kai3.xianshi();
kai3.jisuanqi();
}
}
| UTF-8 | Java | 622 | java | Phone.java | Java | [] | null | [] | package net.liujian.cheer.LearnStudy.FengzhuangJichengDuotai.KaiPhone;
public class Phone extends KaiPhone3{
public static void main(String[] args) {
KaiPhone kai1=new KaiPhone();
kai1.dadianhua();
kai1.jiedianhua();
kai1.xianshi();
KaiPhone2 kai2=new KaiPhone2();
kai2.dadianhua();
kai2.jiedianhua();
kai2.fasongduanxin();
kai2.chakanduanxin();
kai2.xianshi();
KaiPhone3 kai3=new KaiPhone3();
kai3.jiedianhua();
kai3.dadianhua();
kai3.fasongduanxin();
kai3.chakanduanxin();
kai3.naozhong();
kai3.rili();
kai3.genghuanlingsheng();
kai3.xianshi();
kai3.jisuanqi();
}
}
| 622 | 0.696141 | 0.655949 | 31 | 19.064516 | 14.67703 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.225806 | false | false | 9 |
02685edb8e417be85528a1895dcc2dd2b8a72d7c | 16,234,976,430,959 | f4620cccef765930920106d21ad26d7352e3dc38 | /app/femr/util/stringhelpers/StringUtils.java | d96ae2baf8f9805e1b1b99e9304b89270d4ccdea | [
"MIT"
] | permissive | b6025/csc4996femr | https://github.com/b6025/csc4996femr | 5c2eb01bbf4371e7b0c3f56a88ff98e943cfa9a9 | 850febed3f9caddc8b9f6e03529acf05ec65c000 | refs/heads/master | 2016-07-26T09:06:54.487000 | 2014-02-20T22:32:22 | 2014-02-20T22:32:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package femr.util.stringhelpers;
public class StringUtils {
public static boolean isNullOrWhiteSpace(String stringToCheck) {
return stringToCheck == null || stringToCheck.trim().isEmpty();
}
public static boolean isNotNullOrWhiteSpace(String stringToCheck) {
return !isNullOrWhiteSpace(stringToCheck);
}
}
| UTF-8 | Java | 340 | java | StringUtils.java | Java | [] | null | [] | package femr.util.stringhelpers;
public class StringUtils {
public static boolean isNullOrWhiteSpace(String stringToCheck) {
return stringToCheck == null || stringToCheck.trim().isEmpty();
}
public static boolean isNotNullOrWhiteSpace(String stringToCheck) {
return !isNullOrWhiteSpace(stringToCheck);
}
}
| 340 | 0.732353 | 0.732353 | 11 | 29.90909 | 28.789059 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
46e2229ea8c52efa2116ca55e1e90510e75742d4 | 21,517,786,206,228 | 6e2c5c2b512fbb9fc954bd4f93fe6a6290c9485d | /app/src/main/java/com/example/vegetablessell/model/ProductDetails.java | ef2eef48efb1d1a9828856b73613685cd943c8b7 | [] | no_license | RonakSahu0204/VegetableSellingApp | https://github.com/RonakSahu0204/VegetableSellingApp | 2a158e2da81a565aa1f9cd9546172f6031e4a2c7 | 53c9ae003d0f14e457802bf0c0604b57ef407489 | refs/heads/master | 2023-01-05T09:50:42.650000 | 2020-11-05T17:36:06 | 2020-11-05T17:36:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.vegetablessell.model;
public class ProductDetails {
private String productName;
private int price;
private int discount;
private int quantity;
private String description;
private String sellerShopName;
private String sellerEmail;
private String imageUrl;
private String id;
public ProductDetails() {}
public ProductDetails(String id, String productName, int price, int discount, int quantity, String description, String sellerShopName, String sellerEmail, String imageUrl) {
this.productName = productName;
this.price = price;
this.discount = discount;
this.quantity = quantity;
this.description = description;
this.sellerShopName = sellerShopName;
this.sellerEmail = sellerEmail;
this.id = id;
this.imageUrl = imageUrl;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSellerShopName() {
return sellerShopName;
}
public void setSellerShopName(String sellerShopName) {
this.sellerShopName = sellerShopName;
}
public String getSellerEmail() {
return sellerEmail;
}
public void setSellerEmail(String sellerEmail) {
this.sellerEmail = sellerEmail;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "ProductDetails{" +
"productName='" + productName + '\'' +
", price=" + price +
", discount=" + discount +
", quantity=" + quantity +
", description='" + description + '\'' +
", sellerShopName='" + sellerShopName + '\'' +
", sellerEmail='" + sellerEmail + '\'' +
", imageUrl='" + imageUrl + '\'' +
", id='" + id + '\'' +
'}';
}
}
| UTF-8 | Java | 2,826 | java | ProductDetails.java | Java | [] | null | [] | package com.example.vegetablessell.model;
public class ProductDetails {
private String productName;
private int price;
private int discount;
private int quantity;
private String description;
private String sellerShopName;
private String sellerEmail;
private String imageUrl;
private String id;
public ProductDetails() {}
public ProductDetails(String id, String productName, int price, int discount, int quantity, String description, String sellerShopName, String sellerEmail, String imageUrl) {
this.productName = productName;
this.price = price;
this.discount = discount;
this.quantity = quantity;
this.description = description;
this.sellerShopName = sellerShopName;
this.sellerEmail = sellerEmail;
this.id = id;
this.imageUrl = imageUrl;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSellerShopName() {
return sellerShopName;
}
public void setSellerShopName(String sellerShopName) {
this.sellerShopName = sellerShopName;
}
public String getSellerEmail() {
return sellerEmail;
}
public void setSellerEmail(String sellerEmail) {
this.sellerEmail = sellerEmail;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "ProductDetails{" +
"productName='" + productName + '\'' +
", price=" + price +
", discount=" + discount +
", quantity=" + quantity +
", description='" + description + '\'' +
", sellerShopName='" + sellerShopName + '\'' +
", sellerEmail='" + sellerEmail + '\'' +
", imageUrl='" + imageUrl + '\'' +
", id='" + id + '\'' +
'}';
}
}
| 2,826 | 0.584572 | 0.584572 | 115 | 23.573914 | 22.843536 | 177 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.469565 | false | false | 9 |
e77ada333e0db8a0de14297ac5246fb53ded8a3e | 21,517,786,209,311 | 61fcbb7bb6d3fcf24383311692097c1c94bd9624 | /app/src/main/java/com/android/htc/greenroad/activity/MainActivity.java | fef1d1e58ae057ddb94786da11216574663dda30 | [] | no_license | ZEROwolfHwang/ZEROwolf10-20 | https://github.com/ZEROwolfHwang/ZEROwolf10-20 | 01776f430888c87b1100833c08806244ca11f5a1 | faf464310e3c335e069cad6f3c13d46f59e6516c | refs/heads/master | 2021-07-15T06:41:19.738000 | 2017-10-21T04:28:22 | 2017-10-21T04:28:22 | 106,633,280 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.htc.greenroad.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.htc.greenroad.manager.GlobalManager;
import com.orhanobut.logger.Logger;
import com.android.htc.greenroad.R;
import com.android.htc.greenroad.bean.UpdateAppInfo;
import com.android.htc.greenroad.httpresultbean.HttpResultMacInfo;
import com.android.htc.greenroad.https.RequestMacInfo;
import com.android.htc.greenroad.litepalbean.SupportOperator;
import com.android.htc.greenroad.servicy.BlackListService;
import com.android.htc.greenroad.servicy.SubmitService;
import com.android.htc.greenroad.tools.ActionBarTool;
import com.android.htc.greenroad.tools.ActivityCollector;
import com.android.htc.greenroad.tools.CommonUtils;
import com.android.htc.greenroad.tools.DevicesInfoUtils;
import com.android.htc.greenroad.tools.PermissionUtils;
import com.android.htc.greenroad.tools.SDcardSpace;
import com.android.htc.greenroad.tools.SPListUtil;
import com.android.htc.greenroad.tools.SPUtils;
import com.android.htc.greenroad.tools.ToastUtils;
import com.android.htc.greenroad.update.AppInnerDownLoder;
import com.android.htc.greenroad.update.CheckUpdateUtils;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
/**
* Created by Administrator on 2017/6/20.
*/
public class MainActivity extends BaseActivity implements
NavigationView.OnNavigationItemSelectedListener{
@BindView(R.id.toolbar_main)
Toolbar mToolbarMain;
@BindView(R.id.drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view)
NavigationView mNavView;
@BindView(R.id.tv_change_station_main)
TextView mTvChangeStationMain;
@BindView(R.id.tv_change_lane_main)
TextView mTvChangeLaneMain;
@BindView(R.id.tv_operator_check_main)
TextView mTvOperatorCheckMain;
@BindView(R.id.tv_operator_login_main)
TextView mTvOperatorLoginMain;
@BindView(R.id.rl_main_draft)
RelativeLayout mRlMainDraft;
@BindView(R.id.rl_main_submit)
RelativeLayout mRlMainSubmit;
@BindView(R.id.tv_math_number_draft)
TextView mTvMathNumberDraft;
private static TextView mTvMathNumberSubmit;
@BindView(R.id.tv_avail_space)
TextView mTvAvailSpace;
@BindView(R.id.tv_all_space)
TextView mTvAllSpace;
@BindView(R.id.tv_math_number_blacklist)
TextView mTvMathNumberBlacklist;
@BindView(R.id.rl_main_blacklist)
RelativeLayout mRlMainBlacklist;
private long firstClick;
private static final String TAG = "MainActivity";
private static final int REQ_0 = 001;
@BindView(R.id.footer_item_setting)
TextView mTv_footer_setting;
@BindView(R.id.footer_item_theme)
TextView mTv_footer_theme;
@BindView(R.id.footer_item_location)
TextView mTv_footer_location;
private AppCompatActivity mActivity;
private AlertDialog.Builder mDialog;
private AlertDialog.Builder mNotPostDialog;
private int thumb_margin_left_day = 0;
private int thumb_margin_left_night = 0;
private String mRoad_Q;
private String mStation_Q;
private String mAvailSpace;
private String mAllSpace;
private String macID;
private MyBroadCaseReceiver mBroadCaseReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mActivity = this;
mTvOperatorCheckMain = (TextView) findViewById(R.id.tv_operator_check_main);
mTvOperatorLoginMain = (TextView) findViewById(R.id.tv_operator_login_main);
mTvMathNumberSubmit = (TextView) findViewById(R.id.tv_math_number_submit);
mTvChangeLaneMain.setOnClickListener(v -> openSettingActivity());
mTvOperatorCheckMain.setOnClickListener(v -> openSettingActivity());
mTvOperatorLoginMain.setOnClickListener(v -> openSettingActivity());
initSpace();
initData();
//initSp();
initView();
}
@OnClick({R.id.rl_main_draft, R.id.rl_main_submit, R.id.rl_main_blacklist, R.id.btn_enter_show})
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_main_draft:
Intent intent = new Intent(MainActivity.this, DraftActivity.class);
startActivity(intent);
break;
case R.id.rl_main_submit:
Intent intent1 = new Intent(MainActivity.this, SubmitActivity.class);
startActivity(intent1);
break;
case R.id.rl_main_blacklist:
Intent intent2 = new Intent(MainActivity.this, BlackListActivity.class);
startActivity(intent2);
break;
case R.id.btn_enter_show:
List<SupportOperator> check = DataSupport.where("check_select=?", "1").
find(SupportOperator.class);
List<SupportOperator> login = DataSupport.where("login_select=?", "1").
find(SupportOperator.class);
if (check.size() >= 1 && login.size() == 1) {
ShowActivity.actionStart(MainActivity.this);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("确定选择默认检查人/登记人");
builder.setMessage("点击确定进入设置界面添加默认操作员;\n" +
"点击取消则回到界面,不可以采集车辆数据");
builder.setPositiveButton("确定", (dialog, which) -> {
openSettingActivity();
});
builder.setNegativeButton("取消", (dialog, which) -> {
dialog.dismiss();
});
builder.show();
// ToastUtils.singleToast("目前请添加操作员");
break;
}
break;
default:
break;
}
}
private void initSpace() {
SDcardSpace sDcardSpace = new SDcardSpace(mActivity);
mAvailSpace = sDcardSpace.getAvailSpace();
// mAllSpace = sDcardSpace.getAllSpace();
mAllSpace = sDcardSpace.getSDTotalSize(mActivity);
mTvAllSpace.setText(" / " + mAllSpace);
mTvAvailSpace.setText(mAvailSpace + "");
}
private void initData() {
PermissionUtils.verifyStoragePermissions(mActivity);
BlackListService.startActionBlack(this, mTvMathNumberBlacklist);
macID = Settings.Secure
.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
List<String> strListValue = SPListUtil.getStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO);
if (strListValue == null || strListValue.size() != 3) {
RequestMacInfo.getInstance().getMacInfo(new Subscriber<HttpResultMacInfo>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Logger.i(e.getMessage());
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, null);
}
@Override
public void onNext(HttpResultMacInfo httpResultMacInfo) {
int code = httpResultMacInfo.getCode();
Logger.i(code + "");
HttpResultMacInfo.DataBean dataBean = httpResultMacInfo.getData();
Logger.i(dataBean.toString());
if (code == 200) {
List app_config_info = new ArrayList<String>();
app_config_info.add(dataBean.getName());
app_config_info.add(dataBean.getTerminal_road());
app_config_info.add(dataBean.getTerminal_site());
Logger.i(app_config_info.toString());
mTvChangeStationMain.setText(dataBean.getTerminal_road());
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, app_config_info);
} else {
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, null);
}
}
}, macID);
}
List<String> new_ListValue = SPListUtil.getStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO);
for (int i = 0; i < new_ListValue.size(); i++) {
String string = new_ListValue.get(i).toString();
Logger.i(string);
}
if (new_ListValue.size() == 3) {
mTvChangeStationMain.setText(new_ListValue.get(2));
}
}
private void initView() {
setSupportActionBar(mToolbarMain);
TextView title_text_view = ActionBarTool.getInstance(mActivity, 991).getTitle_text_view();
title_text_view.setText("绿通车登记");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbarMain, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@OnClick({R.id.footer_item_setting,
R.id.footer_item_theme, R.id.footer_item_location})
public void onFooterClick(View view) {
switch (view.getId()) {
case R.id.footer_item_setting:
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
break;
case R.id.footer_item_theme:
changeTheme();
break;
case R.id.footer_item_location:
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_about) {
navAbout();
} else if (id == R.id.nav_update) {
Logger.i("点击了更新按钮");
updateApp();
} else if (id == R.id.nav_backup) {
buckUpApp();
} else if (id == R.id.nav_config) {
// post_not_upload();
openConfigLine();
// Logger.i("点击了代开配置路线的按钮");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* 做配置路线的处理
*/
private void openConfigLine() {
LineConfigActivity.actionStart(MainActivity.this, GlobalManager.OTHER2PORT);
}
/**
* 点击主题菜单按钮改变App的主题
* /**
* 切换主题时展示动画
*/
private void changeTheme() {
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(240);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Intent intent = new Intent(getContext(), AnimatorActivity.class);
finish();
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
animatorSet.play(obtainCheckboxAnimator());
animatorSet.start();
}
private Animator obtainCheckboxAnimator() {
int start = getThemeTag() == -1 ? thumb_margin_left_night : thumb_margin_left_day;
int end = getThemeTag() == -1 ? thumb_margin_left_day : thumb_margin_left_night;
ValueAnimator animator = ValueAnimator.ofInt(start, end);
return animator;
}
/**
* 退出程序
*/
private void buckUpApp() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
/**
* 关于的方法
*/
private void navAbout() {
Intent intent = new Intent(mActivity, AboutActivity.class);
mActivity.startActivity(intent);
}
/**
* 刷新当前页面的数据
*/
private void refresh() {
onResume();
}
//在onResume()方法注册
@Override
protected void onResume() {
super.onResume();
setOperatorInfo("check_select = ?", mTvOperatorCheckMain);
setOperatorInfo("login_select = ?", mTvOperatorLoginMain);
mTvChangeLaneMain.setText((String) SPUtils.get(this, SPUtils.TEXTLANE, "66"));
mTvMathNumberDraft.setText(SPUtils.get(this, SPUtils.MATH_DRAFT_LITE, 0) + "");
mTvMathNumberSubmit.setText(SPUtils.get(this, SPUtils.MATH_SUBMIT_LITE, 0) + "");
//注册广播,接收service中启动的线程发送过来的信息,同时更新UI
IntentFilter filter = new IntentFilter("com.example.updateUI");
mBroadCaseReceiver = new MyBroadCaseReceiver();
registerReceiver(mBroadCaseReceiver, filter);
}
private void setOperatorInfo(String condition, TextView textView) {
List<SupportOperator> operatorList = DataSupport.where(condition, "1").find(SupportOperator.class);
//ArrayList<String> checkOperatorList = new ArrayList<>();
String operator = "";
if (operatorList.size() != 0) {
for (int i = 0; i < operatorList.size(); i++) {
String job_number = operatorList.get(i).getJob_number();
String operator_name = operatorList.get(i).getOperator_name();
if (i == 0) {
operator = job_number + "/" + operator_name;
} else {
operator=operator+"\n"+job_number + "/" + operator_name;
}
}
} else {
operator = "500001/苏三";
}
Logger.i(operator);
if (operatorList.size() == 3) {
textView.setTextSize(CommonUtils.sp2px(this, 7));
} else {
textView.setTextSize(CommonUtils.sp2px(this, 9));
}
textView.setText(operator);
}
//onPause()方法注销
@Override
protected void onPause() {
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - firstClick > 2000) {
firstClick = System.currentTimeMillis();
Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
} else {
ActivityCollector.finishAll();
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
// return super.onKeyDown(keyCode, event);
}
return true;
}
return false;
}
/**
* 根据版本号判断要不要更新
*/
private void updateApp() {
String version = DevicesInfoUtils.getInstance().getVersion(mActivity);
CheckUpdateUtils.checkUpdate("GreenRoad.apk", version,
new CheckUpdateUtils.CheckCallBack() {
@Override
public void onSuccess(UpdateAppInfo updateInfo) {
String isForce = updateInfo.getData().getLastfalse();//是否需要强制更新
String downUrl = updateInfo.getData().getDownloadurl();//apk下载地址
String updateinfo = updateInfo.getData().getUpdateinfo();//apk更新详情
String appName = updateInfo.getData().getAppname();
Logger.i(isForce + "------" + downUrl + " -----"
+ updateinfo + " -----" + appName);
if (("1".equals(isForce)) && !TextUtils.isEmpty(updateinfo)) {//强制更新
Logger.i("强制更新");
forceUpdate(MainActivity.this, appName, downUrl, updateinfo);
} else {//非强制更新
//正常升级
Logger.i("正常升级");
normalUpdate(MainActivity.this, appName, downUrl, updateinfo);
}
}
@Override
public void onError() {
noneUpdate(MainActivity.this);
Logger.i("返回信息为空,更新错误!");
}
});
}
/**
* 强制更新
*
* @param context
* @param appName
* @param downUrl
* @param updateinfo
*/
private void forceUpdate(final Context context, final String appName, final String downUrl, final String updateinfo) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle(appName + "又更新咯!");
mDialog.setMessage(updateinfo);
mDialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!canDownloadState()) {
Logger.i("立即更新,,,,当前手机状态是否为可下载状态");
showDownloadSetting();
return;
}
// DownLoadApk.download(MainActivity.this,downUrl,updateinfo,appName);
AppInnerDownLoder.downLoadApk(MainActivity.this, downUrl, appName);
}
}).setCancelable(false).create().show();
}
/**
* 正常更新
*
* @param context
* @param appName
* @param downUrl
* @param updateinfo
*/
private void normalUpdate(Context context, final String appName, final String downUrl, final String updateinfo) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle(appName + "又更新咯!");
mDialog.setMessage(updateinfo);
mDialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!canDownloadState()) {
showDownloadSetting();
return;
}
AppInnerDownLoder.downLoadApk(context, downUrl, appName);
// DownLoadApk.download(MainActivity.this,downUrl,updateinfo,appName);
}
}).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setCancelable(false).create().show();
}
/**
* 无需跟新
*
* @param context
*/
private void noneUpdate(Context context) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle("版本更新")
.setMessage("当前已是最新版本无需更新")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
})
.setCancelable(false).create().show();
}
private void showDownloadSetting() {
String packageName = "com.android.providers.downloads";
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + packageName));
if (intentAvailable(intent)) {
startActivity(intent);
}
}
private boolean intentAvailable(Intent intent) {
PackageManager packageManager = getPackageManager();
List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private boolean canDownloadState() {
try {
int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@OnClick(R.id.footer_item_setting)
public void onSetting(View view) {
ToastUtils.singleToast("点击了设置");
}
@Override
protected void onDestroy() {
super.onDestroy();
// mLocalBroadcastManager.unregisterReceiver(mPostReceiver);
Logger.i("mainactivity被销毁");
// PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
unregisterReceiver(mBroadCaseReceiver);
}
private void openSettingActivity() {
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
}
public static void notifyAndRefreshMath() {
// mTvMathNumberSubmit.setText(SPUtils.get(MainActivity.this, SPUtils.MATH_SUBMIT_LITE, 0) + "");
}
class MyBroadCaseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
int draft = intent.getIntExtra(SubmitService.ARG_BROADCAST_DRAFT, 0);
int submit = intent.getIntExtra(SubmitService.ARG_BROADCAST_SUBMIT, 0);
mTvMathNumberDraft.setText(draft+"");
mTvMathNumberSubmit.setText(submit+"");
}
}
}
| UTF-8 | Java | 23,914 | java | MainActivity.java | Java | [] | null | [] | package com.android.htc.greenroad.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.htc.greenroad.manager.GlobalManager;
import com.orhanobut.logger.Logger;
import com.android.htc.greenroad.R;
import com.android.htc.greenroad.bean.UpdateAppInfo;
import com.android.htc.greenroad.httpresultbean.HttpResultMacInfo;
import com.android.htc.greenroad.https.RequestMacInfo;
import com.android.htc.greenroad.litepalbean.SupportOperator;
import com.android.htc.greenroad.servicy.BlackListService;
import com.android.htc.greenroad.servicy.SubmitService;
import com.android.htc.greenroad.tools.ActionBarTool;
import com.android.htc.greenroad.tools.ActivityCollector;
import com.android.htc.greenroad.tools.CommonUtils;
import com.android.htc.greenroad.tools.DevicesInfoUtils;
import com.android.htc.greenroad.tools.PermissionUtils;
import com.android.htc.greenroad.tools.SDcardSpace;
import com.android.htc.greenroad.tools.SPListUtil;
import com.android.htc.greenroad.tools.SPUtils;
import com.android.htc.greenroad.tools.ToastUtils;
import com.android.htc.greenroad.update.AppInnerDownLoder;
import com.android.htc.greenroad.update.CheckUpdateUtils;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;
/**
* Created by Administrator on 2017/6/20.
*/
public class MainActivity extends BaseActivity implements
NavigationView.OnNavigationItemSelectedListener{
@BindView(R.id.toolbar_main)
Toolbar mToolbarMain;
@BindView(R.id.drawer_layout)
DrawerLayout mDrawerLayout;
@BindView(R.id.nav_view)
NavigationView mNavView;
@BindView(R.id.tv_change_station_main)
TextView mTvChangeStationMain;
@BindView(R.id.tv_change_lane_main)
TextView mTvChangeLaneMain;
@BindView(R.id.tv_operator_check_main)
TextView mTvOperatorCheckMain;
@BindView(R.id.tv_operator_login_main)
TextView mTvOperatorLoginMain;
@BindView(R.id.rl_main_draft)
RelativeLayout mRlMainDraft;
@BindView(R.id.rl_main_submit)
RelativeLayout mRlMainSubmit;
@BindView(R.id.tv_math_number_draft)
TextView mTvMathNumberDraft;
private static TextView mTvMathNumberSubmit;
@BindView(R.id.tv_avail_space)
TextView mTvAvailSpace;
@BindView(R.id.tv_all_space)
TextView mTvAllSpace;
@BindView(R.id.tv_math_number_blacklist)
TextView mTvMathNumberBlacklist;
@BindView(R.id.rl_main_blacklist)
RelativeLayout mRlMainBlacklist;
private long firstClick;
private static final String TAG = "MainActivity";
private static final int REQ_0 = 001;
@BindView(R.id.footer_item_setting)
TextView mTv_footer_setting;
@BindView(R.id.footer_item_theme)
TextView mTv_footer_theme;
@BindView(R.id.footer_item_location)
TextView mTv_footer_location;
private AppCompatActivity mActivity;
private AlertDialog.Builder mDialog;
private AlertDialog.Builder mNotPostDialog;
private int thumb_margin_left_day = 0;
private int thumb_margin_left_night = 0;
private String mRoad_Q;
private String mStation_Q;
private String mAvailSpace;
private String mAllSpace;
private String macID;
private MyBroadCaseReceiver mBroadCaseReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mActivity = this;
mTvOperatorCheckMain = (TextView) findViewById(R.id.tv_operator_check_main);
mTvOperatorLoginMain = (TextView) findViewById(R.id.tv_operator_login_main);
mTvMathNumberSubmit = (TextView) findViewById(R.id.tv_math_number_submit);
mTvChangeLaneMain.setOnClickListener(v -> openSettingActivity());
mTvOperatorCheckMain.setOnClickListener(v -> openSettingActivity());
mTvOperatorLoginMain.setOnClickListener(v -> openSettingActivity());
initSpace();
initData();
//initSp();
initView();
}
@OnClick({R.id.rl_main_draft, R.id.rl_main_submit, R.id.rl_main_blacklist, R.id.btn_enter_show})
public void onClick(View view) {
switch (view.getId()) {
case R.id.rl_main_draft:
Intent intent = new Intent(MainActivity.this, DraftActivity.class);
startActivity(intent);
break;
case R.id.rl_main_submit:
Intent intent1 = new Intent(MainActivity.this, SubmitActivity.class);
startActivity(intent1);
break;
case R.id.rl_main_blacklist:
Intent intent2 = new Intent(MainActivity.this, BlackListActivity.class);
startActivity(intent2);
break;
case R.id.btn_enter_show:
List<SupportOperator> check = DataSupport.where("check_select=?", "1").
find(SupportOperator.class);
List<SupportOperator> login = DataSupport.where("login_select=?", "1").
find(SupportOperator.class);
if (check.size() >= 1 && login.size() == 1) {
ShowActivity.actionStart(MainActivity.this);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("确定选择默认检查人/登记人");
builder.setMessage("点击确定进入设置界面添加默认操作员;\n" +
"点击取消则回到界面,不可以采集车辆数据");
builder.setPositiveButton("确定", (dialog, which) -> {
openSettingActivity();
});
builder.setNegativeButton("取消", (dialog, which) -> {
dialog.dismiss();
});
builder.show();
// ToastUtils.singleToast("目前请添加操作员");
break;
}
break;
default:
break;
}
}
private void initSpace() {
SDcardSpace sDcardSpace = new SDcardSpace(mActivity);
mAvailSpace = sDcardSpace.getAvailSpace();
// mAllSpace = sDcardSpace.getAllSpace();
mAllSpace = sDcardSpace.getSDTotalSize(mActivity);
mTvAllSpace.setText(" / " + mAllSpace);
mTvAvailSpace.setText(mAvailSpace + "");
}
private void initData() {
PermissionUtils.verifyStoragePermissions(mActivity);
BlackListService.startActionBlack(this, mTvMathNumberBlacklist);
macID = Settings.Secure
.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
List<String> strListValue = SPListUtil.getStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO);
if (strListValue == null || strListValue.size() != 3) {
RequestMacInfo.getInstance().getMacInfo(new Subscriber<HttpResultMacInfo>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Logger.i(e.getMessage());
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, null);
}
@Override
public void onNext(HttpResultMacInfo httpResultMacInfo) {
int code = httpResultMacInfo.getCode();
Logger.i(code + "");
HttpResultMacInfo.DataBean dataBean = httpResultMacInfo.getData();
Logger.i(dataBean.toString());
if (code == 200) {
List app_config_info = new ArrayList<String>();
app_config_info.add(dataBean.getName());
app_config_info.add(dataBean.getTerminal_road());
app_config_info.add(dataBean.getTerminal_site());
Logger.i(app_config_info.toString());
mTvChangeStationMain.setText(dataBean.getTerminal_road());
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, app_config_info);
} else {
SPListUtil.putStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO, null);
}
}
}, macID);
}
List<String> new_ListValue = SPListUtil.getStrListValue(MainActivity.this, SPListUtil.APPCONFIGINFO);
for (int i = 0; i < new_ListValue.size(); i++) {
String string = new_ListValue.get(i).toString();
Logger.i(string);
}
if (new_ListValue.size() == 3) {
mTvChangeStationMain.setText(new_ListValue.get(2));
}
}
private void initView() {
setSupportActionBar(mToolbarMain);
TextView title_text_view = ActionBarTool.getInstance(mActivity, 991).getTitle_text_view();
title_text_view.setText("绿通车登记");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, mToolbarMain, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@OnClick({R.id.footer_item_setting,
R.id.footer_item_theme, R.id.footer_item_location})
public void onFooterClick(View view) {
switch (view.getId()) {
case R.id.footer_item_setting:
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
break;
case R.id.footer_item_theme:
changeTheme();
break;
case R.id.footer_item_location:
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_about) {
navAbout();
} else if (id == R.id.nav_update) {
Logger.i("点击了更新按钮");
updateApp();
} else if (id == R.id.nav_backup) {
buckUpApp();
} else if (id == R.id.nav_config) {
// post_not_upload();
openConfigLine();
// Logger.i("点击了代开配置路线的按钮");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* 做配置路线的处理
*/
private void openConfigLine() {
LineConfigActivity.actionStart(MainActivity.this, GlobalManager.OTHER2PORT);
}
/**
* 点击主题菜单按钮改变App的主题
* /**
* 切换主题时展示动画
*/
private void changeTheme() {
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.setDuration(240);
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Intent intent = new Intent(getContext(), AnimatorActivity.class);
finish();
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
});
animatorSet.play(obtainCheckboxAnimator());
animatorSet.start();
}
private Animator obtainCheckboxAnimator() {
int start = getThemeTag() == -1 ? thumb_margin_left_night : thumb_margin_left_day;
int end = getThemeTag() == -1 ? thumb_margin_left_day : thumb_margin_left_night;
ValueAnimator animator = ValueAnimator.ofInt(start, end);
return animator;
}
/**
* 退出程序
*/
private void buckUpApp() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
/**
* 关于的方法
*/
private void navAbout() {
Intent intent = new Intent(mActivity, AboutActivity.class);
mActivity.startActivity(intent);
}
/**
* 刷新当前页面的数据
*/
private void refresh() {
onResume();
}
//在onResume()方法注册
@Override
protected void onResume() {
super.onResume();
setOperatorInfo("check_select = ?", mTvOperatorCheckMain);
setOperatorInfo("login_select = ?", mTvOperatorLoginMain);
mTvChangeLaneMain.setText((String) SPUtils.get(this, SPUtils.TEXTLANE, "66"));
mTvMathNumberDraft.setText(SPUtils.get(this, SPUtils.MATH_DRAFT_LITE, 0) + "");
mTvMathNumberSubmit.setText(SPUtils.get(this, SPUtils.MATH_SUBMIT_LITE, 0) + "");
//注册广播,接收service中启动的线程发送过来的信息,同时更新UI
IntentFilter filter = new IntentFilter("com.example.updateUI");
mBroadCaseReceiver = new MyBroadCaseReceiver();
registerReceiver(mBroadCaseReceiver, filter);
}
private void setOperatorInfo(String condition, TextView textView) {
List<SupportOperator> operatorList = DataSupport.where(condition, "1").find(SupportOperator.class);
//ArrayList<String> checkOperatorList = new ArrayList<>();
String operator = "";
if (operatorList.size() != 0) {
for (int i = 0; i < operatorList.size(); i++) {
String job_number = operatorList.get(i).getJob_number();
String operator_name = operatorList.get(i).getOperator_name();
if (i == 0) {
operator = job_number + "/" + operator_name;
} else {
operator=operator+"\n"+job_number + "/" + operator_name;
}
}
} else {
operator = "500001/苏三";
}
Logger.i(operator);
if (operatorList.size() == 3) {
textView.setTextSize(CommonUtils.sp2px(this, 7));
} else {
textView.setTextSize(CommonUtils.sp2px(this, 9));
}
textView.setText(operator);
}
//onPause()方法注销
@Override
protected void onPause() {
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (System.currentTimeMillis() - firstClick > 2000) {
firstClick = System.currentTimeMillis();
Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
} else {
ActivityCollector.finishAll();
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
// return super.onKeyDown(keyCode, event);
}
return true;
}
return false;
}
/**
* 根据版本号判断要不要更新
*/
private void updateApp() {
String version = DevicesInfoUtils.getInstance().getVersion(mActivity);
CheckUpdateUtils.checkUpdate("GreenRoad.apk", version,
new CheckUpdateUtils.CheckCallBack() {
@Override
public void onSuccess(UpdateAppInfo updateInfo) {
String isForce = updateInfo.getData().getLastfalse();//是否需要强制更新
String downUrl = updateInfo.getData().getDownloadurl();//apk下载地址
String updateinfo = updateInfo.getData().getUpdateinfo();//apk更新详情
String appName = updateInfo.getData().getAppname();
Logger.i(isForce + "------" + downUrl + " -----"
+ updateinfo + " -----" + appName);
if (("1".equals(isForce)) && !TextUtils.isEmpty(updateinfo)) {//强制更新
Logger.i("强制更新");
forceUpdate(MainActivity.this, appName, downUrl, updateinfo);
} else {//非强制更新
//正常升级
Logger.i("正常升级");
normalUpdate(MainActivity.this, appName, downUrl, updateinfo);
}
}
@Override
public void onError() {
noneUpdate(MainActivity.this);
Logger.i("返回信息为空,更新错误!");
}
});
}
/**
* 强制更新
*
* @param context
* @param appName
* @param downUrl
* @param updateinfo
*/
private void forceUpdate(final Context context, final String appName, final String downUrl, final String updateinfo) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle(appName + "又更新咯!");
mDialog.setMessage(updateinfo);
mDialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!canDownloadState()) {
Logger.i("立即更新,,,,当前手机状态是否为可下载状态");
showDownloadSetting();
return;
}
// DownLoadApk.download(MainActivity.this,downUrl,updateinfo,appName);
AppInnerDownLoder.downLoadApk(MainActivity.this, downUrl, appName);
}
}).setCancelable(false).create().show();
}
/**
* 正常更新
*
* @param context
* @param appName
* @param downUrl
* @param updateinfo
*/
private void normalUpdate(Context context, final String appName, final String downUrl, final String updateinfo) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle(appName + "又更新咯!");
mDialog.setMessage(updateinfo);
mDialog.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!canDownloadState()) {
showDownloadSetting();
return;
}
AppInnerDownLoder.downLoadApk(context, downUrl, appName);
// DownLoadApk.download(MainActivity.this,downUrl,updateinfo,appName);
}
}).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setCancelable(false).create().show();
}
/**
* 无需跟新
*
* @param context
*/
private void noneUpdate(Context context) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle("版本更新")
.setMessage("当前已是最新版本无需更新")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
})
.setCancelable(false).create().show();
}
private void showDownloadSetting() {
String packageName = "com.android.providers.downloads";
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + packageName));
if (intentAvailable(intent)) {
startActivity(intent);
}
}
private boolean intentAvailable(Intent intent) {
PackageManager packageManager = getPackageManager();
List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private boolean canDownloadState() {
try {
int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@OnClick(R.id.footer_item_setting)
public void onSetting(View view) {
ToastUtils.singleToast("点击了设置");
}
@Override
protected void onDestroy() {
super.onDestroy();
// mLocalBroadcastManager.unregisterReceiver(mPostReceiver);
Logger.i("mainactivity被销毁");
// PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
unregisterReceiver(mBroadCaseReceiver);
}
private void openSettingActivity() {
Intent intent = new Intent(this, SettingActivity.class);
startActivity(intent);
}
public static void notifyAndRefreshMath() {
// mTvMathNumberSubmit.setText(SPUtils.get(MainActivity.this, SPUtils.MATH_SUBMIT_LITE, 0) + "");
}
class MyBroadCaseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
int draft = intent.getIntExtra(SubmitService.ARG_BROADCAST_DRAFT, 0);
int submit = intent.getIntExtra(SubmitService.ARG_BROADCAST_SUBMIT, 0);
mTvMathNumberDraft.setText(draft+"");
mTvMathNumberSubmit.setText(submit+"");
}
}
}
| 23,914 | 0.603889 | 0.600798 | 666 | 33.975975 | 27.426659 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615616 | false | false | 9 |
4b810d1ee0c90e2275c7b20495352ad5bec42a6b | 4,363,686,821,021 | 4f13b478716a818c34792955a1dd1852e8d6e3b7 | /loja3/src/main/java/br/senac/rn/loja/Loja3Application.java | 638d95ff3de0e6bf6c40b2073563190d3f4b5c6b | [] | no_license | irancruz/loja-antiga | https://github.com/irancruz/loja-antiga | 6b838b26b6ed6482a91919aef6a1bcc2ea80b0ab | 760cae9257e2993538f3ded82656cdb3a991c0c1 | refs/heads/master | 2020-03-28T16:36:35.977000 | 2018-10-03T00:23:27 | 2018-10-03T00:23:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.senac.rn.loja;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//public class Loja3Application implements CommandLineRunner{
public class Loja3Application {
public static void main(String[] args) {
SpringApplication.run(Loja3Application.class);
}
//versão para teste no console
/* @Autowired
private MarcaRepository repository;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Loja3Application.class);
app.run(args);
}*/
/* @Override
public void run(String... args) throws Exception {
System.out.println(repository.buscaPorNome("n%"));
}
*/
}
| UTF-8 | Java | 723 | java | Loja3Application.java | Java | [] | null | [] | package br.senac.rn.loja;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//public class Loja3Application implements CommandLineRunner{
public class Loja3Application {
public static void main(String[] args) {
SpringApplication.run(Loja3Application.class);
}
//versão para teste no console
/* @Autowired
private MarcaRepository repository;
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Loja3Application.class);
app.run(args);
}*/
/* @Override
public void run(String... args) throws Exception {
System.out.println(repository.buscaPorNome("n%"));
}
*/
}
| 723 | 0.763158 | 0.757618 | 30 | 23.066668 | 23.181793 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.233333 | false | false | 9 |
3ac800c32cabd4b2c811edd7b5308640aad717c6 | 9,174,050,197,226 | 765c357ea03262e568852cbaaef47755b8b7e6ea | /src/chapter8/CountingSort.java | d04cae9345106cb0ecc91e67aa6e87c79441351d | [] | no_license | YinZe0/CLRS | https://github.com/YinZe0/CLRS | 94beb826c67cf378f61ac5e95dd7776413001cc7 | 68aa60bc38644a89232cd64e860ef278f1562dbf | refs/heads/master | 2021-10-14T08:20:08.308000 | 2019-02-03T02:43:07 | 2019-02-03T02:43:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package introduction.chapter8;
import introduction.Util;
import java.util.Arrays;
/**
* 计数排序
*/
public class CountingSort {
/*
伪代码(书上拿过来的) 如下写法需要确认B和C数组的容量问题 如果随机的数字过大。。。
CountingSort(A, B, k)
let C[0..k] be a new array
for i = 0 to k
C[i] = 0
经过如下循环 C[i]包含了等于i的元素数
for j = 1 to A.length
C[A[j]] = C[A[j]] + 1
经过如下循环 C[i]包含了小于等于i的元素数
for i = 1 to k
C[i] = C[i] + C[i - 1]
for j = A.length downto 1
B[C[A[j]]] = A[j]
C[A[j]] = C[A[j]] - 1
*/
/**
* 没有处理负数 目前只支持0 U 正整数
*/
public static void main(String[] args) {
int bound = 100;
int[] ints = Util.init(50, 0, bound);
System.out.println("before: " + Arrays.toString(ints));
ints = countingSort(ints, bound);
System.out.println("after: " + Arrays.toString(ints));
}
/**
* 计数排序
*
* @param ints 待排序数组
* @param maxValue 数组中的最大值
* @return 一个新的数组
*/
private static int[] countingSort(int[] ints, int maxValue) {
int[] b = new int[ints.length]; // 排序后的
int[] c = new int[maxValue]; // 计数器
for (int anInt : ints) {
c[anInt] = c[anInt] + 1;
}
for (int i = 1; i < c.length; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = ints.length - 1; i >= 0; i--) {
b[c[ints[i]] - 1] = ints[i];
c[ints[i]] = c[ints[i]] - 1;
}
return b;
}
}
| UTF-8 | Java | 1,767 | java | CountingSort.java | Java | [] | null | [] | package introduction.chapter8;
import introduction.Util;
import java.util.Arrays;
/**
* 计数排序
*/
public class CountingSort {
/*
伪代码(书上拿过来的) 如下写法需要确认B和C数组的容量问题 如果随机的数字过大。。。
CountingSort(A, B, k)
let C[0..k] be a new array
for i = 0 to k
C[i] = 0
经过如下循环 C[i]包含了等于i的元素数
for j = 1 to A.length
C[A[j]] = C[A[j]] + 1
经过如下循环 C[i]包含了小于等于i的元素数
for i = 1 to k
C[i] = C[i] + C[i - 1]
for j = A.length downto 1
B[C[A[j]]] = A[j]
C[A[j]] = C[A[j]] - 1
*/
/**
* 没有处理负数 目前只支持0 U 正整数
*/
public static void main(String[] args) {
int bound = 100;
int[] ints = Util.init(50, 0, bound);
System.out.println("before: " + Arrays.toString(ints));
ints = countingSort(ints, bound);
System.out.println("after: " + Arrays.toString(ints));
}
/**
* 计数排序
*
* @param ints 待排序数组
* @param maxValue 数组中的最大值
* @return 一个新的数组
*/
private static int[] countingSort(int[] ints, int maxValue) {
int[] b = new int[ints.length]; // 排序后的
int[] c = new int[maxValue]; // 计数器
for (int anInt : ints) {
c[anInt] = c[anInt] + 1;
}
for (int i = 1; i < c.length; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = ints.length - 1; i >= 0; i--) {
b[c[ints[i]] - 1] = ints[i];
c[ints[i]] = c[ints[i]] - 1;
}
return b;
}
}
| 1,767 | 0.463192 | 0.447557 | 61 | 24.163935 | 17.325411 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409836 | false | false | 9 |
049e3098f524bd39bf2fd9d19696e82e5c6d0d80 | 17,300,128,320,206 | 878dbc6f46c9f429bb9ce4a12f2da73bc91aa2b0 | /Tree.java | e33cc892dba70ac5bbcefdf63746e89634b21466 | [] | no_license | Rumaesa/java-programs | https://github.com/Rumaesa/java-programs | 30d90ca85dcb9a310b26e065a13a11988c210593 | 6c41be0d822109d578cbca76c630ac05dda098d5 | refs/heads/master | 2020-09-24T20:34:41.366000 | 2019-12-04T10:18:53 | 2019-12-04T10:18:53 | 225,837,225 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
class Tree
{
int no;
double height, base, amount;
Tree(int num, double ht, double bs, double amt)
{
no=num;
height=ht;
base=bs;
amount=amt;
}
void update()
{
height=height+3;
base=base+2;
amount=amount+100;
}
void display()
{
System.out.println("TREE");
System.out.println("Tree Code "+no);
System.out.println("Height of a tree is "+height);
System.out.println("Base of a tree is "+base);
System.out.println("Amount spent so far on a tree is "+amount);
}
}
class MangoTree extends Tree
{
double yield;
MangoTree(int num, double ht, double bs, double amt, double yd)
{
super(num,ht,bs,amt);
yield=yd;
}
void update()
{
height=height+3;
base=base+2;
amount=amount+100;
yield=yield+2.3;
}
void display()
{
System.out.println("MANGO TREE");
System.out.println("Tree Code "+no);
System.out.println("Height of a tree is "+height);
System.out.println("Base of a tree is "+base);
System.out.println("Yield is "+yield);
System.out.println("Amount spent so far on a tree is "+amount);
}
}
class Garden
{
public static void main(String args[])
{
Tree t= new Tree(1, 4.5, 2.3, 2000);
t.update();
t.display();
MangoTree mt= new MangoTree(2, 5.8, 2.1, 3000, 4.55);
mt.update();
mt.display();
}
}
| UTF-8 | Java | 1,284 | java | Tree.java | Java | [] | null | [] | import java.io.*;
class Tree
{
int no;
double height, base, amount;
Tree(int num, double ht, double bs, double amt)
{
no=num;
height=ht;
base=bs;
amount=amt;
}
void update()
{
height=height+3;
base=base+2;
amount=amount+100;
}
void display()
{
System.out.println("TREE");
System.out.println("Tree Code "+no);
System.out.println("Height of a tree is "+height);
System.out.println("Base of a tree is "+base);
System.out.println("Amount spent so far on a tree is "+amount);
}
}
class MangoTree extends Tree
{
double yield;
MangoTree(int num, double ht, double bs, double amt, double yd)
{
super(num,ht,bs,amt);
yield=yd;
}
void update()
{
height=height+3;
base=base+2;
amount=amount+100;
yield=yield+2.3;
}
void display()
{
System.out.println("MANGO TREE");
System.out.println("Tree Code "+no);
System.out.println("Height of a tree is "+height);
System.out.println("Base of a tree is "+base);
System.out.println("Yield is "+yield);
System.out.println("Amount spent so far on a tree is "+amount);
}
}
class Garden
{
public static void main(String args[])
{
Tree t= new Tree(1, 4.5, 2.3, 2000);
t.update();
t.display();
MangoTree mt= new MangoTree(2, 5.8, 2.1, 3000, 4.55);
mt.update();
mt.display();
}
}
| 1,284 | 0.648754 | 0.623053 | 71 | 16.084507 | 17.947298 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746479 | false | false | 9 |
b5540d3cdd1c0930c322299efdab4914e8cf7ca5 | 10,780,367,972,802 | 963ffb56c7484c7b2ba3566eff91087fbd56fdd3 | /src/com/eyunda/third/domain/oil/GasOrderData.java | b0d1b3b78d1ff06720aa2cd25705409faf3feaa3 | [] | no_license | leif228/hyclient | https://github.com/leif228/hyclient | 83953b1cf588dad1269589974f63aa95f194d044 | 25acc09f3e2ea60270d1669a3161fb676eb52a89 | refs/heads/master | 2020-05-20T11:31:56.251000 | 2019-05-08T06:57:15 | 2019-05-08T06:57:15 | 185,549,816 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.eyunda.third.domain.oil;
import java.util.Map;
import com.eyunda.third.domain.BaseData;
import com.eyunda.third.domain.account.UserData;
import com.eyunda.third.domain.enumeric.BuyOilStatusCode;
public class GasOrderData extends BaseData {
private static final long serialVersionUID = 1L;
private Long id = 0L;
private Long companyId = 0L; // 卖家公司Id
private GasCompanyData company = null;
private Long waresId = 0L; // 商品Id
private GasWaresData gasWaresData = null;
private Long carrierId = 0L; // 买家承运人Id
private UserData carrier = null;
private String description = ""; // 订单描述
private String orderTime = ""; // 下单时间
private Double saleCount = 0.00D; // 购买数量
private Double price = 0.00D; // 交易价格
private Double tradeMoney = 0.00D; // 交易金额
private BuyOilStatusCode status = BuyOilStatusCode.edit; // 状态
private Long adminId = 0L; // 操作员Id
private AdminInfoData admin = null;
@SuppressWarnings("unchecked")
public GasOrderData(Map<String, Object> params){
super();
if (params != null && !params.isEmpty()) {
this.id = ((Double) params.get("id")).longValue();
this.companyId = ((Double) params.get("companyId")).longValue();
this.company = new GasCompanyData((Map<String, Object>) params.get("company"));
this.waresId = ((Double) params.get("waresId")).longValue();
this.gasWaresData = new GasWaresData((Map<String, Object>) params.get("gasWaresData"));
this.carrierId = ((Double) params.get("carrierId")).longValue();
this.carrier = new UserData((Map<String, Object>) params.get("carrier"));
this.description = (String) params.get("description");
this.orderTime = (String) params.get("orderTime");
this.saleCount = (Double) params.get("saleCount");
this.price = (Double) params.get("price");
this.tradeMoney = (Double) params.get("tradeMoney");
this.adminId = ((Double) params.get("adminId")).longValue();
this.admin = new AdminInfoData((Map<String, Object>) params.get("admin"));
String status = (String) params.get("status");
if ((status != null) && (!status.equals(""))) {
this.status = BuyOilStatusCode.valueOf(status);
}
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
public GasCompanyData getCompany() {
return company;
}
public void setCompany(GasCompanyData companyData) {
this.company = companyData;
}
public Long getWaresId() {
return waresId;
}
public void setWaresId(Long waresId) {
this.waresId = waresId;
}
public GasWaresData getGasWaresData() {
return gasWaresData;
}
public void setGasWaresData(GasWaresData gasWaresData) {
this.gasWaresData = gasWaresData;
}
public Long getCarrierId() {
return carrierId;
}
public void setCarrierId(Long carrierId) {
this.carrierId = carrierId;
}
public UserData getCarrier() {
return carrier;
}
public void setCarrier(UserData carrier) {
this.carrier = carrier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public Double getSaleCount() {
return saleCount;
}
public void setSaleCount(Double saleCount) {
this.saleCount = saleCount;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getTradeMoney() {
return tradeMoney;
}
public void setTradeMoney(Double tradeMoney) {
this.tradeMoney = tradeMoney;
}
public BuyOilStatusCode getStatus() {
return status;
}
public void setStatus(BuyOilStatusCode status) {
this.status = status;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public AdminInfoData getAdmin() {
return admin;
}
public void setAdmin(AdminInfoData admin) {
this.admin = admin;
}
}
| UTF-8 | Java | 4,366 | java | GasOrderData.java | Java | [] | null | [] | package com.eyunda.third.domain.oil;
import java.util.Map;
import com.eyunda.third.domain.BaseData;
import com.eyunda.third.domain.account.UserData;
import com.eyunda.third.domain.enumeric.BuyOilStatusCode;
public class GasOrderData extends BaseData {
private static final long serialVersionUID = 1L;
private Long id = 0L;
private Long companyId = 0L; // 卖家公司Id
private GasCompanyData company = null;
private Long waresId = 0L; // 商品Id
private GasWaresData gasWaresData = null;
private Long carrierId = 0L; // 买家承运人Id
private UserData carrier = null;
private String description = ""; // 订单描述
private String orderTime = ""; // 下单时间
private Double saleCount = 0.00D; // 购买数量
private Double price = 0.00D; // 交易价格
private Double tradeMoney = 0.00D; // 交易金额
private BuyOilStatusCode status = BuyOilStatusCode.edit; // 状态
private Long adminId = 0L; // 操作员Id
private AdminInfoData admin = null;
@SuppressWarnings("unchecked")
public GasOrderData(Map<String, Object> params){
super();
if (params != null && !params.isEmpty()) {
this.id = ((Double) params.get("id")).longValue();
this.companyId = ((Double) params.get("companyId")).longValue();
this.company = new GasCompanyData((Map<String, Object>) params.get("company"));
this.waresId = ((Double) params.get("waresId")).longValue();
this.gasWaresData = new GasWaresData((Map<String, Object>) params.get("gasWaresData"));
this.carrierId = ((Double) params.get("carrierId")).longValue();
this.carrier = new UserData((Map<String, Object>) params.get("carrier"));
this.description = (String) params.get("description");
this.orderTime = (String) params.get("orderTime");
this.saleCount = (Double) params.get("saleCount");
this.price = (Double) params.get("price");
this.tradeMoney = (Double) params.get("tradeMoney");
this.adminId = ((Double) params.get("adminId")).longValue();
this.admin = new AdminInfoData((Map<String, Object>) params.get("admin"));
String status = (String) params.get("status");
if ((status != null) && (!status.equals(""))) {
this.status = BuyOilStatusCode.valueOf(status);
}
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCompanyId() {
return companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
public GasCompanyData getCompany() {
return company;
}
public void setCompany(GasCompanyData companyData) {
this.company = companyData;
}
public Long getWaresId() {
return waresId;
}
public void setWaresId(Long waresId) {
this.waresId = waresId;
}
public GasWaresData getGasWaresData() {
return gasWaresData;
}
public void setGasWaresData(GasWaresData gasWaresData) {
this.gasWaresData = gasWaresData;
}
public Long getCarrierId() {
return carrierId;
}
public void setCarrierId(Long carrierId) {
this.carrierId = carrierId;
}
public UserData getCarrier() {
return carrier;
}
public void setCarrier(UserData carrier) {
this.carrier = carrier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public Double getSaleCount() {
return saleCount;
}
public void setSaleCount(Double saleCount) {
this.saleCount = saleCount;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Double getTradeMoney() {
return tradeMoney;
}
public void setTradeMoney(Double tradeMoney) {
this.tradeMoney = tradeMoney;
}
public BuyOilStatusCode getStatus() {
return status;
}
public void setStatus(BuyOilStatusCode status) {
this.status = status;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public AdminInfoData getAdmin() {
return admin;
}
public void setAdmin(AdminInfoData admin) {
this.admin = admin;
}
}
| 4,366 | 0.67606 | 0.672566 | 179 | 21.988827 | 21.723501 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.547486 | false | false | 9 |
37c74f5c5caf4d24333fcfe8f79c51d4fff12976 | 21,457,656,669,660 | 80e732ad3538b57383eba484c9b6b856642b813c | /PantallasListados/app/src/main/java/com/example/pantallaslistados/Objetos/Catedratico.java | 9966fb111142dcef0505591251fd91bf8b431f75 | [] | no_license | MiriamMondragon/Pantallas_Listado | https://github.com/MiriamMondragon/Pantallas_Listado | 4d38564f4ffb8942ddb2689e6a887201f06d4694 | bb4e2e578e976f569d8579ace94b06357b6ec869 | refs/heads/master | 2023-06-29T20:05:58.466000 | 2021-07-29T19:43:52 | 2021-07-29T19:43:52 | 390,833,037 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.pantallaslistados.Objetos;
public class Catedratico {
private String id;
private String nombre;
private String telefono;
private String fechaNacimiento;
private String direccion;
private String foto;
private String correo;
public Catedratico() {
}
public Catedratico(String nombre, String telefono, String foto, String correo) {
this.nombre = nombre;
this.telefono = telefono;
this.foto = foto;
this.correo = correo;
}
public Catedratico(String id, String nombre, String telefono, String fechaNacimiento, String direccion, String foto, String correo) {
this.id = id;
this.nombre = nombre;
this.telefono = telefono;
this.fechaNacimiento = fechaNacimiento;
this.direccion = direccion;
this.foto = foto;
this.correo = correo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
}
| UTF-8 | Java | 1,933 | java | Catedratico.java | Java | [] | null | [] | package com.example.pantallaslistados.Objetos;
public class Catedratico {
private String id;
private String nombre;
private String telefono;
private String fechaNacimiento;
private String direccion;
private String foto;
private String correo;
public Catedratico() {
}
public Catedratico(String nombre, String telefono, String foto, String correo) {
this.nombre = nombre;
this.telefono = telefono;
this.foto = foto;
this.correo = correo;
}
public Catedratico(String id, String nombre, String telefono, String fechaNacimiento, String direccion, String foto, String correo) {
this.id = id;
this.nombre = nombre;
this.telefono = telefono;
this.fechaNacimiento = fechaNacimiento;
this.direccion = direccion;
this.foto = foto;
this.correo = correo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
}
| 1,933 | 0.61821 | 0.61821 | 87 | 21.218391 | 21.19663 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false | 9 |
4388c02aed07122b44812b12b44b759ea59a15d3 | 13,984,413,554,891 | 7ecc9aaa75fe4d35008d1ded54ae29a67c2d2e14 | /report-core/src/main/java/com/maplecloudy/bi/mapreduce/GenericReport.java | afbbc850e0a0381670396237252b4720c5252f38 | [] | no_license | TOURISTZHANG1990/maplecloudy-sdk | https://github.com/TOURISTZHANG1990/maplecloudy-sdk | e201edb26855cc2c56d7382a8859152093a130cd | 389032f1b7784f3f350aedf74282d7d33febda8f | refs/heads/master | 2021-02-14T16:47:13.304000 | 2019-08-29T11:00:24 | 2019-08-29T11:00:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.maplecloudy.bi.mapreduce;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import com.maplecloudy.avro.io.UnionData;
import com.maplecloudy.bi.ReportConstants;
import com.maplecloudy.bi.ReportFrequence;
import com.maplecloudy.bi.interceptor.TimestampInterceptor;
import com.maplecloudy.bi.model.report.ActivelyReportKey;
import com.maplecloudy.bi.model.report.ReportKey;
import com.maplecloudy.bi.model.report.ReportPair;
import com.maplecloudy.bi.model.report.ReportValues;
import com.maplecloudy.bi.report.algorithm.ReportAlgorithm;
import com.maplecloudy.bi.util.FilterUtil;
import com.maplecloudy.bi.util.ReportConstantsUtils;
import com.maplecloudy.bi.util.ReportUtils;
/**
* @author kim
* @date 2012-11-11
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class GenericReport {
public static class M<K,V> extends Mapper<K,V,UnionData,ReportValues> {
List<ReportAlgorithm> ras = null;
TimestampInterceptor ti = null;
public ReportFrequence frequence = ReportFrequence.Hourly;
public long reportTime = System.currentTimeMillis();
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
ras = context.getConfiguration().getInstances(
ReportConstants.REPORT_ALGORITHMS, ReportAlgorithm.class);
frequence = ReportFrequence.valueOf(context.getConfiguration().get(
ReportConstants.REPORT_FREQUENCE, ReportFrequence.Hourly.name()));
reportTime = context.getConfiguration().getInt(
ReportConstants.REPORT_TIME,
(int) (System.currentTimeMillis() / 1000));
ti = new TimestampInterceptor(reportTime, ReportConstantsUtils.getEdndate(
new Date(reportTime * 1000), frequence).getTime());
if (ras == null || ras.size() < 1) throw new IOException(
"No algorithms been set!");
for (ReportAlgorithm ra : ras)
ra.init(context.getConfiguration());
//add some info for debug
FileSplit fp = ((FileSplit)context.getInputSplit());
System.out.println("start:"+fp.getStart()+" length:"+fp.getLength());
FilterUtil.set(context.getConfiguration());
FilterUtil.get().setFilter();
}
int pnum = 0;
@Override
protected void map(K key, V value, Context context) throws IOException,
InterruptedException {
++pnum;
if(pnum%10000 == 0)
System.out.println("current process: " + pnum);
if (key instanceof UnionData)// other reuse ReportKey for up daily
// report
{
context.write((UnionData) key, (ReportValues) value);
} else {
pressLog(key, value, context);
}
}
protected void pressLog(K k, V v, Context context) {
// log = ti.intercept(log);
// if (log == null) {
// context.getCounter("Mapper-Intercept", "Skip-Num").increment(1);
// return;
// }
//
try {
for (ReportAlgorithm ra : ras) {
try {
List<ReportPair> lst = ra.algorithm(k, v);
if (lst == null) continue;
for (ReportPair pair : lst) {
context.getCounter("Mapper-ReportAlgorithm-Outputkeys",
pair.key.getClass().getSimpleName()).increment(1);
context.write(new UnionData(pair.key), pair.reportValues);
}
} catch (Exception e) {
context.getCounter("Mapper-Error", ra.getClass().getSimpleName())
.increment(1);
e.printStackTrace();
}
}
} catch (Exception e) {
context.getCounter("Mapper-Error", "Unexpected").increment(1);
e.printStackTrace();
}
}
protected void cleanup(Context context) throws IOException,
InterruptedException {
System.out.println("current process:"+pnum);
}
}
public static class R extends
Reducer<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void reduce(UnionData key, Iterable<ReportValues> values,
Context context) throws IOException, InterruptedException {
context.getCounter("reducer-key", key.datum.getClass().getSimpleName()).increment(1);
ReportValues reportValues = new ReportValues();
for (ReportValues rv : values) {
reportValues.merge(rv);
}
context.write(key, reportValues);
}
}
public static class M2 extends
Mapper<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
}
@Override
protected void map(UnionData key, ReportValues value, Context context)
throws IOException, InterruptedException {
if (value == null) return;
try {
if (key.datum instanceof ActivelyReportKey) {
ActivelyReportKey ark = (ActivelyReportKey) key.datum;
ReportKey rk = ark.getSuperKey();
Map<String,List<Integer>> map = ReportUtils.getActivelys(rk.getClass(),context.getConfiguration());
ReportValues rv = new ReportValues();
for (Entry<String,List<Integer>> entry : map.entrySet()) {
Long it = value.getMerge(entry.getKey());
if (it != null) {
List<Integer> lst = entry.getValue();
for (int i : lst) {
if (it > i) {
rv.putMerge(entry.getKey() + (i == 0 ? "" : "-" + i), 1L);
// context.write(key, );
}
}
}
}
if (rv.size() > 0) {
context.write(new UnionData(ark.getSuperKey()), rv);
}
} else {
context.write(key, value);
}
} catch (Exception e) {
// context.getCounter("Bad-Line", type.name()).increment(1);
e.printStackTrace();
}
}
}
public static class R2 extends
Reducer<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void reduce(UnionData key, Iterable<ReportValues> values,
Context context) throws IOException, InterruptedException {
ReportValues reportValues = new ReportValues();
for (ReportValues rv : values) {
reportValues.merge(rv);
}
context.write(key, reportValues);
}
}
}
| UTF-8 | Java | 6,550 | java | GenericReport.java | Java | [
{
"context": "m.maplecloudy.bi.util.ReportUtils;\n\n/**\n * @author kim\n * @date 2012-11-11\n */\n@SuppressWarnings({\"rawty",
"end": 927,
"score": 0.8145925402641296,
"start": 924,
"tag": "USERNAME",
"value": "kim"
}
] | null | [] | package com.maplecloudy.bi.mapreduce;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import com.maplecloudy.avro.io.UnionData;
import com.maplecloudy.bi.ReportConstants;
import com.maplecloudy.bi.ReportFrequence;
import com.maplecloudy.bi.interceptor.TimestampInterceptor;
import com.maplecloudy.bi.model.report.ActivelyReportKey;
import com.maplecloudy.bi.model.report.ReportKey;
import com.maplecloudy.bi.model.report.ReportPair;
import com.maplecloudy.bi.model.report.ReportValues;
import com.maplecloudy.bi.report.algorithm.ReportAlgorithm;
import com.maplecloudy.bi.util.FilterUtil;
import com.maplecloudy.bi.util.ReportConstantsUtils;
import com.maplecloudy.bi.util.ReportUtils;
/**
* @author kim
* @date 2012-11-11
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class GenericReport {
public static class M<K,V> extends Mapper<K,V,UnionData,ReportValues> {
List<ReportAlgorithm> ras = null;
TimestampInterceptor ti = null;
public ReportFrequence frequence = ReportFrequence.Hourly;
public long reportTime = System.currentTimeMillis();
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
ras = context.getConfiguration().getInstances(
ReportConstants.REPORT_ALGORITHMS, ReportAlgorithm.class);
frequence = ReportFrequence.valueOf(context.getConfiguration().get(
ReportConstants.REPORT_FREQUENCE, ReportFrequence.Hourly.name()));
reportTime = context.getConfiguration().getInt(
ReportConstants.REPORT_TIME,
(int) (System.currentTimeMillis() / 1000));
ti = new TimestampInterceptor(reportTime, ReportConstantsUtils.getEdndate(
new Date(reportTime * 1000), frequence).getTime());
if (ras == null || ras.size() < 1) throw new IOException(
"No algorithms been set!");
for (ReportAlgorithm ra : ras)
ra.init(context.getConfiguration());
//add some info for debug
FileSplit fp = ((FileSplit)context.getInputSplit());
System.out.println("start:"+fp.getStart()+" length:"+fp.getLength());
FilterUtil.set(context.getConfiguration());
FilterUtil.get().setFilter();
}
int pnum = 0;
@Override
protected void map(K key, V value, Context context) throws IOException,
InterruptedException {
++pnum;
if(pnum%10000 == 0)
System.out.println("current process: " + pnum);
if (key instanceof UnionData)// other reuse ReportKey for up daily
// report
{
context.write((UnionData) key, (ReportValues) value);
} else {
pressLog(key, value, context);
}
}
protected void pressLog(K k, V v, Context context) {
// log = ti.intercept(log);
// if (log == null) {
// context.getCounter("Mapper-Intercept", "Skip-Num").increment(1);
// return;
// }
//
try {
for (ReportAlgorithm ra : ras) {
try {
List<ReportPair> lst = ra.algorithm(k, v);
if (lst == null) continue;
for (ReportPair pair : lst) {
context.getCounter("Mapper-ReportAlgorithm-Outputkeys",
pair.key.getClass().getSimpleName()).increment(1);
context.write(new UnionData(pair.key), pair.reportValues);
}
} catch (Exception e) {
context.getCounter("Mapper-Error", ra.getClass().getSimpleName())
.increment(1);
e.printStackTrace();
}
}
} catch (Exception e) {
context.getCounter("Mapper-Error", "Unexpected").increment(1);
e.printStackTrace();
}
}
protected void cleanup(Context context) throws IOException,
InterruptedException {
System.out.println("current process:"+pnum);
}
}
public static class R extends
Reducer<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void reduce(UnionData key, Iterable<ReportValues> values,
Context context) throws IOException, InterruptedException {
context.getCounter("reducer-key", key.datum.getClass().getSimpleName()).increment(1);
ReportValues reportValues = new ReportValues();
for (ReportValues rv : values) {
reportValues.merge(rv);
}
context.write(key, reportValues);
}
}
public static class M2 extends
Mapper<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void setup(Context context) throws IOException,
InterruptedException {
}
@Override
protected void map(UnionData key, ReportValues value, Context context)
throws IOException, InterruptedException {
if (value == null) return;
try {
if (key.datum instanceof ActivelyReportKey) {
ActivelyReportKey ark = (ActivelyReportKey) key.datum;
ReportKey rk = ark.getSuperKey();
Map<String,List<Integer>> map = ReportUtils.getActivelys(rk.getClass(),context.getConfiguration());
ReportValues rv = new ReportValues();
for (Entry<String,List<Integer>> entry : map.entrySet()) {
Long it = value.getMerge(entry.getKey());
if (it != null) {
List<Integer> lst = entry.getValue();
for (int i : lst) {
if (it > i) {
rv.putMerge(entry.getKey() + (i == 0 ? "" : "-" + i), 1L);
// context.write(key, );
}
}
}
}
if (rv.size() > 0) {
context.write(new UnionData(ark.getSuperKey()), rv);
}
} else {
context.write(key, value);
}
} catch (Exception e) {
// context.getCounter("Bad-Line", type.name()).increment(1);
e.printStackTrace();
}
}
}
public static class R2 extends
Reducer<UnionData,ReportValues,UnionData,ReportValues> {
@Override
protected void reduce(UnionData key, Iterable<ReportValues> values,
Context context) throws IOException, InterruptedException {
ReportValues reportValues = new ReportValues();
for (ReportValues rv : values) {
reportValues.merge(rv);
}
context.write(key, reportValues);
}
}
}
| 6,550 | 0.632824 | 0.627481 | 188 | 33.840427 | 24.346699 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.691489 | false | false | 9 |
aaa98070ef189be04fd8477690ac975d27322c4b | 33,681,133,585,891 | 4ed5a14ab86e317df1ad7a2d322398c09a75761b | /src/holding/exercises/Ex31_IterableShapeGenerator.java | da1ca97858b8181bc366ce4ccfa4b09e8e0c4bf8 | [] | no_license | wladyk/LearningJava | https://github.com/wladyk/LearningJava | 717ecc1cc3a6b05f250196c1f899ee66197b3b61 | fdeae48cd7ff862ff2d81dcb76986db28bc1a099 | refs/heads/master | 2015-08-09T02:28:47.704000 | 2013-11-13T20:11:50 | 2013-11-13T20:11:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package holding.exercises;
import polymorphism.shape.RandomShapeGenerator;
import polymorphism.shape.Shape;
/**
* Created with IntelliJ IDEA.
* User: user
* Date: 16.08.13
* Time: 21:51
* To change this template use File | Settings | File Templates.
*/
public class Ex31_IterableShapeGenerator {
public static void main(String[] args){
RandomShapeGenerator randomShapeGenerator = new RandomShapeGenerator(10);
for (Shape shape:randomShapeGenerator){
System.out.println(shape.getClass().getSimpleName());
}
}
}
| UTF-8 | Java | 562 | java | Ex31_IterableShapeGenerator.java | Java | [
{
"context": "hape;\n\n/**\n * Created with IntelliJ IDEA.\n * User: user\n * Date: 16.08.13\n * Time: 21:51\n * To change thi",
"end": 158,
"score": 0.9985455274581909,
"start": 154,
"tag": "USERNAME",
"value": "user"
}
] | null | [] | package holding.exercises;
import polymorphism.shape.RandomShapeGenerator;
import polymorphism.shape.Shape;
/**
* Created with IntelliJ IDEA.
* User: user
* Date: 16.08.13
* Time: 21:51
* To change this template use File | Settings | File Templates.
*/
public class Ex31_IterableShapeGenerator {
public static void main(String[] args){
RandomShapeGenerator randomShapeGenerator = new RandomShapeGenerator(10);
for (Shape shape:randomShapeGenerator){
System.out.println(shape.getClass().getSimpleName());
}
}
}
| 562 | 0.708185 | 0.683274 | 20 | 27.1 | 24.087133 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 9 |
00c2941f12369d97985bb0375a386f32898d86dd | 3,951,369,974,760 | e6d16a55951eabc607cc35aab834ba7bb0179ba9 | /txlcn-protocol/src/main/java/com/codingapi/txlcn/protocol/ProtocolServer.java | 69807e63d2357a69f9b0d0faef5e133dc8074a6f | [
"Apache-2.0"
] | permissive | codingapi/tx-lcn | https://github.com/codingapi/tx-lcn | 708a03ebc1a4206e91f1b0782735162d3f66a008 | f8ce807b8a820cfb4e8290eec132fa4e3e8da3fd | refs/heads/dev6.0 | 2023-08-16T13:50:49.204000 | 2022-10-21T07:33:38 | 2022-10-21T07:33:38 | 110,315,174 | 4,518 | 1,537 | Apache-2.0 | false | 2023-09-06T07:27:15 | 2017-11-11T03:34:34 | 2023-09-05T17:00:38 | 2023-09-06T07:27:14 | 14,551 | 4,208 | 1,466 | 196 | Java | false | false | package com.codingapi.txlcn.protocol;
import com.codingapi.txlcn.protocol.config.Config;
import com.codingapi.txlcn.protocol.handler.ProtocolChannelHandler;
import com.codingapi.txlcn.protocol.handler.ProtocolChannelInitializer;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* @author lorne
* @date 2020/3/4
* @description
*/
@Slf4j
public class ProtocolServer {
private final EventLoopGroup acceptorEventLoopGroup;
private final EventLoopGroup networkEventLoopGroup;
private final EventExecutorGroup eventExecutorGroup;
private final Config config;
private final ApplicationContext applicationContext;
@Getter
private final Protocoler protocoler;
public ProtocolServer(Config config,ApplicationContext applicationContext) {
this.config = config;
this.applicationContext = applicationContext;
protocoler = new Protocoler(config);
acceptorEventLoopGroup = new NioEventLoopGroup(1);
networkEventLoopGroup = new NioEventLoopGroup(6);
eventExecutorGroup = new NioEventLoopGroup(10);
}
public ChannelFuture start() throws InterruptedException {
int portToBind = config.getPort();
ChannelFuture closeFuture = null;
ProtocolChannelHandler protocolChannelHandler = new ProtocolChannelHandler(protocoler,applicationContext,config);
ProtocolChannelInitializer protocolChannelInitializer = new ProtocolChannelInitializer(config,protocolChannelHandler,eventExecutorGroup);
final ServerBootstrap peerBootstrap = new ServerBootstrap();
peerBootstrap.group(acceptorEventLoopGroup, networkEventLoopGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(protocolChannelInitializer);
final ChannelFuture bindFuture = peerBootstrap.bind(portToBind).sync();
if (bindFuture.isSuccess()) {
log.info("Successfully bind to {}",portToBind);
final Channel serverChannel = bindFuture.channel();
final SettableFuture<Void> setServerChannelFuture = SettableFuture.create();
eventExecutorGroup.execute(() -> {
try {
protocoler.setBindChannel(serverChannel);
setServerChannelFuture.set(null);
} catch (Exception e) {
setServerChannelFuture.setException(e);
}
});
try {
setServerChannelFuture.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("server Couldn't set bind channel to server ", e);
System.exit(-1);
}
closeFuture = serverChannel.closeFuture();
} else {
log.error(" server could not bind to " + portToBind, bindFuture.cause());
System.exit(-1);
}
return closeFuture;
}
public boolean connectTo(String host, int port) {
CompletableFuture<Void> futureToNotify = new CompletableFuture<>();
return connectTo(host, port,futureToNotify);
}
public boolean connectTo(String host, int port, CompletableFuture<Void> futureToNotify) {
if(protocoler.isShutdown()){
log.warn("server already shut down!");
return false;
}
String uniqueKey = String.format("%s:%d",host,port);
if(protocoler.existConnect(uniqueKey)){
// log.warn("Already existing connection to " + uniqueKey + " is closed.");
return false;
}
ProtocolChannelHandler protocolChannelHandler = new ProtocolChannelHandler(protocoler,applicationContext,config);
ProtocolChannelInitializer protocolChannelInitializer = new ProtocolChannelInitializer(config,protocolChannelHandler,eventExecutorGroup);
final Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(networkEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(protocolChannelInitializer);
final ChannelFuture connectFuture = clientBootstrap.connect(host, port);
if (futureToNotify != null) {
connectFuture.addListener((ChannelFuture future)->{
if (future.isSuccess()) {
log.info("Successfully connect to {}:{}", host, port);
futureToNotify.complete(null);
} else {
log.error("Could not connect to " + host + ":" + port, future.cause());
futureToNotify.completeExceptionally(future.cause());
}
}
);
}
return true;
}
}
| UTF-8 | Java | 5,759 | java | ProtocolServer.java | Java | [
{
"context": "ort java.util.concurrent.TimeUnit;\n\n/**\n * @author lorne\n * @date 2020/3/4\n * @description\n */\n@Slf4j\npubl",
"end": 1037,
"score": 0.9994726777076721,
"start": 1032,
"tag": "USERNAME",
"value": "lorne"
},
{
"context": "return false;\n }\n String uniqueKey = String.format(\"%s:%d\",host,port);\n if(protocoler.existConnect(uniqueKey)){\n/",
"end": 4348,
"score": 0.9479581713676453,
"start": 4315,
"tag": "KEY",
"value": "String.format(\"%s:%d\",host,port);"
}
] | null | [] | package com.codingapi.txlcn.protocol;
import com.codingapi.txlcn.protocol.config.Config;
import com.codingapi.txlcn.protocol.handler.ProtocolChannelHandler;
import com.codingapi.txlcn.protocol.handler.ProtocolChannelInitializer;
import com.google.common.util.concurrent.SettableFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
/**
* @author lorne
* @date 2020/3/4
* @description
*/
@Slf4j
public class ProtocolServer {
private final EventLoopGroup acceptorEventLoopGroup;
private final EventLoopGroup networkEventLoopGroup;
private final EventExecutorGroup eventExecutorGroup;
private final Config config;
private final ApplicationContext applicationContext;
@Getter
private final Protocoler protocoler;
public ProtocolServer(Config config,ApplicationContext applicationContext) {
this.config = config;
this.applicationContext = applicationContext;
protocoler = new Protocoler(config);
acceptorEventLoopGroup = new NioEventLoopGroup(1);
networkEventLoopGroup = new NioEventLoopGroup(6);
eventExecutorGroup = new NioEventLoopGroup(10);
}
public ChannelFuture start() throws InterruptedException {
int portToBind = config.getPort();
ChannelFuture closeFuture = null;
ProtocolChannelHandler protocolChannelHandler = new ProtocolChannelHandler(protocoler,applicationContext,config);
ProtocolChannelInitializer protocolChannelInitializer = new ProtocolChannelInitializer(config,protocolChannelHandler,eventExecutorGroup);
final ServerBootstrap peerBootstrap = new ServerBootstrap();
peerBootstrap.group(acceptorEventLoopGroup, networkEventLoopGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(protocolChannelInitializer);
final ChannelFuture bindFuture = peerBootstrap.bind(portToBind).sync();
if (bindFuture.isSuccess()) {
log.info("Successfully bind to {}",portToBind);
final Channel serverChannel = bindFuture.channel();
final SettableFuture<Void> setServerChannelFuture = SettableFuture.create();
eventExecutorGroup.execute(() -> {
try {
protocoler.setBindChannel(serverChannel);
setServerChannelFuture.set(null);
} catch (Exception e) {
setServerChannelFuture.setException(e);
}
});
try {
setServerChannelFuture.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("server Couldn't set bind channel to server ", e);
System.exit(-1);
}
closeFuture = serverChannel.closeFuture();
} else {
log.error(" server could not bind to " + portToBind, bindFuture.cause());
System.exit(-1);
}
return closeFuture;
}
public boolean connectTo(String host, int port) {
CompletableFuture<Void> futureToNotify = new CompletableFuture<>();
return connectTo(host, port,futureToNotify);
}
public boolean connectTo(String host, int port, CompletableFuture<Void> futureToNotify) {
if(protocoler.isShutdown()){
log.warn("server already shut down!");
return false;
}
String uniqueKey = String.format("%s:%d",host,port);
if(protocoler.existConnect(uniqueKey)){
// log.warn("Already existing connection to " + uniqueKey + " is closed.");
return false;
}
ProtocolChannelHandler protocolChannelHandler = new ProtocolChannelHandler(protocoler,applicationContext,config);
ProtocolChannelInitializer protocolChannelInitializer = new ProtocolChannelInitializer(config,protocolChannelHandler,eventExecutorGroup);
final Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(networkEventLoopGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(protocolChannelInitializer);
final ChannelFuture connectFuture = clientBootstrap.connect(host, port);
if (futureToNotify != null) {
connectFuture.addListener((ChannelFuture future)->{
if (future.isSuccess()) {
log.info("Successfully connect to {}:{}", host, port);
futureToNotify.complete(null);
} else {
log.error("Could not connect to " + host + ":" + port, future.cause());
futureToNotify.completeExceptionally(future.cause());
}
}
);
}
return true;
}
}
| 5,759 | 0.666088 | 0.661747 | 155 | 36.154839 | 31.195562 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.658065 | false | false | 9 |
83136241f18cf0140bf3941a6946863ac2b95e3c | 8,864,812,502,649 | bfceea292bedb20fc1d9edd869ef863e3d74928b | /src/sayden/World.java | 7748eb4d2056ec72a042c316cda236d5031a32ab | [] | no_license | BBalderrabano/SimpleSayden | https://github.com/BBalderrabano/SimpleSayden | c78a927b29b53f604f2b11e0c9594d890aab2d98 | 717680fe65f98ecbe0e4e0e8ee1868bf634480d0 | refs/heads/master | 2021-05-02T10:37:15.894000 | 2017-06-09T02:34:45 | 2017-06-09T02:35:30 | 43,966,933 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sayden;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
public class World {
private Tile[][] tiles;
public Tile[][] tiles() { return tiles; }
private Item[][] items;
private float[][] blood;
private boolean[][] visited;
private int width;
public int width() { return width; }
private int height;
public int height() { return height; }
private List<Creature> creatures;
private List<Projectile> projectiles;
public World(Tile[][] tiles){
this.tiles = tiles;
this.width = tiles.length;
this.height = tiles[0].length;
this.creatures = new ArrayList<Creature>();
this.projectiles = new ArrayList<Projectile>();
this.items = new Item[tiles.length][tiles[0].length];
this.blood = new float[tiles.length][tiles[0].length];
this.visited = new boolean[tiles.length][tiles[0].length];
this.regions = new int[tiles.length][tiles[0].length];
}
private int[][] regions;
private int visitedRegions = 1;
public void createRegions(){
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
if(tiles[x][y].isGround() && regions[x][y] == 0){
connectRegion(visitedRegions++, x, y);
}
}
}
}
private void connectRegion(int region, int x, int y){
int size = 1;
ArrayList<Point> open = new ArrayList<Point>();
open.add(new Point(x,y));
regions[x][y] = region;
while (!open.isEmpty()){
Point p = open.remove(0);
for (Point neighbor : p.neighbors8()){
if (neighbor.x < 0 || neighbor.y < 0 || neighbor.x >= width || neighbor.y >= height)
continue;
if (regions[neighbor.x][neighbor.y] > 0
|| !tiles[neighbor.x][neighbor.y].isGround())
continue;
size++;
regions[neighbor.x][neighbor.y] = region;
open.add(neighbor);
}
}
System.out.println(size);
}
public void overrideFloor(World newWorld){
int maxHeight = Math.max(height, newWorld.height());
int maxWidth = Math.max(width, newWorld.width());
width = newWorld.width();
height = newWorld.height();
for(int y = 0; y < maxHeight; y++){
for(int x = 0; x < maxWidth; x++){
tiles[x][y] = newWorld.tile(x, y);
if(tiles[x][y] == Tile.STAIRS_DOWN){
tiles[x][y] = Tile.STAIRS_UP;
}
}
}
}
public void modifyActionPoints(int amount){
amount = Math.abs(amount);
for(Creature c : creatures){
if(c.isPlayer())
continue;
c.modifyActionPoints(amount);
}
for(Projectile p : projectiles){
p.modifyActionPoints(amount);
}
}
public Projectile projectile(int x, int y){
for (Projectile p : projectiles){
if (p.x == x && p.y == y)
return p;
}
return null;
}
public Creature creature(int x, int y){
for (Creature c : creatures){
if (c.x == x && c.y == y)
return c;
}
return null;
}
public boolean isOutBounds(int x, int y){
return (x < 0 || x >= width || y < 0 || y >= height);
}
public Tile tile(int x, int y){
if (x < 0 || x >= width || y < 0 || y >= height)
return Tile.BOUNDS;
else
return tiles[x][y];
}
public void setTile(int x, int y, Tile newTile){
if (x < 0 || x >= width || y < 0 || y >= height)
return;
else
tiles[x][y] = newTile;
}
public void propagate(int x, int y, float amount, String fluidType){
Point tile = new Point(x,y);
if(x > width || x < 0 || y > height || y < 0)
return;
//Blood is additive, when a tile is about to be filled with more blood than it
//can sustain its spread to adjacent tiles
if(fluidType == Constants.BLOOD_FLUID){
if(blood[x][y] + amount < 100f){
blood[x][y] += amount;
}else{
for(Point t : tile.neighbors8()){
if(isOutBounds(t.x, t.y)){
continue;
}
if(blood[t.x][t.y] <= 100f){
blood[t.x][t.y] += amount;
if(blood[t.x][t.y] > 100f){
propagate(x,y, blood[t.x][t.y] - 100f, fluidType);
blood[x][y] = 100f;
}
return;
}
}
}
}
}
public char glyph(int x, int y){
Creature creature = creature(x, y);
Projectile projectile = projectile(x, y);
if(projectile != null)
return projectile.projectile().glyph();
if (creature != null && !creature.getBooleanData(Constants.FLAG_INVISIBLE))
return creature.glyph();
if (item(x,y) != null)
return item(x,y).glyph();
return tile(x, y).glyph();
}
public Color color(int x, int y){
Creature creature = creature(x, y);
Projectile projectile = projectile(x, y);
if(projectile != null)
return projectile.projectile().color();
if (creature != null && !creature.getBooleanData(Constants.FLAG_INVISIBLE))
return creature.color();
if (item(x,y) != null)
return item(x,y).color();
return tile(x, y).color();
}
public Color backgroundColor(int x, int y){
float bloodAmount = blood[x][y];
Projectile projectile = projectile(x, y);
if(projectile != null)
return Constants.THROWN_BKG_COLOR;
if (x < 0 || x >= width || y < 0 || y >= height)
return Tile.BOUNDS.backgroundColor();
if(bloodAmount > 0f){
return new Color(Math.min((bloodAmount / 100f), 1f),0,0);
}
return tile(x, y).backgroundColor();
}
public void dig(int x, int y) {
if (tile(x, y).isDiggable())
tiles[x][y] = Tile.FLOOR;
}
public void open(int x, int y) {
if (tile(x, y).isDoor())
tiles[x][y] = tile(x, y) == Tile.DOOR_OPEN ? Tile.DOOR_CLOSE : Tile.DOOR_OPEN;
}
public void addAtEmptyLocation(Creature creature){
int x;
int y;
do {
x = (int)(Math.random() * width);
y = (int)(Math.random() * height);
}
while (!tile(x,y).isGround() || creature(x,y) != null);
creature.x = x;
creature.y = y;
creatures.add(creature);
}
private void updateProjectiles(){
List<Projectile> done = new ArrayList<Projectile>();
for (Projectile projectile : projectiles){
projectile.update();
if (projectile.isDone()) {
if(!projectile.isInterrupted()){ projectile.end(); }
done.add(projectile);
}
}
projectiles.removeAll(done);
}
public void updateFloor(){
List<Creature> toUpdate = new ArrayList<Creature>(creatures);
for (Creature creature : toUpdate){
creature.update();
}
updateProjectiles();
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
if(blood[x][y] > Constants.MIN_FLUID_AMOUNT)
blood[x][y] -= 1f;
}
}
}
public void remove(Creature other) {
creatures.remove(other);
}
public void remove(Item item) {
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
if (items[x][y] == item) {
items[x][y] = null;
return;
}
}
}
}
public Item item(int x, int y){
if(x < 0 || y < 0 || x >= width || y >= height)
return null;
return items[x][y];
}
public void addAtEmptyLocation(Item item) {
addAtEmptyLocation(item, true);
}
public void addAtEmptyLocation(Item item, boolean spawn) {
int x;
int y;
if(!spawn){
return;
}
do {
x = (int)(Math.random() * width);
y = (int)(Math.random() * height);
}
while (!tile(x,y).isGround() || item(x,y) != null);
items[x][y] = item;
}
public void remove(int x, int y) {
items[x][y] = null;
}
public boolean addAtEmptySpace(Creature creature, int x, int y){
return addAtEmptySpace(creature, x, y, true);
}
public boolean addAtEmptySpace(Creature creature, int x, int y, boolean spawn){
if (creature == null)
return true;
if(!spawn)
return true;
List<Point> points = new ArrayList<Point>();
List<Point> checked = new ArrayList<Point>();
points.add(new Point(x, y));
while (!points.isEmpty()){
Point p = points.remove(0);
checked.add(p);
if (!tile(p.x, p.y).isGround())
continue;
if (creature(p.x, p.y) == null){
creature.x = p.x;
creature.y = p.y;
creatures.add(creature);
return true;
} else {
List<Point> neighbors = p.neighbors8();
neighbors.removeAll(checked);
points.addAll(neighbors);
}
}
return false;
}
public boolean addAtEmptySpace(Item item, int x, int y){
return addAtEmptySpace(item, x, y, true);
}
public boolean addAtEmptySpace(Item item, int x, int y, boolean spawn){
if (item == null)
return true;
if(!spawn)
return true;
List<Point> points = new ArrayList<Point>();
List<Point> checked = new ArrayList<Point>();
points.add(new Point(x, y));
while (!points.isEmpty()){
Point p = points.remove(0);
checked.add(p);
if (!tile(p.x, p.y).isGround())
continue;
if (items[p.x][p.y] == null){
items[p.x][p.y] = item;
Creature c = this.creature(p.x, p.y);
if (c != null)
c.notify("%s cae a tus pies.", item.nameUnUna().substring(0, 1).toUpperCase() + item.nameUnUna().substring(1));
return true;
} else {
List<Point> neighbors = p.neighbors8();
neighbors.removeAll(checked);
points.addAll(neighbors);
}
}
return false;
}
public void add(Creature pet) {
creatures.add(pet);
}
public void add(List<Creature> pets) {
creatures.addAll(pets);
}
public void add(Projectile missile) {
projectiles.add(missile);
}
public float getCost(Creature mover, int sx, int sy, int tx, int ty) {
//We can change the cost of moving to different tiles
return 1;
}
public void pathFinderVisited(int x, int y) {
visited[x][y] = true;
}
}
| UTF-8 | Java | 9,333 | java | World.java | Java | [] | null | [] | package sayden;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
public class World {
private Tile[][] tiles;
public Tile[][] tiles() { return tiles; }
private Item[][] items;
private float[][] blood;
private boolean[][] visited;
private int width;
public int width() { return width; }
private int height;
public int height() { return height; }
private List<Creature> creatures;
private List<Projectile> projectiles;
public World(Tile[][] tiles){
this.tiles = tiles;
this.width = tiles.length;
this.height = tiles[0].length;
this.creatures = new ArrayList<Creature>();
this.projectiles = new ArrayList<Projectile>();
this.items = new Item[tiles.length][tiles[0].length];
this.blood = new float[tiles.length][tiles[0].length];
this.visited = new boolean[tiles.length][tiles[0].length];
this.regions = new int[tiles.length][tiles[0].length];
}
private int[][] regions;
private int visitedRegions = 1;
public void createRegions(){
for(int x = 0; x < width; x++){
for(int y = 0; y < height; y++){
if(tiles[x][y].isGround() && regions[x][y] == 0){
connectRegion(visitedRegions++, x, y);
}
}
}
}
private void connectRegion(int region, int x, int y){
int size = 1;
ArrayList<Point> open = new ArrayList<Point>();
open.add(new Point(x,y));
regions[x][y] = region;
while (!open.isEmpty()){
Point p = open.remove(0);
for (Point neighbor : p.neighbors8()){
if (neighbor.x < 0 || neighbor.y < 0 || neighbor.x >= width || neighbor.y >= height)
continue;
if (regions[neighbor.x][neighbor.y] > 0
|| !tiles[neighbor.x][neighbor.y].isGround())
continue;
size++;
regions[neighbor.x][neighbor.y] = region;
open.add(neighbor);
}
}
System.out.println(size);
}
public void overrideFloor(World newWorld){
int maxHeight = Math.max(height, newWorld.height());
int maxWidth = Math.max(width, newWorld.width());
width = newWorld.width();
height = newWorld.height();
for(int y = 0; y < maxHeight; y++){
for(int x = 0; x < maxWidth; x++){
tiles[x][y] = newWorld.tile(x, y);
if(tiles[x][y] == Tile.STAIRS_DOWN){
tiles[x][y] = Tile.STAIRS_UP;
}
}
}
}
public void modifyActionPoints(int amount){
amount = Math.abs(amount);
for(Creature c : creatures){
if(c.isPlayer())
continue;
c.modifyActionPoints(amount);
}
for(Projectile p : projectiles){
p.modifyActionPoints(amount);
}
}
public Projectile projectile(int x, int y){
for (Projectile p : projectiles){
if (p.x == x && p.y == y)
return p;
}
return null;
}
public Creature creature(int x, int y){
for (Creature c : creatures){
if (c.x == x && c.y == y)
return c;
}
return null;
}
public boolean isOutBounds(int x, int y){
return (x < 0 || x >= width || y < 0 || y >= height);
}
public Tile tile(int x, int y){
if (x < 0 || x >= width || y < 0 || y >= height)
return Tile.BOUNDS;
else
return tiles[x][y];
}
public void setTile(int x, int y, Tile newTile){
if (x < 0 || x >= width || y < 0 || y >= height)
return;
else
tiles[x][y] = newTile;
}
public void propagate(int x, int y, float amount, String fluidType){
Point tile = new Point(x,y);
if(x > width || x < 0 || y > height || y < 0)
return;
//Blood is additive, when a tile is about to be filled with more blood than it
//can sustain its spread to adjacent tiles
if(fluidType == Constants.BLOOD_FLUID){
if(blood[x][y] + amount < 100f){
blood[x][y] += amount;
}else{
for(Point t : tile.neighbors8()){
if(isOutBounds(t.x, t.y)){
continue;
}
if(blood[t.x][t.y] <= 100f){
blood[t.x][t.y] += amount;
if(blood[t.x][t.y] > 100f){
propagate(x,y, blood[t.x][t.y] - 100f, fluidType);
blood[x][y] = 100f;
}
return;
}
}
}
}
}
public char glyph(int x, int y){
Creature creature = creature(x, y);
Projectile projectile = projectile(x, y);
if(projectile != null)
return projectile.projectile().glyph();
if (creature != null && !creature.getBooleanData(Constants.FLAG_INVISIBLE))
return creature.glyph();
if (item(x,y) != null)
return item(x,y).glyph();
return tile(x, y).glyph();
}
public Color color(int x, int y){
Creature creature = creature(x, y);
Projectile projectile = projectile(x, y);
if(projectile != null)
return projectile.projectile().color();
if (creature != null && !creature.getBooleanData(Constants.FLAG_INVISIBLE))
return creature.color();
if (item(x,y) != null)
return item(x,y).color();
return tile(x, y).color();
}
public Color backgroundColor(int x, int y){
float bloodAmount = blood[x][y];
Projectile projectile = projectile(x, y);
if(projectile != null)
return Constants.THROWN_BKG_COLOR;
if (x < 0 || x >= width || y < 0 || y >= height)
return Tile.BOUNDS.backgroundColor();
if(bloodAmount > 0f){
return new Color(Math.min((bloodAmount / 100f), 1f),0,0);
}
return tile(x, y).backgroundColor();
}
public void dig(int x, int y) {
if (tile(x, y).isDiggable())
tiles[x][y] = Tile.FLOOR;
}
public void open(int x, int y) {
if (tile(x, y).isDoor())
tiles[x][y] = tile(x, y) == Tile.DOOR_OPEN ? Tile.DOOR_CLOSE : Tile.DOOR_OPEN;
}
public void addAtEmptyLocation(Creature creature){
int x;
int y;
do {
x = (int)(Math.random() * width);
y = (int)(Math.random() * height);
}
while (!tile(x,y).isGround() || creature(x,y) != null);
creature.x = x;
creature.y = y;
creatures.add(creature);
}
private void updateProjectiles(){
List<Projectile> done = new ArrayList<Projectile>();
for (Projectile projectile : projectiles){
projectile.update();
if (projectile.isDone()) {
if(!projectile.isInterrupted()){ projectile.end(); }
done.add(projectile);
}
}
projectiles.removeAll(done);
}
public void updateFloor(){
List<Creature> toUpdate = new ArrayList<Creature>(creatures);
for (Creature creature : toUpdate){
creature.update();
}
updateProjectiles();
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
if(blood[x][y] > Constants.MIN_FLUID_AMOUNT)
blood[x][y] -= 1f;
}
}
}
public void remove(Creature other) {
creatures.remove(other);
}
public void remove(Item item) {
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
if (items[x][y] == item) {
items[x][y] = null;
return;
}
}
}
}
public Item item(int x, int y){
if(x < 0 || y < 0 || x >= width || y >= height)
return null;
return items[x][y];
}
public void addAtEmptyLocation(Item item) {
addAtEmptyLocation(item, true);
}
public void addAtEmptyLocation(Item item, boolean spawn) {
int x;
int y;
if(!spawn){
return;
}
do {
x = (int)(Math.random() * width);
y = (int)(Math.random() * height);
}
while (!tile(x,y).isGround() || item(x,y) != null);
items[x][y] = item;
}
public void remove(int x, int y) {
items[x][y] = null;
}
public boolean addAtEmptySpace(Creature creature, int x, int y){
return addAtEmptySpace(creature, x, y, true);
}
public boolean addAtEmptySpace(Creature creature, int x, int y, boolean spawn){
if (creature == null)
return true;
if(!spawn)
return true;
List<Point> points = new ArrayList<Point>();
List<Point> checked = new ArrayList<Point>();
points.add(new Point(x, y));
while (!points.isEmpty()){
Point p = points.remove(0);
checked.add(p);
if (!tile(p.x, p.y).isGround())
continue;
if (creature(p.x, p.y) == null){
creature.x = p.x;
creature.y = p.y;
creatures.add(creature);
return true;
} else {
List<Point> neighbors = p.neighbors8();
neighbors.removeAll(checked);
points.addAll(neighbors);
}
}
return false;
}
public boolean addAtEmptySpace(Item item, int x, int y){
return addAtEmptySpace(item, x, y, true);
}
public boolean addAtEmptySpace(Item item, int x, int y, boolean spawn){
if (item == null)
return true;
if(!spawn)
return true;
List<Point> points = new ArrayList<Point>();
List<Point> checked = new ArrayList<Point>();
points.add(new Point(x, y));
while (!points.isEmpty()){
Point p = points.remove(0);
checked.add(p);
if (!tile(p.x, p.y).isGround())
continue;
if (items[p.x][p.y] == null){
items[p.x][p.y] = item;
Creature c = this.creature(p.x, p.y);
if (c != null)
c.notify("%s cae a tus pies.", item.nameUnUna().substring(0, 1).toUpperCase() + item.nameUnUna().substring(1));
return true;
} else {
List<Point> neighbors = p.neighbors8();
neighbors.removeAll(checked);
points.addAll(neighbors);
}
}
return false;
}
public void add(Creature pet) {
creatures.add(pet);
}
public void add(List<Creature> pets) {
creatures.addAll(pets);
}
public void add(Projectile missile) {
projectiles.add(missile);
}
public float getCost(Creature mover, int sx, int sy, int tx, int ty) {
//We can change the cost of moving to different tiles
return 1;
}
public void pathFinderVisited(int x, int y) {
visited[x][y] = true;
}
}
| 9,333 | 0.604629 | 0.597664 | 419 | 21.274464 | 19.713062 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.892601 | false | false | 9 |
90f7f485d21717efaa953dc3e88006657249fa05 | 37,366,215,513,442 | ed59f134218fa32eb375146708fa910c002e2296 | /android/app/src/main/java/com/rctpdfthumbnails/MyRecycler.java | b26a95807cffc08cd90ee25bb330fcc89c90a627 | [] | no_license | pradeeptimeinc/react-native-pdf-thumbnails | https://github.com/pradeeptimeinc/react-native-pdf-thumbnails | f0fd1e4c5e144c2f41176163e8d56d1cbf5233b2 | 7b8c60e8c437a2ca4c6f295bacaa5cc13db74aa6 | refs/heads/master | 2020-03-16T21:51:02.630000 | 2018-05-14T11:38:10 | 2018-05-14T11:38:10 | 133,016,916 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rctpdfthumbnails;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.LinearLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
/**
* Created by sharmapra on 5/10/18.
*/
public class MyRecycler extends LinearLayout {
public MyRecycler(Context context) {
super(context);
}
public void onReceiveNativeEvent(int index) {
Log.e("ONREC", "JHBJJB");
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
event.putInt("index", index+1);
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"topChange",
event);
}
}
| UTF-8 | Java | 977 | java | MyRecycler.java | Java | [
{
"context": "manager.events.RCTEventEmitter;\n\n/**\n * Created by sharmapra on 5/10/18.\n */\n\npublic class MyRecycler extends ",
"end": 397,
"score": 0.9995648860931396,
"start": 388,
"tag": "USERNAME",
"value": "sharmapra"
}
] | null | [] | package com.rctpdfthumbnails;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.LinearLayout;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
/**
* Created by sharmapra on 5/10/18.
*/
public class MyRecycler extends LinearLayout {
public MyRecycler(Context context) {
super(context);
}
public void onReceiveNativeEvent(int index) {
Log.e("ONREC", "JHBJJB");
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
event.putInt("index", index+1);
ReactContext reactContext = (ReactContext)getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"topChange",
event);
}
}
| 977 | 0.693961 | 0.686796 | 32 | 29.53125 | 20.353109 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65625 | false | false | 9 |
9b5acb1c661f51dbd10ee7220c4dc3f14cfe25f6 | 39,109,972,214,241 | 4a9ba943a3dbccfb2b92641f14c39e9b56707c21 | /src/java/iotbay/g15/controller/CreateUserServlet.java | f2e74611b89a7854d3761b92c820b22c0d09613f | [] | no_license | rjyg/IoTBay | https://github.com/rjyg/IoTBay | e743338e8700edfcf40894c0a559038f7ec3faae | 81f346827cdeff238b3c4ec81dbb3df6a1e702af | refs/heads/master | 2023-05-07T01:08:51.681000 | 2021-05-17T13:58:25 | 2021-05-17T13:58:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package iotbay.g15.controller;
import iotbay.g15.model.dao.UserManagementDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Kevin
*/
public class CreateUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
UserManagementDAO manager = (UserManagementDAO) session.getAttribute("userManager");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
String password = request.getParameter("password");
String phoneNumber = request.getParameter("phoneNumber");
int streetNumber = Integer.parseInt(request.getParameter("streetNumber"));
String streetName = request.getParameter("streetName");
String streetType = request.getParameter("streetType");
String suburb = request.getParameter("suburb");
String state = request.getParameter("state");
int postcode = Integer.parseInt(request.getParameter("postcode"));
String country = request.getParameter("country");
UserManagementValidator validator = new UserManagementValidator();
//Assign errorMessage with int to create if statement line 71. Each error can ++ errorMessage
int errorMessage = 0;
if (!validator.validateName(firstName)) {
session.setAttribute("firstNameError", "Please enter a first name");
errorMessage++;
}
if (!validator.validateName(lastName)) {
session.setAttribute("lastNameError", "Please enter a last name");
errorMessage++;
}
if (!validator.validateEmail(email)) {
session.setAttribute("emailError", "Please enter a valid email");
errorMessage++;
}
if (!validator.validatePhoneNumber(phoneNumber)) {
session.setAttribute("phoneError", "Please enter a valid phone number");
errorMessage++;
}
//If no error message, create new user. Else reload the pagw showing validation errors
try {
if (errorMessage == 0) {
manager.addUser(firstName, lastName, email, password,
Integer.parseInt(phoneNumber), streetNumber, streetName, streetType,
suburb, state, postcode, country);
response.sendRedirect("listUser.jsp");
} else {
response.sendRedirect("createUser.jsp");
}
} catch (SQLException error) {
Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, error);
}
}
}
| UTF-8 | Java | 3,330 | java | CreateUserServlet.java | Java | [
{
"context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author Kevin\n */\npublic class CreateUserServlet extends HttpSe",
"end": 649,
"score": 0.9975447058677673,
"start": 644,
"tag": "NAME",
"value": "Kevin"
},
{
"context": "orMessage == 0) {\n manager.addUser(firstName, lastName, email, password,\n ",
"end": 2847,
"score": 0.9988696575164795,
"start": 2838,
"tag": "NAME",
"value": "firstName"
},
{
"context": "== 0) {\n manager.addUser(firstName, lastName, email, password,\n Integer",
"end": 2857,
"score": 0.9994506239891052,
"start": 2849,
"tag": "NAME",
"value": "lastName"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package iotbay.g15.controller;
import iotbay.g15.model.dao.UserManagementDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Kevin
*/
public class CreateUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
UserManagementDAO manager = (UserManagementDAO) session.getAttribute("userManager");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
String password = request.getParameter("password");
String phoneNumber = request.getParameter("phoneNumber");
int streetNumber = Integer.parseInt(request.getParameter("streetNumber"));
String streetName = request.getParameter("streetName");
String streetType = request.getParameter("streetType");
String suburb = request.getParameter("suburb");
String state = request.getParameter("state");
int postcode = Integer.parseInt(request.getParameter("postcode"));
String country = request.getParameter("country");
UserManagementValidator validator = new UserManagementValidator();
//Assign errorMessage with int to create if statement line 71. Each error can ++ errorMessage
int errorMessage = 0;
if (!validator.validateName(firstName)) {
session.setAttribute("firstNameError", "Please enter a first name");
errorMessage++;
}
if (!validator.validateName(lastName)) {
session.setAttribute("lastNameError", "Please enter a last name");
errorMessage++;
}
if (!validator.validateEmail(email)) {
session.setAttribute("emailError", "Please enter a valid email");
errorMessage++;
}
if (!validator.validatePhoneNumber(phoneNumber)) {
session.setAttribute("phoneError", "Please enter a valid phone number");
errorMessage++;
}
//If no error message, create new user. Else reload the pagw showing validation errors
try {
if (errorMessage == 0) {
manager.addUser(firstName, lastName, email, password,
Integer.parseInt(phoneNumber), streetNumber, streetName, streetType,
suburb, state, postcode, country);
response.sendRedirect("listUser.jsp");
} else {
response.sendRedirect("createUser.jsp");
}
} catch (SQLException error) {
Logger.getLogger(CreateUserServlet.class.getName()).log(Level.SEVERE, null, error);
}
}
}
| 3,330 | 0.666667 | 0.664264 | 85 | 38.176472 | 29.309776 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.741176 | false | false | 9 |
688bfabb8b0ba74ddb52879a05712f21e77a3ce8 | 9,509,057,620,438 | f54dba44c8335d1d54338941bd675a986d1aaa4d | /teaapp/src/main/java/com/jarvisdong/teaapp/domain/contract/CommonLocalRepository.java | f0ca6131ace2f971f9f120152371743349fc9cae | [] | no_license | JarvisBuop/ComponentDemo | https://github.com/JarvisBuop/ComponentDemo | c3fa828b0b4d2b0dfde9c58cc494eef32cd1b14a | 4d2a5d837b02595989606d1b85966e68f6f62fb7 | refs/heads/master | 2020-03-21T02:22:45.769000 | 2018-09-27T09:41:44 | 2018-09-27T09:41:44 | 137,995,683 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jarvisdong.teaapp.domain.contract;
import android.support.annotation.NonNull;
import com.jarvisdong.uikit.clear.UseCase;
import com.jarvisdong.uikit.mvp.BaseModelDataSource;
/**
* Created by JarvisDong on 2018/2/6.
*
*/
public class CommonLocalRepository implements BaseModelDataSource<UseCase.RequestValues, UseCase.ResponseValues> {
private static volatile CommonLocalRepository sInstance;
// Prevent direct instantiation.
private CommonLocalRepository() {
}
public static CommonLocalRepository getInstance() {
if (sInstance == null) {
synchronized (CommonLocalRepository.class) {
if (sInstance == null) {
sInstance = new CommonLocalRepository();
}
}
}
return sInstance;
}
@Override
public void feachDatas(@NonNull UseCase.RequestValues requestValue, @NonNull LoadDatasCallback<UseCase.ResponseValues> callback) {
}
@Override
public void saveDatas(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void updateCompleted(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void deleteDatas(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void deleteAllDatas() {
}
@Override
public void cancel() {
}
}
| UTF-8 | Java | 1,386 | java | CommonLocalRepository.java | Java | [
{
"context": "uikit.mvp.BaseModelDataSource;\n\n\n/**\n * Created by JarvisDong on 2018/2/6.\n *\n */\n\npublic class CommonLocalRepo",
"end": 218,
"score": 0.9473974108695984,
"start": 208,
"tag": "NAME",
"value": "JarvisDong"
}
] | null | [] | package com.jarvisdong.teaapp.domain.contract;
import android.support.annotation.NonNull;
import com.jarvisdong.uikit.clear.UseCase;
import com.jarvisdong.uikit.mvp.BaseModelDataSource;
/**
* Created by JarvisDong on 2018/2/6.
*
*/
public class CommonLocalRepository implements BaseModelDataSource<UseCase.RequestValues, UseCase.ResponseValues> {
private static volatile CommonLocalRepository sInstance;
// Prevent direct instantiation.
private CommonLocalRepository() {
}
public static CommonLocalRepository getInstance() {
if (sInstance == null) {
synchronized (CommonLocalRepository.class) {
if (sInstance == null) {
sInstance = new CommonLocalRepository();
}
}
}
return sInstance;
}
@Override
public void feachDatas(@NonNull UseCase.RequestValues requestValue, @NonNull LoadDatasCallback<UseCase.ResponseValues> callback) {
}
@Override
public void saveDatas(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void updateCompleted(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void deleteDatas(@NonNull UseCase.ResponseValues responseValue) {
}
@Override
public void deleteAllDatas() {
}
@Override
public void cancel() {
}
}
| 1,386 | 0.678932 | 0.674603 | 62 | 21.354839 | 29.218365 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.145161 | false | false | 9 |
2a8cfa7a6dc58deab321a5384a3f3964b9df9890 | 19,533,511,305,074 | 96054dfb0cc5cb786b56159f11319c59dc6bc32e | /src/test/java/com/soil/logger/controller/HelloWorldControllerTest.java | a773d66044c41bbe48c9c87d2005a4e918bf108b | [] | no_license | ggsongnail/flower | https://github.com/ggsongnail/flower | aa6e4f9a9ba55314a3f037da1fe700a47ea824f5 | daccaedb56b7b4a464d2bd0642667bb0fdb12a6d | refs/heads/master | 2020-11-27T00:18:36.676000 | 2019-12-27T10:05:32 | 2019-12-27T10:05:32 | 229,241,271 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.soil.logger.controller;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.annotation.Resource;
@Slf4j
@SpringBootTest(classes = HelloWorldController.class)
@AutoConfigureMockMvc
class HelloWorldControllerTest {
@Resource
private MockMvc mockMvc;
private MvcResult getMvcResult(String url, Object dto) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url).header("Authorization", "token")
.contentType(MediaType.APPLICATION_JSON_UTF8).content("")
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
//.andExpect(MockMvcResultMatchers.content().string("hello world"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
private void responseResult(MvcResult mvcResult) throws Exception {
log.debug("status: {}", mvcResult.getResponse().getStatus());
log.debug("content: {}", mvcResult.getResponse().getContentAsString());
}
@Test
void hello() throws Exception {
responseResult(getMvcResult("/hello",null));
}
} | UTF-8 | Java | 1,706 | java | HelloWorldControllerTest.java | Java | [] | null | [] | package com.soil.logger.controller;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.annotation.Resource;
@Slf4j
@SpringBootTest(classes = HelloWorldController.class)
@AutoConfigureMockMvc
class HelloWorldControllerTest {
@Resource
private MockMvc mockMvc;
private MvcResult getMvcResult(String url, Object dto) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url).header("Authorization", "token")
.contentType(MediaType.APPLICATION_JSON_UTF8).content("")
.accept(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk())
//.andExpect(MockMvcResultMatchers.content().string("hello world"))
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
private void responseResult(MvcResult mvcResult) throws Exception {
log.debug("status: {}", mvcResult.getResponse().getStatus());
log.debug("content: {}", mvcResult.getResponse().getContentAsString());
}
@Test
void hello() throws Exception {
responseResult(getMvcResult("/hello",null));
}
} | 1,706 | 0.739742 | 0.736811 | 42 | 39.642857 | 29.58267 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 9 |
8152c0199cece6d2edf55cfdfff12dd4f3b7b0a5 | 22,600,117,936,529 | 670a4987447467a31703e0d92f041298b800ab07 | /src/main/java/org/hashtable/dp/template/DP32.java | 0774cd3c5855746f74afa7ceab6ac28e141fccfd | [
"Apache-2.0"
] | permissive | seulkikims/hashtable | https://github.com/seulkikims/hashtable | 2f5f9337f24ebd98618ee6e2e78b0c7992c2d917 | e6c4e7959a2c0adfd090d9329445da1252ab4705 | refs/heads/master | 2016-09-05T13:32:38.078000 | 2015-05-29T20:49:42 | 2015-05-29T20:49:44 | 18,306,801 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.hashtable.dp.template;
public class DP32 {
public int solve(int N) {
return -1;
}
}
| UTF-8 | Java | 113 | java | DP32.java | Java | [] | null | [] | package org.hashtable.dp.template;
public class DP32 {
public int solve(int N) {
return -1;
}
}
| 113 | 0.610619 | 0.584071 | 7 | 15.142858 | 12.551933 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 9 |
89ad8e9b0514514351fbf6e483a4b967fb36db3c | 14,113,262,560,079 | ab0915a2349da43e6bf090d0054452ef779c82b0 | /src/main/java/com/bstirbat/sample/electronicstore/model/db/Store.java | b6dd480861e5e18e00c4642e9fc53463a636ae1d | [] | no_license | BogdanStirbat/ElectronicStore | https://github.com/BogdanStirbat/ElectronicStore | e899b25b79d72c22aa9ea550b1eb6da8f226c9cd | 856ec59995044332515553eb0199b357c19149a1 | refs/heads/master | 2020-03-25T07:29:29.352000 | 2018-09-12T19:30:24 | 2018-09-12T19:30:24 | 143,563,898 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bstirbat.sample.electronicstore.model.db;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "stores")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Store {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "address")
private String address;
public Store() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Store{" +
"id=" + id +
", city='" + city + '\'' +
", address='" + address + '\'' +
'}';
}
}
| UTF-8 | Java | 1,383 | java | Store.java | Java | [] | null | [] | package com.bstirbat.sample.electronicstore.model.db;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "stores")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Store {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "address")
private String address;
public Store() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Store{" +
"id=" + id +
", city='" + city + '\'' +
", address='" + address + '\'' +
'}';
}
}
| 1,383 | 0.616775 | 0.616775 | 67 | 19.64179 | 16.542755 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.328358 | false | false | 9 |
17ee1a2a5a47f57409156412f4f207977345b0fc | 23,545,010,756,196 | ca115647260b89e4ce69a0248cea2bd42ec229e6 | /server/central-pivot/src/main/java/com/hptpd/centralpivot/alarm/service/shortmessage/AlarmShortMessageServiceImpl.java | 87c2800e2ab1651b8f8e4469907d88ff8c3559a7 | [] | no_license | tracy4262/detection | https://github.com/tracy4262/detection | 096ec6b12904ddb61a257c6b03c2bb4375e74e35 | 60c6d43534cd28ad134dc8dd706bdf5efca1de53 | refs/heads/master | 2020-03-24T06:08:46.600000 | 2020-03-04T07:08:56 | 2020-03-04T07:08:56 | 142,517,801 | 5 | 7 | null | false | 2019-12-27T19:44:38 | 2018-07-27T02:30:22 | 2019-12-26T02:07:39 | 2019-12-27T19:44:36 | 59,660 | 4 | 2 | 5 | TSQL | false | false | package com.hptpd.centralpivot.alarm.service.shortmessage;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hptpd.centralpivot.alarm.domain.AlarmConfig;
import com.hptpd.centralpivot.alarm.repository.AlarmConfRep;
import com.hptpd.centralpivot.alarm.vo.ProcessingVo;
import com.hptpd.centralpivot.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author YMHUI
*/
@Service("shortMessageService")
public class AlarmShortMessageServiceImpl implements IAlarmShortMessageService {
private Logger logger = LoggerFactory.getLogger(AlarmShortMessageServiceImpl.class);
@Value("${alibaba.short-message.accesskeyid}")
private String shortMessageAccesskeyId;
@Value("${alibaba.short-message.secret}")
private String shortMessageSecret;
@Value("${alibaba.short-message.domain}")
private String shortMessageDomain;
@Value("${alibaba.short-message.action}")
private String shortMessageAction;
@Value("${alibaba.short-message.signname}")
private String shortMessageSignName;
@Value("${alibaba.short-message.temp}")
private String shortMessageTemp;
@Resource
private AlarmConfRep alarmConfRep;
/**
* 发送短信
*
* @param alarmConfig
* @param processingVo
* @return
*/
@Override
public void sendShortMessage(AlarmConfig alarmConfig, ProcessingVo processingVo) {
if (!alarmConfig.getFactorId().equals(processingVo.getFactorId())) {
return;
}
if (!alarmConfig.isMessageEnabled()) {
return;
}
if (alarmConfig.getMessageTimeInterval() == null) {
alarmConfig.setMessageTimeInterval(1);
}
Boolean result = false;
if (alarmConfig.getLastMessageTime() == null || StringUtils.isBlank(alarmConfig.getLastMessageTime())) {
result = sendMessage(alarmConfig, processingVo);
}else if (DateUtil.CompareTime(alarmConfig.getLastMessageTime(), DateUtil.getStrTime()) > alarmConfig.getMessageTimeInterval()) {
result = sendMessage(alarmConfig, processingVo);
}
if (result) {
alarmConfig.setLastMessageTime(DateUtil.getStrTime());
alarmConfRep.save(alarmConfig);
}
}
private Boolean sendMessage(AlarmConfig alarmConfig, ProcessingVo processingVo) {
if (alarmConfig.getPhoneNum() == null || StringUtils.isBlank(alarmConfig.getPhoneNum())) {
return false;
}
DefaultProfile profile = DefaultProfile.getProfile("default", shortMessageAccesskeyId, shortMessageSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain(shortMessageDomain);
request.setVersion("2017-05-25");
request.setAction(shortMessageAction);
request.putQueryParameter("PhoneNumbers", alarmConfig.getPhoneNum());
request.putQueryParameter("SignName", shortMessageSignName);
request.putQueryParameter("TemplateCode", shortMessageTemp);
request.putQueryParameter("TemplateParam", "{\"serviceArea\":\"" + alarmConfig.getServiceArea()
+ "\",\"factor\":\"" + alarmConfig.getFactorName() + "\",\"value\":\"" + processingVo.getValue()
+ "\",\"dateTime\":\"" + processingVo.getTime() + "\"}");
try {
CommonResponse response = client.getCommonResponse(request);
logger.info(response.getData());
return true;
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
| UTF-8 | Java | 4,089 | java | AlarmShortMessageServiceImpl.java | Java | [
{
"context": "import javax.annotation.Resource;\n\n\n/**\n * @author YMHUI\n */\n@Service(\"shortMessageService\")\npublic class ",
"end": 817,
"score": 0.9987017512321472,
"start": 812,
"tag": "USERNAME",
"value": "YMHUI"
}
] | null | [] | package com.hptpd.centralpivot.alarm.service.shortmessage;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hptpd.centralpivot.alarm.domain.AlarmConfig;
import com.hptpd.centralpivot.alarm.repository.AlarmConfRep;
import com.hptpd.centralpivot.alarm.vo.ProcessingVo;
import com.hptpd.centralpivot.common.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author YMHUI
*/
@Service("shortMessageService")
public class AlarmShortMessageServiceImpl implements IAlarmShortMessageService {
private Logger logger = LoggerFactory.getLogger(AlarmShortMessageServiceImpl.class);
@Value("${alibaba.short-message.accesskeyid}")
private String shortMessageAccesskeyId;
@Value("${alibaba.short-message.secret}")
private String shortMessageSecret;
@Value("${alibaba.short-message.domain}")
private String shortMessageDomain;
@Value("${alibaba.short-message.action}")
private String shortMessageAction;
@Value("${alibaba.short-message.signname}")
private String shortMessageSignName;
@Value("${alibaba.short-message.temp}")
private String shortMessageTemp;
@Resource
private AlarmConfRep alarmConfRep;
/**
* 发送短信
*
* @param alarmConfig
* @param processingVo
* @return
*/
@Override
public void sendShortMessage(AlarmConfig alarmConfig, ProcessingVo processingVo) {
if (!alarmConfig.getFactorId().equals(processingVo.getFactorId())) {
return;
}
if (!alarmConfig.isMessageEnabled()) {
return;
}
if (alarmConfig.getMessageTimeInterval() == null) {
alarmConfig.setMessageTimeInterval(1);
}
Boolean result = false;
if (alarmConfig.getLastMessageTime() == null || StringUtils.isBlank(alarmConfig.getLastMessageTime())) {
result = sendMessage(alarmConfig, processingVo);
}else if (DateUtil.CompareTime(alarmConfig.getLastMessageTime(), DateUtil.getStrTime()) > alarmConfig.getMessageTimeInterval()) {
result = sendMessage(alarmConfig, processingVo);
}
if (result) {
alarmConfig.setLastMessageTime(DateUtil.getStrTime());
alarmConfRep.save(alarmConfig);
}
}
private Boolean sendMessage(AlarmConfig alarmConfig, ProcessingVo processingVo) {
if (alarmConfig.getPhoneNum() == null || StringUtils.isBlank(alarmConfig.getPhoneNum())) {
return false;
}
DefaultProfile profile = DefaultProfile.getProfile("default", shortMessageAccesskeyId, shortMessageSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain(shortMessageDomain);
request.setVersion("2017-05-25");
request.setAction(shortMessageAction);
request.putQueryParameter("PhoneNumbers", alarmConfig.getPhoneNum());
request.putQueryParameter("SignName", shortMessageSignName);
request.putQueryParameter("TemplateCode", shortMessageTemp);
request.putQueryParameter("TemplateParam", "{\"serviceArea\":\"" + alarmConfig.getServiceArea()
+ "\",\"factor\":\"" + alarmConfig.getFactorName() + "\",\"value\":\"" + processingVo.getValue()
+ "\",\"dateTime\":\"" + processingVo.getTime() + "\"}");
try {
CommonResponse response = client.getCommonResponse(request);
logger.info(response.getData());
return true;
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
| 4,089 | 0.694683 | 0.691742 | 105 | 37.866665 | 29.770893 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 9 |
93e4e6604313fa8e3ac18d5ecabf4a18b7a331d3 | 27,144,193,328,047 | be469d75f553f0b74f03f6b8b0e44ec59b8f614c | /files/uva/2007.extras/P138.java | 9976b9eac3f4e4567b323b82b6abf95a1bb6ea29 | [] | no_license | barata/prog_contest | https://github.com/barata/prog_contest | 6bf660f9cf7d0bf92b58d471cfe44240c867b534 | ea2f785cab91f0ccac250a2ae5cbaa85a454fedf | refs/heads/master | 2023-08-05T05:13:24.217000 | 2023-07-22T12:30:50 | 2023-07-22T12:30:50 | 34,699,719 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class Main {
public static void main(String[] args) {
// int count = 10;
// long n = 8;
//
// while (count > 0) {
//
// long tmp = (n * n + n) / 2;
// double x = Math.sqrt(tmp);
// long roundX = Math.round(x);
// if (roundX * roundX == tmp) {
// System.out.println(roundX + " " + n);
// count--;
// }
//
// n++;
// }
System.out.println(" 6 8\n 35 49\n 204 288\n 1189 1681\n 6930 9800\n 40391 57121\n 235416 332928\n 1372105 1940449\n 7997214 11309768\n 46611179 65918161");
}
}
| UTF-8 | Java | 603 | java | P138.java | Java | [] | null | [] |
class Main {
public static void main(String[] args) {
// int count = 10;
// long n = 8;
//
// while (count > 0) {
//
// long tmp = (n * n + n) / 2;
// double x = Math.sqrt(tmp);
// long roundX = Math.round(x);
// if (roundX * roundX == tmp) {
// System.out.println(roundX + " " + n);
// count--;
// }
//
// n++;
// }
System.out.println(" 6 8\n 35 49\n 204 288\n 1189 1681\n 6930 9800\n 40391 57121\n 235416 332928\n 1372105 1940449\n 7997214 11309768\n 46611179 65918161");
}
}
| 603 | 0.466003 | 0.300166 | 23 | 25.173914 | 48.411869 | 243 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.478261 | false | false | 9 |
737a2b9191c8bc40c3185b367713b9b923c331e5 | 10,737,418,242,111 | e0a5bebf2692ce94f7480755287a3455b7db2c9e | /dev_web/src/pojo/board/step2/MemberLogic.java | 358ce0cd1d81d7c358eda611b444c159a415be25 | [] | no_license | amazingtmon/java210208 | https://github.com/amazingtmon/java210208 | 92ed7281103f6c45717be17ce933ebdea7ab6327 | a185172aaa22f220d94b64049e657855fcf0943e | refs/heads/master | 2023-06-15T10:04:33.172000 | 2021-07-10T08:43:04 | 2021-07-10T08:43:04 | 336,936,468 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pojo.board.step2;
public class MemberLogic {
}
| UTF-8 | Java | 57 | java | MemberLogic.java | Java | [] | null | [] | package pojo.board.step2;
public class MemberLogic {
}
| 57 | 0.754386 | 0.736842 | 5 | 10.4 | 12.338557 | 26 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 9 |
4dfd69c694473d5489c3aba38cb3d996c933a1e6 | 31,971,736,604,898 | bfd8a18fc1271e716e7501affac9642df2286021 | /src/main/java/com/grupo18sub10/springboot/app/models/service/UsuarioServiceImpl.java | eb3159e33e3d871f3f399b34ee3ec6239ed19264 | [] | no_license | miremos/Grupo18Tienda10 | https://github.com/miremos/Grupo18Tienda10 | d99f384be262a8f3294c2476d8ee6e7c39388aad | 348d212e2289ac1fe51c14d80ad545d6e600532b | refs/heads/master | 2023-08-27T00:45:00.617000 | 2021-10-14T23:58:19 | 2021-10-14T23:58:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.grupo18sub10.springboot.app.models.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.grupo18sub10.springboot.app.models.dao.IUsuarioDao;
import com.grupo18sub10.springboot.app.models.entity.Usuario;
@Service
public class UsuarioServiceImpl implements IUsuarioService {
@Autowired
private IUsuarioDao usuariodao;
@Override
@Transactional(readOnly = true) // Anotacion que solo permite leer el metodo.
public List<Usuario> findAll() {
return (List<Usuario>) usuariodao.findAll();
}
@Override
@Transactional
public void save(Usuario usuario) {
usuariodao.save(usuario);
}
@Override
@Transactional(readOnly = true)
public Usuario findOne(Long cedula_usuario) {
return usuariodao.findById(cedula_usuario).orElse(null);
}
@Override
@Transactional()
public void delete(Long cedula_usuario) {
usuariodao.deleteById(cedula_usuario);
}
@Override
@Transactional(readOnly = true)
public Page<Usuario> findAll(Pageable pageable) {
return usuariodao.findAll(pageable);
}
} | UTF-8 | Java | 1,295 | java | UsuarioServiceImpl.java | Java | [] | null | [] | package com.grupo18sub10.springboot.app.models.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.grupo18sub10.springboot.app.models.dao.IUsuarioDao;
import com.grupo18sub10.springboot.app.models.entity.Usuario;
@Service
public class UsuarioServiceImpl implements IUsuarioService {
@Autowired
private IUsuarioDao usuariodao;
@Override
@Transactional(readOnly = true) // Anotacion que solo permite leer el metodo.
public List<Usuario> findAll() {
return (List<Usuario>) usuariodao.findAll();
}
@Override
@Transactional
public void save(Usuario usuario) {
usuariodao.save(usuario);
}
@Override
@Transactional(readOnly = true)
public Usuario findOne(Long cedula_usuario) {
return usuariodao.findById(cedula_usuario).orElse(null);
}
@Override
@Transactional()
public void delete(Long cedula_usuario) {
usuariodao.deleteById(cedula_usuario);
}
@Override
@Transactional(readOnly = true)
public Page<Usuario> findAll(Pageable pageable) {
return usuariodao.findAll(pageable);
}
} | 1,295 | 0.779151 | 0.769884 | 57 | 21.736841 | 23.160406 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.035088 | false | false | 9 |
08853ba0054d6069305f5e353af9e07430e5fd04 | 27,522,150,436,792 | 7e8894159afb36bfe692c937aa53c51e94d88d7c | /movie_booking/src/com/movie/controller/action/MovieUpdateFormAction.java | afb7118f7ba54729950bfa0d2eecdcd29a00f169 | [] | no_license | gguro/moive_booking | https://github.com/gguro/moive_booking | d0971a0d4b076a0f7644bdf95f36ae973e3a8443 | 2de32e72d2f84e83153df0cac63f759e55f42a0d | refs/heads/master | 2021-05-15T13:26:47.549000 | 2017-10-24T04:53:32 | 2017-10-24T04:53:32 | 107,105,918 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.movie.controller.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.movie.dao.MovieDAO;
import com.movie.dto.MovieDTO;
public class MovieUpdateFormAction implements IAction {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "/movie/movieUpdate.jsp";
String mv_code = request.getParameter("mv_code");
MovieDAO movieDAO = MovieDAO.getInstance();
MovieDTO mDto = movieDAO.selectMovieByTitle(mv_code);
request.setAttribute("movie", mDto);
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| UTF-8 | Java | 918 | java | MovieUpdateFormAction.java | Java | [] | null | [] | package com.movie.controller.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.movie.dao.MovieDAO;
import com.movie.dto.MovieDTO;
public class MovieUpdateFormAction implements IAction {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "/movie/movieUpdate.jsp";
String mv_code = request.getParameter("mv_code");
MovieDAO movieDAO = MovieDAO.getInstance();
MovieDTO mDto = movieDAO.selectMovieByTitle(mv_code);
request.setAttribute("movie", mDto);
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
| 918 | 0.763617 | 0.763617 | 30 | 28.6 | 26.849705 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.366667 | false | false | 9 |
ce689ce229c5f517ee2441d0cf7f4e454779b308 | 18,098,992,226,842 | 33fd417b6e8eae61c22be87e168fdd073cd8cfb0 | /iterator/src/main/java/v22/CafeMenu.java | be008d1be69bc8e5e18225eacca272c7a82d708f | [] | no_license | zzyygg/design-model | https://github.com/zzyygg/design-model | 6469b0392ef4247f4f610fa7e53b3e32812b349b | b483429732d20af8bd0853e5b04a873485ccd286 | refs/heads/master | 2020-05-29T13:58:40.280000 | 2019-07-05T16:01:11 | 2019-07-05T16:01:11 | 189,179,950 | 0 | 0 | null | false | 2020-10-13T13:32:43 | 2019-05-29T08:07:10 | 2019-07-05T16:02:00 | 2020-10-13T13:32:42 | 117 | 0 | 0 | 1 | Java | false | false | package v22;
import base.MenuItem;
import v2.Menu;
import java.util.Hashtable;
import java.util.Iterator;
/**
* @author Guoxj
* @Date 2019/6/15 15:17
* @Version 1.0
*/
public class CafeMenu implements Menu {
Hashtable menuItems = new Hashtable();
public CafeMenu(){
addItem(new MenuItem("猫屎咖啡", "猫的屎做的咖啡", true, 7.5));
addItem(new MenuItem("拿铁", "浓缩咖啡+牛奶", false, 8.0));
addItem(new MenuItem("卡布奇诺", "浓缩咖啡+热牛奶+奶泡", false, 6.2));
addItem(new MenuItem("摩卡", "浓缩咖啡+巧克力糖浆+奶油+牛奶", true, 12));
}
public void addItem(MenuItem item){
menuItems.put(item.getName(), item);
}
public Iterator createIterator() {
return menuItems.values().iterator();
}
}
| UTF-8 | Java | 823 | java | CafeMenu.java | Java | [
{
"context": "htable;\nimport java.util.Iterator;\n\n/**\n * @author Guoxj\n * @Date 2019/6/15 15:17\n * @Version 1.0\n */\npubl",
"end": 129,
"score": 0.9993399977684021,
"start": 124,
"tag": "USERNAME",
"value": "Guoxj"
}
] | null | [] | package v22;
import base.MenuItem;
import v2.Menu;
import java.util.Hashtable;
import java.util.Iterator;
/**
* @author Guoxj
* @Date 2019/6/15 15:17
* @Version 1.0
*/
public class CafeMenu implements Menu {
Hashtable menuItems = new Hashtable();
public CafeMenu(){
addItem(new MenuItem("猫屎咖啡", "猫的屎做的咖啡", true, 7.5));
addItem(new MenuItem("拿铁", "浓缩咖啡+牛奶", false, 8.0));
addItem(new MenuItem("卡布奇诺", "浓缩咖啡+热牛奶+奶泡", false, 6.2));
addItem(new MenuItem("摩卡", "浓缩咖啡+巧克力糖浆+奶油+牛奶", true, 12));
}
public void addItem(MenuItem item){
menuItems.put(item.getName(), item);
}
public Iterator createIterator() {
return menuItems.values().iterator();
}
}
| 823 | 0.624143 | 0.591221 | 32 | 21.78125 | 21.31715 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.78125 | false | false | 9 |
a366094259a2576b64e0da39d339287ebb21ba8b | 14,010,183,351,517 | a99289bfb81665fe0d8c80aa7d51cf637b0b3c5f | /basic/basic.cache/src/main/java/net/yitun/basic/cache/support/serializer/LongRedisSerializer.java | 58ccde19d068a76e25b03cea22758d790b4ec0a5 | [] | no_license | moutainhigh/read-ecommerce-paas | https://github.com/moutainhigh/read-ecommerce-paas | e55bdcd29addb103f7a3f08066f5918029ca501d | 0064106482223800727b56e72db6c1eafaa20bd9 | refs/heads/master | 2023-01-01T05:54:58.629000 | 2019-05-25T01:54:01 | 2019-05-25T01:54:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.yitun.basic.cache.support.serializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import net.yitun.basic.cache.utils.ByteUtil;
public class LongRedisSerializer implements RedisSerializer<Long> {
@Override
public byte[] serialize(Long value) throws SerializationException {
return null == value ? null : ByteUtil.long2Bytes(value.longValue());
}
@Override
public Long deserialize(byte[] bytes) throws SerializationException {
return null == bytes ? null : ByteUtil.bytes2Long(bytes);
}
}
| UTF-8 | Java | 640 | java | LongRedisSerializer.java | Java | [] | null | [] | package net.yitun.basic.cache.support.serializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import net.yitun.basic.cache.utils.ByteUtil;
public class LongRedisSerializer implements RedisSerializer<Long> {
@Override
public byte[] serialize(Long value) throws SerializationException {
return null == value ? null : ByteUtil.long2Bytes(value.longValue());
}
@Override
public Long deserialize(byte[] bytes) throws SerializationException {
return null == bytes ? null : ByteUtil.bytes2Long(bytes);
}
}
| 640 | 0.75625 | 0.753125 | 20 | 31 | 31.565804 | 77 | true | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 9 |
322dac6860d4bb8e8ab8f9f24dcdfc06809986ca | 13,348,758,367,127 | 88035e01ed400a472bcd86173921f42de6e32b9e | /jqh-core/src/main/java/com/jqh/jqh/deletegates/web/WebViewInitializer.java | 9aca6c055a3863688ea8f065d397443f4c5b77b8 | [] | no_license | jiangqianghua/CommonECApp | https://github.com/jiangqianghua/CommonECApp | 0fd48796ef1138019c1384f3c94f07dcd77529bf | 818ea4b7afdb6e3da27267c103fa1e4001d73caf | refs/heads/master | 2021-04-28T10:39:17.048000 | 2019-09-07T06:01:15 | 2019-09-07T06:01:15 | 122,070,725 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jqh.jqh.deletegates.web;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* webview 初始化参数
*/
public class WebViewInitializer {
public WebView createWebView(WebView webView){
// 可以调试,最低19
WebView.setWebContentsDebuggingEnabled(true);
// 不允许横向滚动
webView.setHorizontalScrollBarEnabled(false);
// 不允许纵向滚动
webView.setVerticalScrollBarEnabled(false);
// 允许截图
webView.setDrawingCacheEnabled(true);
// 屏蔽长安事件
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
return true;
}
});
// 初始化settings
final WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
final String ua = settings.getUserAgentString();
settings.setUserAgentString(ua+"Jqh");// 方便判断是我们自己打开的网页
//隐藏缩放控件
settings.setBuiltInZoomControls(false);
settings.setDisplayZoomControls(false);
// 禁止缩放
settings.setSupportZoom(false);
// 文件权限
settings.setAllowFileAccess(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
// 缓存相关
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
return webView;
}
}
| UTF-8 | Java | 1,765 | java | WebViewInitializer.java | Java | [] | null | [] | package com.jqh.jqh.deletegates.web;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* webview 初始化参数
*/
public class WebViewInitializer {
public WebView createWebView(WebView webView){
// 可以调试,最低19
WebView.setWebContentsDebuggingEnabled(true);
// 不允许横向滚动
webView.setHorizontalScrollBarEnabled(false);
// 不允许纵向滚动
webView.setVerticalScrollBarEnabled(false);
// 允许截图
webView.setDrawingCacheEnabled(true);
// 屏蔽长安事件
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
return true;
}
});
// 初始化settings
final WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
final String ua = settings.getUserAgentString();
settings.setUserAgentString(ua+"Jqh");// 方便判断是我们自己打开的网页
//隐藏缩放控件
settings.setBuiltInZoomControls(false);
settings.setDisplayZoomControls(false);
// 禁止缩放
settings.setSupportZoom(false);
// 文件权限
settings.setAllowFileAccess(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
// 缓存相关
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
return webView;
}
}
| 1,765 | 0.654344 | 0.653112 | 53 | 29.622641 | 20.257984 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.490566 | false | false | 9 |
080e152f1615152842f532c111859ef448613e1c | 1,348,619,767,861 | dc8e8c9db3aec667b656c2755ea97af277b29c17 | /computer-database-persistence/src/main/java/persistence/ICompanyDAO.java | 6f4b5c454ecbfed0f0238907ba34906dc8844e80 | [] | no_license | dkrache/computerDatabase | https://github.com/dkrache/computerDatabase | b0dc92ccb66754e0b358219521e9fdfce7de8315 | 1e1d4ff1b7a74ae131c16002d150238481a9057f | refs/heads/master | 2021-01-19T12:36:28.328000 | 2014-11-05T17:08:57 | 2014-11-06T10:41:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package persistence;
import java.util.List;
import core.Company;
/**
* @author excilys
*
*/
public interface ICompanyDAO extends MyBaseRepository<Company, Long> {
/**
* Extract All company
* @return
*/
List<Company> findAll();
} | UTF-8 | Java | 250 | java | ICompanyDAO.java | Java | [
{
"context": "a.util.List;\n\nimport core.Company;\n\n/**\n * @author excilys\n * \n */\npublic interface ICompanyDAO extends MyBa",
"end": 90,
"score": 0.9996357560157776,
"start": 83,
"tag": "USERNAME",
"value": "excilys"
}
] | null | [] | package persistence;
import java.util.List;
import core.Company;
/**
* @author excilys
*
*/
public interface ICompanyDAO extends MyBaseRepository<Company, Long> {
/**
* Extract All company
* @return
*/
List<Company> findAll();
} | 250 | 0.668 | 0.668 | 19 | 12.210526 | 16.46233 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 9 |
b6f618c4fdb2e16f0880d1aa48f0ad69d330922b | 28,681,791,651,046 | 633ba0b02370bb5a9992a983a80e208ca500a4c8 | /final-framework/tests/com/training/sanity/tests/UniformLogin_Test.java | 8af8f597353ea28b27e6267dd321559b29c03302 | [] | no_license | vishalkabre/Uniform | https://github.com/vishalkabre/Uniform | a98b501e17b23fa599de826dc62a3bad1eab1a1a | 239e938b8bcd54fabe902d53182a7302b574fb09 | refs/heads/master | 2022-07-12T18:57:05.622000 | 2019-08-12T11:01:03 | 2019-08-12T11:01:03 | 196,946,325 | 0 | 0 | null | false | 2022-06-29T17:30:32 | 2019-07-15T07:23:25 | 2019-08-12T11:01:05 | 2022-06-29T17:30:29 | 140 | 0 | 0 | 9 | Java | false | false | package com.training.sanity.tests;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.training.generics.ApplicationMethods;
import com.training.generics.ScreenShot;
import com.training.pom.LoginPOM;
import com.training.pom.UniformPOM;
import com.training.pom.UniformProductReturns_POM;
import com.training.pom.UniformRecurringOrders_POM;
import com.training.pom.UniformOrder_POM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
public class UniformLogin_Test {
private WebDriver driver;
private String baseUrl;
private UniformPOM uniformPOM;
private LoginPOM loginPOM;
private UniformOrder_POM uniformorderPOM;
private UniformRecurringOrders_POM uniformrecurringorderPOM;
private UniformProductReturns_POM uniformproductreturnPOM;
private static Properties properties;
private ScreenShot screenShot;
@BeforeClass
public static void setUpBeforeClass() throws IOException {
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@BeforeMethod
public void setUp() throws Exception {
driver = DriverFactory.getDriver(DriverNames.CHROME);
uniformPOM = new UniformPOM(driver);
loginPOM = new LoginPOM(driver);
uniformorderPOM = new UniformOrder_POM(driver);
uniformrecurringorderPOM = new UniformRecurringOrders_POM(driver);
uniformproductreturnPOM = new UniformProductReturns_POM(driver);
baseUrl = properties.getProperty("baseURL");
screenShot = new ScreenShot(driver);
driver.get(baseUrl);
}
@AfterMethod
public void tearDown() throws Exception {
Thread.sleep(5000);
driver.quit();
}
@Test(priority=1, groups = { "simpleTestCases" })
public void loginPassTest() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
System.out.println("Admin logged in in system");
screenShot.captureScreenShot("First");
}
@Test(priority=2, groups = { "simpleTestCases" })
public void deleteOrder() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.deleteOrder();
System.out.println("Scenario to delete Order is comepleted");
screenShot.captureScreenShot("DeleteOrder");
}
@Test(priority=3, groups={"simpleTestCases"})
public void recurring_OrderFilter() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.recurring_OrderFilter();
//appmeth.return_Order();
System.out.println("Scenario to recurring Order Filtered is comepleted");
screenShot.captureScreenShot("Recurring_OrderFilter");
}
@Test(priority=4, groups={"simpleTestCases"})
public void return_Order() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.return_Order();
System.out.println("Scenario to return Order is comepleted");
screenShot.captureScreenShot("Return_Order");
}
}
| UTF-8 | Java | 3,270 | java | UniformLogin_Test.java | Java | [] | null | [] | package com.training.sanity.tests;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.training.generics.ApplicationMethods;
import com.training.generics.ScreenShot;
import com.training.pom.LoginPOM;
import com.training.pom.UniformPOM;
import com.training.pom.UniformProductReturns_POM;
import com.training.pom.UniformRecurringOrders_POM;
import com.training.pom.UniformOrder_POM;
import com.training.utility.DriverFactory;
import com.training.utility.DriverNames;
public class UniformLogin_Test {
private WebDriver driver;
private String baseUrl;
private UniformPOM uniformPOM;
private LoginPOM loginPOM;
private UniformOrder_POM uniformorderPOM;
private UniformRecurringOrders_POM uniformrecurringorderPOM;
private UniformProductReturns_POM uniformproductreturnPOM;
private static Properties properties;
private ScreenShot screenShot;
@BeforeClass
public static void setUpBeforeClass() throws IOException {
properties = new Properties();
FileInputStream inStream = new FileInputStream("./resources/others.properties");
properties.load(inStream);
}
@BeforeMethod
public void setUp() throws Exception {
driver = DriverFactory.getDriver(DriverNames.CHROME);
uniformPOM = new UniformPOM(driver);
loginPOM = new LoginPOM(driver);
uniformorderPOM = new UniformOrder_POM(driver);
uniformrecurringorderPOM = new UniformRecurringOrders_POM(driver);
uniformproductreturnPOM = new UniformProductReturns_POM(driver);
baseUrl = properties.getProperty("baseURL");
screenShot = new ScreenShot(driver);
driver.get(baseUrl);
}
@AfterMethod
public void tearDown() throws Exception {
Thread.sleep(5000);
driver.quit();
}
@Test(priority=1, groups = { "simpleTestCases" })
public void loginPassTest() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
System.out.println("Admin logged in in system");
screenShot.captureScreenShot("First");
}
@Test(priority=2, groups = { "simpleTestCases" })
public void deleteOrder() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.deleteOrder();
System.out.println("Scenario to delete Order is comepleted");
screenShot.captureScreenShot("DeleteOrder");
}
@Test(priority=3, groups={"simpleTestCases"})
public void recurring_OrderFilter() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.recurring_OrderFilter();
//appmeth.return_Order();
System.out.println("Scenario to recurring Order Filtered is comepleted");
screenShot.captureScreenShot("Recurring_OrderFilter");
}
@Test(priority=4, groups={"simpleTestCases"})
public void return_Order() {
ApplicationMethods appmeth = new ApplicationMethods(driver);
appmeth.login();
appmeth.return_Order();
System.out.println("Scenario to return Order is comepleted");
screenShot.captureScreenShot("Return_Order");
}
}
| 3,270 | 0.754434 | 0.751988 | 102 | 30.058823 | 21.619627 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.696078 | false | false | 9 |
c1870fbd9900283f1c6fefd2f71e90308ff5dc7a | 32,117,765,450,686 | c3c385f23fe21a61ae2f583970629fcdc214315d | /src/M1004.java | cebf50b657103172f7e7be1925968f6d5eea8ee2 | [] | no_license | Tiankai-Jiang/LeetCode | https://github.com/Tiankai-Jiang/LeetCode | 121fd82c81f8ee386cde97d5ba0aad5465b3a995 | ce68d7fff21ff77d52b88ffda84df06a7766b062 | refs/heads/master | 2023-02-24T13:56:36.652000 | 2021-02-04T07:46:15 | 2021-02-04T07:46:15 | 265,052,430 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class M1004 {
// For each A[j], try to find the longest subarray.
// If A[i] ~ A[j] has zeros <= K, we continue to increment j.
// If A[i] ~ A[j] has zeros > K, we increment i (as well as j).
public int longestOnes(int[] A, int K) {
int i = 0, j;
for (j = 0; j < A.length; ++j) {
if (A[j] == 0) K--;
if (K < 0 && A[i++] == 0) K++;
}
return j - i;
}
}
| UTF-8 | Java | 435 | java | M1004.java | Java | [] | null | [] | public class M1004 {
// For each A[j], try to find the longest subarray.
// If A[i] ~ A[j] has zeros <= K, we continue to increment j.
// If A[i] ~ A[j] has zeros > K, we increment i (as well as j).
public int longestOnes(int[] A, int K) {
int i = 0, j;
for (j = 0; j < A.length; ++j) {
if (A[j] == 0) K--;
if (K < 0 && A[i++] == 0) K++;
}
return j - i;
}
}
| 435 | 0.448276 | 0.427586 | 14 | 30.071428 | 21.923452 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 9 |
f8b99544e5e8e7cd759291fe6b07e575600d3e4a | 11,725,260,730,532 | 6fc702bc3d8e49592436fe7ca0eb086cae5be647 | /app/src/main/java/com/example/android/tourguideapp/FoodFragment.java | 0cff22f561ae1c9212e5b372094b165dea727855 | [] | no_license | gdlykos/TourGuideApp | https://github.com/gdlykos/TourGuideApp | 1322847df7cc0cd3ded95bb196a3af2efa9221a9 | e2622a487793e3ccbe3fff840a9b52879f744706 | refs/heads/master | 2020-03-08T04:38:38.534000 | 2018-04-03T19:21:53 | 2018-04-03T19:21:53 | 127,927,965 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.tourguideapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.place_list, container, false);
//Create an array list
final ArrayList<Place> places = new ArrayList<Place>();
places.add(new Place(R.string.food_first_address, R.string.food_first_title, R.drawable.a_for_athens));
places.add(new Place(R.string.food_second_address, R.string.food_second_title, R.drawable.rest_360_degrees));
places.add(new Place(R.string.food_third_address, R.string.food_third_title, R.drawable.dinner_in_the_sky));
places.add(new Place(R.string.food_forth_address, R.string.food_forth_title, R.drawable.cinque_wine_deli_bar));
places.add(new Place(R.string.food_fifth_address, R.string.food_fifth_title, R.drawable.aleria_restaurant));
places.add(new Place(R.string.food_sixth_address, R.string.food_sixth_title, R.drawable.funky_gourmet));
places.add(new Place(R.string.food_seventh_address, R.string.food_seventh_title, R.drawable.gb_roof_garden));
// Create an PlaceAdapter, whose data source is a list of Places.
PlaceAdapter adapter = new PlaceAdapter(getActivity(), places, R.color.category_food);
// Find the ListView object with the view ID called list, which is declared in the
// place_list.xmll file.
ListView listView = (ListView) rootView.findViewById(R.id.list);
// Make the ListView use the PlaceAdapter we created above, so that
// it will display the list items for each Place in the list.
listView.setAdapter(adapter);
return rootView;
}
}
| UTF-8 | Java | 2,248 | java | FoodFragment.java | Java | [] | null | [] | package com.example.android.tourguideapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.place_list, container, false);
//Create an array list
final ArrayList<Place> places = new ArrayList<Place>();
places.add(new Place(R.string.food_first_address, R.string.food_first_title, R.drawable.a_for_athens));
places.add(new Place(R.string.food_second_address, R.string.food_second_title, R.drawable.rest_360_degrees));
places.add(new Place(R.string.food_third_address, R.string.food_third_title, R.drawable.dinner_in_the_sky));
places.add(new Place(R.string.food_forth_address, R.string.food_forth_title, R.drawable.cinque_wine_deli_bar));
places.add(new Place(R.string.food_fifth_address, R.string.food_fifth_title, R.drawable.aleria_restaurant));
places.add(new Place(R.string.food_sixth_address, R.string.food_sixth_title, R.drawable.funky_gourmet));
places.add(new Place(R.string.food_seventh_address, R.string.food_seventh_title, R.drawable.gb_roof_garden));
// Create an PlaceAdapter, whose data source is a list of Places.
PlaceAdapter adapter = new PlaceAdapter(getActivity(), places, R.color.category_food);
// Find the ListView object with the view ID called list, which is declared in the
// place_list.xmll file.
ListView listView = (ListView) rootView.findViewById(R.id.list);
// Make the ListView use the PlaceAdapter we created above, so that
// it will display the list items for each Place in the list.
listView.setAdapter(adapter);
return rootView;
}
}
| 2,248 | 0.703737 | 0.701957 | 53 | 41.415092 | 39.123142 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.849057 | false | false | 9 |
e08a1a46861b0b62cc97e7be7c5c8c3da5a851e4 | 12,472,585,036,367 | 90d29be834016e202f50001306d4dba312b13b91 | /BubbleSort/src/com/rainmaker/Main.java | 5cd60c184e563cba10c3b9e5c386045039c87ae3 | [] | no_license | AnastasiaRainMaker/Algorithms | https://github.com/AnastasiaRainMaker/Algorithms | 59d87bf8dafc02d3217e94edb32a5407b1b3d5eb | 738b3495c17464c60f0d2101439487b43a446e7a | refs/heads/master | 2021-09-11T17:04:50.927000 | 2018-04-10T07:15:12 | 2018-04-10T07:15:12 | 114,790,769 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rainmaker;
public class Main {
public static void main(String[] args) {
// write your code here
int[] ar = {4,1,5,2,7,5,8};
for (int i = 0; i < ar.length-1; i++) {
for(int k = 0; k < ar.length - i - 1; k++) {
if (ar[k] > ar[k + 1]) {
int temp = ar[k];
ar[k] = ar[k + 1];
ar[k + 1] = temp;
}
}
}
print(ar);
}
private static void print(int[] ar) {
for (int anAr : ar) {
System.out.print(anAr + " ");
}
}
}
| UTF-8 | Java | 612 | java | Main.java | Java | [] | null | [] | package com.rainmaker;
public class Main {
public static void main(String[] args) {
// write your code here
int[] ar = {4,1,5,2,7,5,8};
for (int i = 0; i < ar.length-1; i++) {
for(int k = 0; k < ar.length - i - 1; k++) {
if (ar[k] > ar[k + 1]) {
int temp = ar[k];
ar[k] = ar[k + 1];
ar[k + 1] = temp;
}
}
}
print(ar);
}
private static void print(int[] ar) {
for (int anAr : ar) {
System.out.print(anAr + " ");
}
}
}
| 612 | 0.375817 | 0.352941 | 25 | 23.48 | 16.881042 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.72 | false | false | 0 |
7a307d4a01507f2640bbb61681cfe40f2dcae5db | 13,228,499,278,668 | e9c12c13221a27d2a8b4da619004b1b8887ab17f | /examples/spacefiller/mapping/PerspectiveOptimizerTest.java | 1e71a8940940af37c9cccb03ffb9d49f8c01faed | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | flowgunso/spacefillerlib | https://github.com/flowgunso/spacefillerlib | 99ad9b189e667906edfcc6205ed73e0362a6b76e | 3e7a44f24156205d4b84e2614dfcea42b2bfba6a | refs/heads/master | 2022-03-27T15:52:36.025000 | 2019-12-21T18:23:39 | 2019-12-21T18:23:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spacefiller.mapping;
import processing.core.PApplet;
import processing.core.PVector;
import spacefiller.graph.Node;
import java.awt.geom.Point2D;
public class PerspectiveOptimizerTest extends PApplet {
public static void main(String[] args) {
main("spacefiller.mapping.PerspectiveOptimizerTest");
}
public void settings() {
size(1920, 1080, P3D);
}
private Mapper mapper;
private Surface transformer;
private PVector[] preTransformPoints;
private PVector[] postTransformPoints;
private Quad actualQuad;
public void setup() {
mapper = Mapper.load(this);
transformer = mapper.createSurface("surface", 10, 10, 50);
preTransformPoints = new PVector[10];
for (int i = 0; i < preTransformPoints.length; i++) {
preTransformPoints[i] = new PVector(
(float) Math.random() * transformer.getPreTransformGrid().getWidth(),
(float) Math.random() * transformer.getPreTransformGrid().getHeight());
}
for (Node n : transformer.getPostTransformGrid().getBoundingQuad().getNodes()) {
n.translate((float) Math.random() * 500 - 250, (float) Math.random() * 500 - 250);
}
actualQuad = transformer.getPostTransformGrid().getBoundingQuad().copy();
postTransformPoints = new PVector[preTransformPoints.length];
for (int i = 0; i < preTransformPoints.length; i++) {
Point2D src = new Point2D.Float(preTransformPoints[i].x, preTransformPoints[i].y);
Point2D dest = transformer.getPerspective().mapDestPoint(src);
postTransformPoints[i] = new PVector((float) dest.getX(), (float) dest.getY());
}
transformer.resetTransform();
// for (Node n : transformer.getPostTransformGrid().getNodes()) {
// n.translate((float) Math.random() * 100 - 50, (float) Math.random() * 100 - 50);
// }
}
public void draw() {
background(0);
pushMatrix();
translate(width/2 - transformer.getPreTransformGrid().getWidth() / 2f, height/2 - transformer.getPreTransformGrid().getHeight() /2f);
transformer.drawToSurface(canvas -> {
canvas.strokeWeight(10);
canvas.stroke(255);
for (PVector p : preTransformPoints) {
canvas.point(p.x, p.y);
}
});
strokeWeight(2);
stroke(255, 0, 0);
for (PVector p : postTransformPoints) {
ellipse(p.x, p.y, 20, 20);
}
strokeWeight(2);
transformer.draw(getGraphics());
transformer.renderUI(getGraphics());
stroke(255, 0, 0);
beginShape();
for (PVector p : actualQuad.getVertices()) {
vertex(p.x, p.y);
}
endShape(CLOSE);
float score = PerspectiveOptimizer.score(transformer, preTransformPoints, postTransformPoints);
PerspectiveOptimizer.optimize(transformer, preTransformPoints, postTransformPoints, 500);
popMatrix();
text(score, 20, 20);
}
@Override
public void keyPressed() {
if (key == ' ') {
transformer.resetTransform();
for (Node n : transformer.getPostTransformGrid().getNodes()) {
n.translate((float) Math.random() * 100 - 50, (float) Math.random() * 100 - 50);
}
}
}
}
| UTF-8 | Java | 3,101 | java | PerspectiveOptimizerTest.java | Java | [] | null | [] | package spacefiller.mapping;
import processing.core.PApplet;
import processing.core.PVector;
import spacefiller.graph.Node;
import java.awt.geom.Point2D;
public class PerspectiveOptimizerTest extends PApplet {
public static void main(String[] args) {
main("spacefiller.mapping.PerspectiveOptimizerTest");
}
public void settings() {
size(1920, 1080, P3D);
}
private Mapper mapper;
private Surface transformer;
private PVector[] preTransformPoints;
private PVector[] postTransformPoints;
private Quad actualQuad;
public void setup() {
mapper = Mapper.load(this);
transformer = mapper.createSurface("surface", 10, 10, 50);
preTransformPoints = new PVector[10];
for (int i = 0; i < preTransformPoints.length; i++) {
preTransformPoints[i] = new PVector(
(float) Math.random() * transformer.getPreTransformGrid().getWidth(),
(float) Math.random() * transformer.getPreTransformGrid().getHeight());
}
for (Node n : transformer.getPostTransformGrid().getBoundingQuad().getNodes()) {
n.translate((float) Math.random() * 500 - 250, (float) Math.random() * 500 - 250);
}
actualQuad = transformer.getPostTransformGrid().getBoundingQuad().copy();
postTransformPoints = new PVector[preTransformPoints.length];
for (int i = 0; i < preTransformPoints.length; i++) {
Point2D src = new Point2D.Float(preTransformPoints[i].x, preTransformPoints[i].y);
Point2D dest = transformer.getPerspective().mapDestPoint(src);
postTransformPoints[i] = new PVector((float) dest.getX(), (float) dest.getY());
}
transformer.resetTransform();
// for (Node n : transformer.getPostTransformGrid().getNodes()) {
// n.translate((float) Math.random() * 100 - 50, (float) Math.random() * 100 - 50);
// }
}
public void draw() {
background(0);
pushMatrix();
translate(width/2 - transformer.getPreTransformGrid().getWidth() / 2f, height/2 - transformer.getPreTransformGrid().getHeight() /2f);
transformer.drawToSurface(canvas -> {
canvas.strokeWeight(10);
canvas.stroke(255);
for (PVector p : preTransformPoints) {
canvas.point(p.x, p.y);
}
});
strokeWeight(2);
stroke(255, 0, 0);
for (PVector p : postTransformPoints) {
ellipse(p.x, p.y, 20, 20);
}
strokeWeight(2);
transformer.draw(getGraphics());
transformer.renderUI(getGraphics());
stroke(255, 0, 0);
beginShape();
for (PVector p : actualQuad.getVertices()) {
vertex(p.x, p.y);
}
endShape(CLOSE);
float score = PerspectiveOptimizer.score(transformer, preTransformPoints, postTransformPoints);
PerspectiveOptimizer.optimize(transformer, preTransformPoints, postTransformPoints, 500);
popMatrix();
text(score, 20, 20);
}
@Override
public void keyPressed() {
if (key == ' ') {
transformer.resetTransform();
for (Node n : transformer.getPostTransformGrid().getNodes()) {
n.translate((float) Math.random() * 100 - 50, (float) Math.random() * 100 - 50);
}
}
}
}
| 3,101 | 0.661077 | 0.632699 | 105 | 28.533333 | 29.495461 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.752381 | false | false | 0 |
608058986399aa8e5b76b6a26dff647d0281b7ee | 13,228,499,278,179 | c0326e5573eed242c25e37db83a9459a0b22fb20 | /src/test/java/com/chen/myo2o/dao/ShopCategoryDaoTest.java | 33c274db329438858cfedf7c49a69e0818958905 | [] | no_license | chenyaowu/spring-boot-myo2o | https://github.com/chenyaowu/spring-boot-myo2o | 049987890df9680a593570cddb37ac59b011db8e | 40e168e2bfebe8202db88cecc18ca8446eba84a7 | refs/heads/master | 2020-05-05T06:44:59.964000 | 2019-04-06T10:19:47 | 2019-04-06T10:19:47 | 179,796,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chen.myo2o.dao;
import com.chen.myo2o.entity.ShopCategory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShopCategoryDaoTest {
@Autowired
private ShopCategoryDao shopCategoryDao;
@Test
public void testQueryShopCategory(){
List<ShopCategory> shopCategoryList = shopCategoryDao.queryShopCategory(null);
assertEquals(1,shopCategoryList.size());
// ShopCategory testCategory = new ShopCategory();
// ShopCategory parentCategory = new ShopCategory();
// parentCategory.setShopCategoryId(1l);
// testCategory.setParent(parentCategory);
// List<ShopCategory> shopCategoryList = shopCategoryDao.queryShopCategory(testCategory);
// assertEquals(1,shopCategoryList.size());
}
}
| UTF-8 | Java | 1,084 | java | ShopCategoryDaoTest.java | Java | [] | null | [] | package com.chen.myo2o.dao;
import com.chen.myo2o.entity.ShopCategory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ShopCategoryDaoTest {
@Autowired
private ShopCategoryDao shopCategoryDao;
@Test
public void testQueryShopCategory(){
List<ShopCategory> shopCategoryList = shopCategoryDao.queryShopCategory(null);
assertEquals(1,shopCategoryList.size());
// ShopCategory testCategory = new ShopCategory();
// ShopCategory parentCategory = new ShopCategory();
// parentCategory.setShopCategoryId(1l);
// testCategory.setParent(parentCategory);
// List<ShopCategory> shopCategoryList = shopCategoryDao.queryShopCategory(testCategory);
// assertEquals(1,shopCategoryList.size());
}
}
| 1,084 | 0.762915 | 0.75738 | 31 | 33.967743 | 25.68856 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.645161 | false | false | 0 |
a7c9502d607b4e2cc6c0d3efbdae4179a4888ee2 | 13,993,003,458,263 | 91b4499c996a5893edd6c50c6bc9d13d0f0c8e9f | /src/com/feng/hello/model/ZyOkModel.java | 4c7257f8ad587ff7cbf76055155bb8e18f6212ff | [] | no_license | zeenzhou/GitHubPro | https://github.com/zeenzhou/GitHubPro | adb3b2b4d6d9f1679245c2882dedd692535d28ba | 90c94752026d4f700eb64c51ca06f2eadb988c3a | refs/heads/master | 2021-01-12T08:57:39.962000 | 2017-08-29T08:55:41 | 2017-08-29T08:55:41 | 76,736,511 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.feng.hello.model;
/**
* Created by zhouliang on 2016/12/18 1:29.
*/
public class ZyOkModel {
}
| UTF-8 | Java | 110 | java | ZyOkModel.java | Java | [
{
"context": "package com.feng.hello.model;\n\n/**\n * Created by zhouliang on 2016/12/18 1:29.\n */\npublic class ZyOkModel {\n",
"end": 58,
"score": 0.9993172287940979,
"start": 49,
"tag": "USERNAME",
"value": "zhouliang"
}
] | null | [] | package com.feng.hello.model;
/**
* Created by zhouliang on 2016/12/18 1:29.
*/
public class ZyOkModel {
}
| 110 | 0.681818 | 0.581818 | 7 | 14.714286 | 15.898915 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 0 |
8549ec2c8ee4ec38a97235290314722619731a93 | 15,109,694,954,527 | 8a9a17c5193bec1617b7de572e24d1e1fe492813 | /src/atm__interface/SignUp2.java | 651050d5a6995eb5c6e95380f46f5a9359e3fdfd | [] | no_license | ChinkeeGupta/ATM-Interface | https://github.com/ChinkeeGupta/ATM-Interface | 3dcd259629675e3b86b548be57f7bee30c0dfc3a | 895eee450988c5172c5348628b4786efdc0de196 | refs/heads/master | 2023-06-11T18:13:24.684000 | 2021-06-29T11:48:16 | 2021-06-29T11:48:16 | 381,304,559 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package atm__interface;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Random;
import javax.swing.JOptionPane;
/**
*
* @author dell
*/
public class SignUp2 extends javax.swing.JFrame {
Random ran = new Random();
long first7 = (ran.nextLong() % 90000000L) + 5040936000000000L;
String cardno = "" + Math.abs(first7);
long first3 = (ran.nextLong() % 9000L) + 1000L;
String pin = "" + Math.abs(first3);
/**
* Creates new form SignUp2
*/
public SignUp2() {
initComponents();
getContentPane().setBackground(Color.WHITE);
jID.setBackground(Color.WHITE);
jaccount.setBackground(Color.WHITE);
joccupation.setBackground(Color.WHITE);
jincome.setBackground(Color.WHITE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jsubmit = new javax.swing.JButton();
jcheck = new javax.swing.JCheckBox();
jcancel = new javax.swing.JButton();
jLabel15 = new javax.swing.JLabel();
jID = new javax.swing.JComboBox<>();
jLabel16 = new javax.swing.JLabel();
jIdNo = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jaccount = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
joccupation = new javax.swing.JComboBox<>();
jincome = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("New Account Application Form");
jsubmit.setBackground(java.awt.Color.black);
jsubmit.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jsubmit.setForeground(java.awt.Color.white);
jsubmit.setText("SUBMIT");
jsubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jsubmitActionPerformed(evt);
}
});
jcheck.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jcheck.setText("I hereby declared that the above entered details correct to the best of my knowledge ");
jcheck.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcheckActionPerformed(evt);
}
});
jcancel.setBackground(java.awt.Color.black);
jcancel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jcancel.setForeground(java.awt.Color.white);
jcancel.setText("CANCEL");
jcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcancelActionPerformed(evt);
}
});
jLabel15.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel15.setText("ID Proof:");
jID.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Aadhaar Card", "PAN Card", "Voter ID", "Passport", " ", " " }));
jID.setBorder(null);
jID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jIDActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel16.setText("ID Number:");
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel2.setText("Account Type:");
jaccount.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Saving Account", "Current Account" }));
jaccount.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jaccountActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel3.setText("Occupation:");
jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel4.setText("Income:");
joccupation.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Salaried", "Self-Employmed", "Business", "Student", "Retired", "Others" }));
jincome.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Null", "<1,50,000", "<2,50,000", "<5,00,000", "Upto 10,00,000", "Above 10,00,000" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(jcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(177, 177, 177))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jcheck)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 710, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jIdNo, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jaccount, javax.swing.GroupLayout.Alignment.LEADING, 0, 292, Short.MAX_VALUE)
.addComponent(jID, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(joccupation, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jincome, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jID, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jIdNo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jaccount, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(joccupation, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jincome, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
.addComponent(jcheck)
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jcheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcheckActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jcheckActionPerformed
private void jcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcancelActionPerformed
// TODO add your handling code here:
Home hm = new Home();
hm.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_jcancelActionPerformed
private void jsubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jsubmitActionPerformed
// TODO add your handling code here:
String idProof = jID.getItemAt(jID.getSelectedIndex());
String idNo = jIdNo.getText();
String account = jaccount.getItemAt(jaccount.getSelectedIndex());
String occupation = joccupation.getItemAt(jaccount.getSelectedIndex());
String income = jincome.getItemAt(jaccount.getSelectedIndex());
try{
if(idNo.isEmpty()){
JOptionPane.showMessageDialog(null, "Please Fill all fields");
}
if(!jcheck.isSelected()){
JOptionPane.showMessageDialog(null, "Fill the checkbox");
}
else
{
Connection con = createConnection.getconnection();
String sql = "insert into signup2(id_proof,id_no,account,occupation,income,cardno,pin) values(?,?,?,?,?,?,?)";
String sql2 = "insert into login(cardno,pin) values(?,?)";
PreparedStatement stmt = con.prepareStatement(sql);
PreparedStatement stmt2 = con.prepareStatement(sql2);
stmt.setString(1,idProof);
stmt.setString(2,idNo);
stmt.setString(3,account);
stmt.setString(4,occupation);
stmt.setString(5,income);
stmt.setString(6,cardno);
stmt.setString(7,pin);
stmt2.setString(1,cardno);
stmt2.setString(2,pin);
stmt.execute();
stmt2.execute();
con.close();
JOptionPane.showMessageDialog(null," Account Created!!" +"\n Card Number: " + cardno + "\n Pin:"+ pin);
new Deposit(pin).setVisible(true);
setVisible(false);
}
}
catch(Exception e)
{
System.out.println(e);
}
}//GEN-LAST:event_jsubmitActionPerformed
private void jIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jIDActionPerformed
private void jaccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jaccountActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jaccountActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SignUp2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> jID;
private javax.swing.JTextField jIdNo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JComboBox<String> jaccount;
private javax.swing.JButton jcancel;
private javax.swing.JCheckBox jcheck;
private javax.swing.JComboBox<String> jincome;
private javax.swing.JComboBox<String> joccupation;
private javax.swing.JButton jsubmit;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 16,757 | java | SignUp2.java | Java | [
{
"context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author dell\n */\npublic class SignUp2 extends javax.swing.JFra",
"end": 376,
"score": 0.9836360812187195,
"start": 372,
"tag": "USERNAME",
"value": "dell"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package atm__interface;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Random;
import javax.swing.JOptionPane;
/**
*
* @author dell
*/
public class SignUp2 extends javax.swing.JFrame {
Random ran = new Random();
long first7 = (ran.nextLong() % 90000000L) + 5040936000000000L;
String cardno = "" + Math.abs(first7);
long first3 = (ran.nextLong() % 9000L) + 1000L;
String pin = "" + Math.abs(first3);
/**
* Creates new form SignUp2
*/
public SignUp2() {
initComponents();
getContentPane().setBackground(Color.WHITE);
jID.setBackground(Color.WHITE);
jaccount.setBackground(Color.WHITE);
joccupation.setBackground(Color.WHITE);
jincome.setBackground(Color.WHITE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jsubmit = new javax.swing.JButton();
jcheck = new javax.swing.JCheckBox();
jcancel = new javax.swing.JButton();
jLabel15 = new javax.swing.JLabel();
jID = new javax.swing.JComboBox<>();
jLabel16 = new javax.swing.JLabel();
jIdNo = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jaccount = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
joccupation = new javax.swing.JComboBox<>();
jincome = new javax.swing.JComboBox<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 36)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("New Account Application Form");
jsubmit.setBackground(java.awt.Color.black);
jsubmit.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jsubmit.setForeground(java.awt.Color.white);
jsubmit.setText("SUBMIT");
jsubmit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jsubmitActionPerformed(evt);
}
});
jcheck.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jcheck.setText("I hereby declared that the above entered details correct to the best of my knowledge ");
jcheck.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcheckActionPerformed(evt);
}
});
jcancel.setBackground(java.awt.Color.black);
jcancel.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jcancel.setForeground(java.awt.Color.white);
jcancel.setText("CANCEL");
jcancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcancelActionPerformed(evt);
}
});
jLabel15.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel15.setText("ID Proof:");
jID.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Aadhaar Card", "PAN Card", "Voter ID", "Passport", " ", " " }));
jID.setBorder(null);
jID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jIDActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel16.setText("ID Number:");
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel2.setText("Account Type:");
jaccount.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Saving Account", "Current Account" }));
jaccount.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jaccountActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel3.setText("Occupation:");
jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel4.setText("Income:");
joccupation.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Salaried", "Self-Employmed", "Business", "Student", "Retired", "Others" }));
jincome.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Null", "<1,50,000", "<2,50,000", "<5,00,000", "Upto 10,00,000", "Above 10,00,000" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(55, 55, 55)
.addComponent(jcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(177, 177, 177))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jcheck)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 710, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel15, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jIdNo, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jaccount, javax.swing.GroupLayout.Alignment.LEADING, 0, 292, Short.MAX_VALUE)
.addComponent(jID, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(joccupation, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jincome, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jID, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jIdNo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jaccount, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(joccupation, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jincome, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
.addComponent(jcheck)
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jsubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcancel, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jcheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcheckActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jcheckActionPerformed
private void jcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcancelActionPerformed
// TODO add your handling code here:
Home hm = new Home();
hm.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_jcancelActionPerformed
private void jsubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jsubmitActionPerformed
// TODO add your handling code here:
String idProof = jID.getItemAt(jID.getSelectedIndex());
String idNo = jIdNo.getText();
String account = jaccount.getItemAt(jaccount.getSelectedIndex());
String occupation = joccupation.getItemAt(jaccount.getSelectedIndex());
String income = jincome.getItemAt(jaccount.getSelectedIndex());
try{
if(idNo.isEmpty()){
JOptionPane.showMessageDialog(null, "Please Fill all fields");
}
if(!jcheck.isSelected()){
JOptionPane.showMessageDialog(null, "Fill the checkbox");
}
else
{
Connection con = createConnection.getconnection();
String sql = "insert into signup2(id_proof,id_no,account,occupation,income,cardno,pin) values(?,?,?,?,?,?,?)";
String sql2 = "insert into login(cardno,pin) values(?,?)";
PreparedStatement stmt = con.prepareStatement(sql);
PreparedStatement stmt2 = con.prepareStatement(sql2);
stmt.setString(1,idProof);
stmt.setString(2,idNo);
stmt.setString(3,account);
stmt.setString(4,occupation);
stmt.setString(5,income);
stmt.setString(6,cardno);
stmt.setString(7,pin);
stmt2.setString(1,cardno);
stmt2.setString(2,pin);
stmt.execute();
stmt2.execute();
con.close();
JOptionPane.showMessageDialog(null," Account Created!!" +"\n Card Number: " + cardno + "\n Pin:"+ pin);
new Deposit(pin).setVisible(true);
setVisible(false);
}
}
catch(Exception e)
{
System.out.println(e);
}
}//GEN-LAST:event_jsubmitActionPerformed
private void jIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jIDActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jIDActionPerformed
private void jaccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jaccountActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jaccountActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SignUp2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SignUp2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> jID;
private javax.swing.JTextField jIdNo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JComboBox<String> jaccount;
private javax.swing.JButton jcancel;
private javax.swing.JCheckBox jcheck;
private javax.swing.JComboBox<String> jincome;
private javax.swing.JComboBox<String> joccupation;
private javax.swing.JButton jsubmit;
// End of variables declaration//GEN-END:variables
}
| 16,757 | 0.62732 | 0.608164 | 337 | 48.724037 | 38.967129 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.952522 | false | false | 0 |
da76a006db0aba376f0c373ebf836e92a438e68e | 19,387,482,382,965 | 47ea2c322bfe11504dffa9232bde41a8e683bf8c | /src/main/java/com/junyang/common/interceptor/SecurityInterceptor.java | b2ce7f4bebaeb69be61ccb98588e8cc8cc20e93b | [] | no_license | gxgwyj/workplatform_mysql | https://github.com/gxgwyj/workplatform_mysql | ff7a44458c53318fe2fdd753b4845451e7fbd388 | 8762659f6dc6658aa00106b5a828b07a3fb3c233 | refs/heads/master | 2021-01-23T06:02:27.651000 | 2018-12-09T13:27:17 | 2018-12-09T13:27:17 | 86,334,627 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.junyang.common.interceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
public class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(true);
// 从session 里面获取用户名的信息
Object obj = session.getAttribute("user");
// 判断如果没有取到用户信息,就跳转到登陆页面,提示用户进行重新登陆提示
response.setContentType("text/html; charset=UTF-8");
if (obj == null || "".equals(obj.toString())) {
PrintWriter out = response.getWriter();
StringBuffer str = new StringBuffer();
str.append("<script>");
str.append("alert(\"操作超时,请重新登录\");");
str.append("window.top.location.href=").append("\""+request.getContextPath()+"\"");
str.append("</script>");
out.print(str.toString());
out.close();
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
super.afterCompletion(request, response, handler, ex);
}
}
| UTF-8 | Java | 1,884 | java | SecurityInterceptor.java | Java | [] | null | [] | package com.junyang.common.interceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
public class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(true);
// 从session 里面获取用户名的信息
Object obj = session.getAttribute("user");
// 判断如果没有取到用户信息,就跳转到登陆页面,提示用户进行重新登陆提示
response.setContentType("text/html; charset=UTF-8");
if (obj == null || "".equals(obj.toString())) {
PrintWriter out = response.getWriter();
StringBuffer str = new StringBuffer();
str.append("<script>");
str.append("alert(\"操作超时,请重新登录\");");
str.append("window.top.location.href=").append("\""+request.getContextPath()+"\"");
str.append("</script>");
out.print(str.toString());
out.close();
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
super.afterCompletion(request, response, handler, ex);
}
}
| 1,884 | 0.713078 | 0.712514 | 48 | 35.958332 | 22.955536 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.729167 | false | false | 0 |
fa587ead04c7f88de3465447bab73e145bae02ac | 21,251,498,190,050 | 9ec85d92a782a694b09dd9778898b75237f57d46 | /AlgorithmTraining/src/day68/Solution1.java | ea8bf879d5a2d41999117e9e567bf42171da1d86 | [] | no_license | anran222/java_study | https://github.com/anran222/java_study | ffdbad29a85c4953f61a65e83e1ab2ebbdb3924b | 13253e82dfc2d9ea4422b53fadf75fbd1971df41 | refs/heads/master | 2021-01-03T09:26:52.005000 | 2020-12-03T13:24:25 | 2020-12-03T13:24:25 | 240,020,182 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day68;
/*
*@Author:anran
*@Date:2020/11/24
*@Version 1.0
* 字符串中找出最长的数字串
*/
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (sc.hasNext()){
String str=sc.next();
print(str);
}
}
public static void print(String str){
if (str==null){
return;
}
int i=0;
int max=0;
int k=0;
while (i<str.length()){
if (str.charAt(i)>='0'&&str.charAt(i)<='9'){
int j=i;
int count=0;
while (j<str.length()){
if (str.charAt(j)>='0'&&str.charAt(j)<='9'){
count++;
j++;
}else {
break;
}
}
if (count>max){
max=count;
k=i;
}
i=j+1;
}else {
i++;
}
}
System.out.println(str.substring(k,k+max));
}
}
| UTF-8 | Java | 1,169 | java | Solution1.java | Java | [
{
"context": "package day68;\n/*\n *@Author:anran\n *@Date:2020/11/24\n *@Version 1.0\n * 字符串中找出最长的数字串",
"end": 33,
"score": 0.9996042251586914,
"start": 28,
"tag": "USERNAME",
"value": "anran"
}
] | null | [] | package day68;
/*
*@Author:anran
*@Date:2020/11/24
*@Version 1.0
* 字符串中找出最长的数字串
*/
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while (sc.hasNext()){
String str=sc.next();
print(str);
}
}
public static void print(String str){
if (str==null){
return;
}
int i=0;
int max=0;
int k=0;
while (i<str.length()){
if (str.charAt(i)>='0'&&str.charAt(i)<='9'){
int j=i;
int count=0;
while (j<str.length()){
if (str.charAt(j)>='0'&&str.charAt(j)<='9'){
count++;
j++;
}else {
break;
}
}
if (count>max){
max=count;
k=i;
}
i=j+1;
}else {
i++;
}
}
System.out.println(str.substring(k,k+max));
}
}
| 1,169 | 0.367686 | 0.348472 | 49 | 22.367348 | 14.075153 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.408163 | false | false | 0 |
c5676595589dda4da9f27837b64a32fa4592a75b | 23,914,377,912,445 | d87480d4230c7fa24ee36ede5aabee7f7f7949e1 | /src/Entidades/Cliente.java | 87bd92a7da82748e464d47154b55ec77d16daf21 | [] | no_license | jacqli/tcc-consul | https://github.com/jacqli/tcc-consul | 94da1a6d2403a7ea028d784ea1d10a5f6a5bfbb0 | 3210d2a7ed5a763becdfa693fef4ba1b2fa14807 | refs/heads/master | 2020-03-18T07:47:05.354000 | 2018-09-11T19:44:20 | 2018-09-11T19:44:20 | 134,472,786 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package Entidades;
import javax.persistence.Entity;
@Entity
public class Cliente extends Pessoa {
private int rg;
private String CPF;
private String camImg;
public int getRg() {
return rg;
}
public void setRg(int rg) {
this.rg = rg;
}
public String getCPF() {
return CPF;
}
public void setCPF(String CPF) {
this.CPF = CPF;
}
public String getCamImg() {
return camImg;
}
public void setCamImg(String camImg) {
this.camImg = camImg;
}
}
| UTF-8 | Java | 589 | java | Cliente.java | Java | [] | null | [] |
package Entidades;
import javax.persistence.Entity;
@Entity
public class Cliente extends Pessoa {
private int rg;
private String CPF;
private String camImg;
public int getRg() {
return rg;
}
public void setRg(int rg) {
this.rg = rg;
}
public String getCPF() {
return CPF;
}
public void setCPF(String CPF) {
this.CPF = CPF;
}
public String getCamImg() {
return camImg;
}
public void setCamImg(String camImg) {
this.camImg = camImg;
}
}
| 589 | 0.543294 | 0.543294 | 35 | 14.771428 | 13.14118 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.314286 | false | false | 0 |
83573ad032d08e06c788b77c618472320a415a91 | 5,334,349,393,500 | 6fb5af20625f9fbfe8763d5f0c30aefa72f1956f | /src/client/dost/setup/client/ui/AboutPanel.java | d868f08f4aaa460e753f37d0e6769a037e58824f | [] | no_license | jkdeveyra/CMSC-128-SETUP-PMS | https://github.com/jkdeveyra/CMSC-128-SETUP-PMS | 3ad9ba646fb773a58a3c6a726e2f097a9f88c3c3 | 16bf62202dec80454937ef267919832b963c0564 | HEAD | 2019-03-10T03:21:30.722000 | 2011-03-31T18:53:59 | 2011-03-31T18:53:59 | 1,284,928 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dost.setup.client.ui;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.Font;
public class AboutPanel{
/**
* Create the panel.
*/
private NavigationManager navigationManager;
private JPanel mainPanel;
private JPanel toolbarPanel;
private JPanel tablePanel;
private Color lightBlue = new Color(220, 230, 245);
private JLabel lblDostSetup;
private JLabel lblSetupVision;
private JLabel lblSetupProje;
public AboutPanel(NavigationManager navigationManager) {
this.navigationManager = navigationManager;
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.setBackground(lightBlue);
mainPanel.setBounds(0, 0, 780, 500);
toolbarPanel = new JPanel();
toolbarPanel.setLayout(null);
toolbarPanel.setBackground(Color.WHITE);
toolbarPanel.setBounds(10, 11, 760, 42);
mainPanel.add(toolbarPanel);
lblSetupProje = new JLabel("Small Enterprise Technology Upgrading Program (SET-UP)");
lblSetupProje.setFont(new Font("Segoe UI Semibold", Font.PLAIN, 18));
lblSetupProje.setBounds(21, 0, 637, 42);
toolbarPanel.add(lblSetupProje);
tablePanel = new JPanel();
tablePanel.setLayout(null);
tablePanel.setBackground(Color.WHITE);
tablePanel.setBounds(10, 64, 760, 425);
mainPanel.add(tablePanel);
lblDostSetup = new JLabel("SET-UP Mission");
lblDostSetup.setFont(new Font("Segoe UI", Font.ITALIC, 16));
lblDostSetup.setBounds(25, 49, 194, 14);
tablePanel.add(lblDostSetup);
lblSetupVision = new JLabel("SET-UP Vision");
lblSetupVision.setFont(new Font("Segoe UI", Font.ITALIC, 16));
lblSetupVision.setBounds(25, 252, 194, 14);
tablePanel.add(lblSetupVision);
}
public JPanel getMainPanel() {
return mainPanel;
}
public void update() {
resize();
layout();
repaint();
}
private void resize() {
mainPanel.setSize(new Dimension(navigationManager.getMainFrame().getWidth(),
navigationManager.getMainFrame().getHeight()));
toolbarPanel.setSize(new Dimension(mainPanel.getWidth() - 60, toolbarPanel.getHeight()));
tablePanel.setSize(new Dimension(mainPanel.getWidth() - 60, mainPanel.getHeight() - 235));
}
private void layout() {
}
private void repaint() {
mainPanel.repaint();
tablePanel.repaint();
}
}
| UTF-8 | Java | 2,464 | java | AboutPanel.java | Java | [] | null | [] | package dost.setup.client.ui;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.Font;
public class AboutPanel{
/**
* Create the panel.
*/
private NavigationManager navigationManager;
private JPanel mainPanel;
private JPanel toolbarPanel;
private JPanel tablePanel;
private Color lightBlue = new Color(220, 230, 245);
private JLabel lblDostSetup;
private JLabel lblSetupVision;
private JLabel lblSetupProje;
public AboutPanel(NavigationManager navigationManager) {
this.navigationManager = navigationManager;
mainPanel = new JPanel();
mainPanel.setLayout(null);
mainPanel.setBackground(lightBlue);
mainPanel.setBounds(0, 0, 780, 500);
toolbarPanel = new JPanel();
toolbarPanel.setLayout(null);
toolbarPanel.setBackground(Color.WHITE);
toolbarPanel.setBounds(10, 11, 760, 42);
mainPanel.add(toolbarPanel);
lblSetupProje = new JLabel("Small Enterprise Technology Upgrading Program (SET-UP)");
lblSetupProje.setFont(new Font("Segoe UI Semibold", Font.PLAIN, 18));
lblSetupProje.setBounds(21, 0, 637, 42);
toolbarPanel.add(lblSetupProje);
tablePanel = new JPanel();
tablePanel.setLayout(null);
tablePanel.setBackground(Color.WHITE);
tablePanel.setBounds(10, 64, 760, 425);
mainPanel.add(tablePanel);
lblDostSetup = new JLabel("SET-UP Mission");
lblDostSetup.setFont(new Font("Segoe UI", Font.ITALIC, 16));
lblDostSetup.setBounds(25, 49, 194, 14);
tablePanel.add(lblDostSetup);
lblSetupVision = new JLabel("SET-UP Vision");
lblSetupVision.setFont(new Font("Segoe UI", Font.ITALIC, 16));
lblSetupVision.setBounds(25, 252, 194, 14);
tablePanel.add(lblSetupVision);
}
public JPanel getMainPanel() {
return mainPanel;
}
public void update() {
resize();
layout();
repaint();
}
private void resize() {
mainPanel.setSize(new Dimension(navigationManager.getMainFrame().getWidth(),
navigationManager.getMainFrame().getHeight()));
toolbarPanel.setSize(new Dimension(mainPanel.getWidth() - 60, toolbarPanel.getHeight()));
tablePanel.setSize(new Dimension(mainPanel.getWidth() - 60, mainPanel.getHeight() - 235));
}
private void layout() {
}
private void repaint() {
mainPanel.repaint();
tablePanel.repaint();
}
}
| 2,464 | 0.685065 | 0.654221 | 92 | 25.782608 | 22.727032 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380435 | false | false | 0 |
a27912d8f2eb2062b53bd9cf1bbefec81b79ac59 | 3,848,290,709,490 | f2bb1ebe932c23862c37f844f122dd9d9f6b30a5 | /SpringAndMybatisProject/src/com/one/test/testMybatis.java | 8808788ee38092af709759ea302a18a258b299bd | [] | no_license | 0xching/SpringProject | https://github.com/0xching/SpringProject | e39e1c6665a822d297870726cbb7f4c2bef78825 | 53755ca307f958bfa309f1e6405f3867f446edc4 | refs/heads/master | 2023-02-27T15:31:54.294000 | 2021-02-06T05:13:44 | 2021-02-06T05:13:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.one.test;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.one.entity.Grade;
import com.one.entity.Student;
import com.one.entity.StudentBusiness;
import com.one.entity.StudentCard;
import com.one.entity.StudentClass;
import com.one.mapper.StudentMapper;
public class testMybatis {
public static void main(String[] args) throws IOException {
// queryStudentById();
// queryAllStudent();
// queryStudentByIdWithConverter();
// queryCountByNameProcedure();
// queryStudentByIdWithHashMap();
// queryStuByNameOrAgeWithSQLTag();
// queryStudentsWithIdInGrade();
// queryStudentsWithArray();
// queryStudentsWithList();
// queryStudentsWithObjectArray();
// queryStudentByIdWithOTO();
// queryStudentByIdWithOTO2();
// queryClassAndStudents();
// queryStudentWithOTO2Lazyload();
queryAllClassAndStudents();
// addStudent();
// updateStudentById();
// delStudentById();
// queryAllStudent();
}
// 利用resultMap实现 一对一查询 延迟加载
public static void queryAllClassAndStudents() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<StudentClass> studentClass = studentMapper.queryAllClassAndStudents();
for(StudentClass stuClass:studentClass) {
System.out.println(stuClass);
List<Student> students = stuClass.getStudents();
for(Student student:students) {
System.out.println(student);
}
}
session.close();
}
// 利用resultMap实现 一对一查询 延迟加载
public static void queryStudentWithOTO2Lazyload() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Student> students = studentMapper.queryStudentWithOTO2Lazyload();
for(Student student:students) {
System.out.println(student);
StudentCard card = student.getCard();
System.out.println(card);
}
session.close();
}
//一對多
public static void queryClassAndStudents() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentClass students = studentMapper.queryClassAndStudents(1);
System.out.println(students);
session.close();
}
// 利用resultMap实现 一对一查询
public static void queryStudentByIdWithOTO2() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentByIdWithOTO2(2);
System.out.println(student);
session.close();
}
// 利用业务扩展类实现 一对一查询
public static void queryStudentByIdWithOTO() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentBusiness student = studentMapper.queryStudentByIdWithOTO(2);
System.out.println(student);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithObjectArray() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student stu1 = new Student();
stu1.setId(1);
Student stu3 = new Student();
stu3.setId(3);
Student stu4 = new Student();
stu4.setId(4);
Student[] stuIds = { stu1, stu3, stu4 };
List<Student> students = studentMapper.queryStudentsWithObjectArray(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithList() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Integer> stuIds = new ArrayList<>();
stuIds.add(2);
stuIds.add(4);
List<Student> students = studentMapper.queryStudentsWithList(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithArray() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
int[] stuIds = { 2, 4 };
List<Student> students = studentMapper.queryStudentsWithArray(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入对象的属性中
public static void queryStudentsWithIdInGrade() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Grade grade = new Grade();
List<Integer> stuIds = new ArrayList();
stuIds.add(2);
// stuIds.add(3);
stuIds.add(4);
grade.setStuIds(stuIds);
List<Student> students = studentMapper.queryStudentsWithIdInGrade(grade);
System.out.println(students);
session.close();
}
// 动态SQL标签
public static void queryStuByNameOrAgeWithSQLTag() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student stu = new Student();
// stu.setName("zs");
stu.setAge(23);
List<Student> students = studentMapper.queryStuByNameOrAgeWithSQLTag(stu);
System.out.println(students);
session.close();
}
// resultType+HashMap
public static void queryStudentByIdWithHashMap() throws IOException {
// 加载Mybatis配置文件(为了访问数据库)
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Map<String, Object>> students = studentMapper.queryStudentByIdWithHashMap(1);
System.out.println(students);
session.close();
}
// 调用存储过程
public static void queryCountByNameProcedure() throws IOException {
// 加载Mybatis配置文件(为了访问数据库)
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Map<String, Object> params = new HashMap();
params.put("age", 23);
studentMapper.queryCountByAgeWithProcedure(params);// 接口中的方法-》SQL语句
Object count = params.get("scount");
System.out.println(count);
session.close();
}
// 查询单个学生(转换器)
public static void queryStudentByIdWithConverter() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// 1
// String statement = "com.one.mapper.studentMapper.queryStudentById";
// Student student = session.selectOne(statement, 1);
// 2
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentByIdWithConverter(1);// 接口中的方法-》SQL语句
System.out.println(student);
session.close();
}
// 查询单个学生
public static void queryStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// 1
// String statement = "com.one.mapper.studentMapper.queryStudentById";
// Student student = session.selectOne(statement, 1);
// 2
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentById(1);// 接口中的方法-》SQL语句
System.out.println(student);
session.close();
}
// 查询全部学生
public static void queryAllStudent() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.queryAllStudent";
// List<Student> students = session.selectList(statement);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Student> students = studentMapper.queryAllStudent();
System.out.println(students);
session.close();
}
// 增加学生
public static void addStudent() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.addStudent";
// Student student = new Student(2,"ls",24);
Student student = new Student(3, "ww", 25, true);
// int count = session.insert(statement, student);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.addStudent(student);
session.commit();// 提交事务
System.out.println("增加成功");
session.close();
}
// 修改学生
public static void updateStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.updateStudentById";
Student student = new Student();
student.setId(2);
student.setName("ls");
student.setAge(24);
// int count = session.update(statement, student);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.updateStudentById(student);
session.commit();
System.out.println("修改成功");
session.close();
}
// 删除学生
public static void delStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.delStudentById";
// int count = session.delete(statement, 3);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.delStudentById(3);
session.commit();
System.out.println("删除成功");
session.close();
}
}
| UTF-8 | Java | 13,735 | java | testMybatis.java | Java | [
{
"context": "\n\t\tStudent stu = new Student();\r\n//\t\tstu.setName(\"zs\");\r\n\t\tstu.setAge(23);\r\n\t\tList<Student> students =",
"end": 7417,
"score": 0.5008252859115601,
"start": 7415,
"tag": "NAME",
"value": "zs"
},
{
"context": "udent();\r\n\t\tstudent.setId(2);\r\n\t\tstudent.setName(\"ls\");\r\n\t\tstudent.setAge(24);\r\n//\t\tint count = sessio",
"end": 11979,
"score": 0.6090941429138184,
"start": 11977,
"tag": "NAME",
"value": "ls"
}
] | null | [] | package com.one.test;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.one.entity.Grade;
import com.one.entity.Student;
import com.one.entity.StudentBusiness;
import com.one.entity.StudentCard;
import com.one.entity.StudentClass;
import com.one.mapper.StudentMapper;
public class testMybatis {
public static void main(String[] args) throws IOException {
// queryStudentById();
// queryAllStudent();
// queryStudentByIdWithConverter();
// queryCountByNameProcedure();
// queryStudentByIdWithHashMap();
// queryStuByNameOrAgeWithSQLTag();
// queryStudentsWithIdInGrade();
// queryStudentsWithArray();
// queryStudentsWithList();
// queryStudentsWithObjectArray();
// queryStudentByIdWithOTO();
// queryStudentByIdWithOTO2();
// queryClassAndStudents();
// queryStudentWithOTO2Lazyload();
queryAllClassAndStudents();
// addStudent();
// updateStudentById();
// delStudentById();
// queryAllStudent();
}
// 利用resultMap实现 一对一查询 延迟加载
public static void queryAllClassAndStudents() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<StudentClass> studentClass = studentMapper.queryAllClassAndStudents();
for(StudentClass stuClass:studentClass) {
System.out.println(stuClass);
List<Student> students = stuClass.getStudents();
for(Student student:students) {
System.out.println(student);
}
}
session.close();
}
// 利用resultMap实现 一对一查询 延迟加载
public static void queryStudentWithOTO2Lazyload() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Student> students = studentMapper.queryStudentWithOTO2Lazyload();
for(Student student:students) {
System.out.println(student);
StudentCard card = student.getCard();
System.out.println(card);
}
session.close();
}
//一對多
public static void queryClassAndStudents() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentClass students = studentMapper.queryClassAndStudents(1);
System.out.println(students);
session.close();
}
// 利用resultMap实现 一对一查询
public static void queryStudentByIdWithOTO2() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentByIdWithOTO2(2);
System.out.println(student);
session.close();
}
// 利用业务扩展类实现 一对一查询
public static void queryStudentByIdWithOTO() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentBusiness student = studentMapper.queryStudentByIdWithOTO(2);
System.out.println(student);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithObjectArray() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student stu1 = new Student();
stu1.setId(1);
Student stu3 = new Student();
stu3.setId(3);
Student stu4 = new Student();
stu4.setId(4);
Student[] stuIds = { stu1, stu3, stu4 };
List<Student> students = studentMapper.queryStudentsWithObjectArray(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithList() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Integer> stuIds = new ArrayList<>();
stuIds.add(2);
stuIds.add(4);
List<Student> students = studentMapper.queryStudentsWithList(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入数组中 int[]
public static void queryStudentsWithArray() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
int[] stuIds = { 2, 4 };
List<Student> students = studentMapper.queryStudentsWithArray(stuIds);
System.out.println(students);
session.close();
}
// 将多个元素值 放入对象的属性中
public static void queryStudentsWithIdInGrade() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Grade grade = new Grade();
List<Integer> stuIds = new ArrayList();
stuIds.add(2);
// stuIds.add(3);
stuIds.add(4);
grade.setStuIds(stuIds);
List<Student> students = studentMapper.queryStudentsWithIdInGrade(grade);
System.out.println(students);
session.close();
}
// 动态SQL标签
public static void queryStuByNameOrAgeWithSQLTag() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student stu = new Student();
// stu.setName("zs");
stu.setAge(23);
List<Student> students = studentMapper.queryStuByNameOrAgeWithSQLTag(stu);
System.out.println(students);
session.close();
}
// resultType+HashMap
public static void queryStudentByIdWithHashMap() throws IOException {
// 加载Mybatis配置文件(为了访问数据库)
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Map<String, Object>> students = studentMapper.queryStudentByIdWithHashMap(1);
System.out.println(students);
session.close();
}
// 调用存储过程
public static void queryCountByNameProcedure() throws IOException {
// 加载Mybatis配置文件(为了访问数据库)
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Map<String, Object> params = new HashMap();
params.put("age", 23);
studentMapper.queryCountByAgeWithProcedure(params);// 接口中的方法-》SQL语句
Object count = params.get("scount");
System.out.println(count);
session.close();
}
// 查询单个学生(转换器)
public static void queryStudentByIdWithConverter() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// 1
// String statement = "com.one.mapper.studentMapper.queryStudentById";
// Student student = session.selectOne(statement, 1);
// 2
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentByIdWithConverter(1);// 接口中的方法-》SQL语句
System.out.println(student);
session.close();
}
// 查询单个学生
public static void queryStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
// 可通过build的第二个参数指定数据库环境
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// 1
// String statement = "com.one.mapper.studentMapper.queryStudentById";
// Student student = session.selectOne(statement, 1);
// 2
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
Student student = studentMapper.queryStudentById(1);// 接口中的方法-》SQL语句
System.out.println(student);
session.close();
}
// 查询全部学生
public static void queryAllStudent() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.queryAllStudent";
// List<Student> students = session.selectList(statement);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Student> students = studentMapper.queryAllStudent();
System.out.println(students);
session.close();
}
// 增加学生
public static void addStudent() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.addStudent";
// Student student = new Student(2,"ls",24);
Student student = new Student(3, "ww", 25, true);
// int count = session.insert(statement, student);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.addStudent(student);
session.commit();// 提交事务
System.out.println("增加成功");
session.close();
}
// 修改学生
public static void updateStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.updateStudentById";
Student student = new Student();
student.setId(2);
student.setName("ls");
student.setAge(24);
// int count = session.update(statement, student);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.updateStudentById(student);
session.commit();
System.out.println("修改成功");
session.close();
}
// 删除学生
public static void delStudentById() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
// String statement = "com.one.mapper.studentMapper.delStudentById";
// int count = session.delete(statement, 3);
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
studentMapper.delStudentById(3);
session.commit();
System.out.println("删除成功");
session.close();
}
}
| 13,735 | 0.737816 | 0.733774 | 435 | 27.574713 | 27.815001 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.703448 | false | false | 0 |
177649368b780c1dfad53ef1b35c36d89ecde620 | 4,982,162,073,365 | 8078d926a3c1eb7419e80d439f563d9b3e27fa1d | /JavaSolution/src/session2/q148_sort_list/Solution2.java | 5267ed52db73f77892ef2e5d716338bc52fc7355 | [] | no_license | zhhgit/leetcode_solution_java | https://github.com/zhhgit/leetcode_solution_java | e98d5586b3ff2d7b0ea7f12eb4e25bdb9438ed00 | b7e8bb372fa59086fc1555a1322ee756df57d308 | refs/heads/master | 2021-09-29T18:04:43.146000 | 2021-09-09T06:40:23 | 2021-09-09T06:40:23 | 107,952,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package session2.q148_sort_list;
import session2.common.ListBuilder;
import session2.common.ListNode;
import session2.common.PrintUtil;
public class Solution2 {
public static void main(String[] args){
int[] nums = {3,5,7,1,3,2};
ListBuilder listBuilder = new ListBuilder(nums);
PrintUtil.printList(sortList(listBuilder.getHead()));
}
private static ListNode sortList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode fast = head;
ListNode slow = head;
while (slow.next != null && fast.next != null && fast.next.next!= null){
slow = slow.next;
fast = fast.next.next;
}
ListNode head1 = head;
ListNode head2 = slow.next;
slow.next = null;
head1 = sortList(head1);
head2 = sortList(head2);
return merge(head1,head2);
}
//总长度为偶数时,head1与head2一样长;总长度为奇数时,head1比head2长1;
private static ListNode merge(ListNode head1,ListNode head2){
ListNode curr1 = head1;
ListNode curr2 = head2;
ListNode fakeHead = new ListNode(0);
ListNode curr = fakeHead;
while (curr1 != null && curr2 != null){
if(curr1.val <= curr2.val){
curr.next = curr1;
curr1 = curr1.next;
}
else{
curr.next = curr2;
curr2 = curr2.next;
}
curr = curr.next;
}
if(curr1 == null){
curr.next = curr2;
}
else {
curr.next = curr1;
}
return fakeHead.next;
}
}
| UTF-8 | Java | 1,755 | java | Solution2.java | Java | [] | null | [] | package session2.q148_sort_list;
import session2.common.ListBuilder;
import session2.common.ListNode;
import session2.common.PrintUtil;
public class Solution2 {
public static void main(String[] args){
int[] nums = {3,5,7,1,3,2};
ListBuilder listBuilder = new ListBuilder(nums);
PrintUtil.printList(sortList(listBuilder.getHead()));
}
private static ListNode sortList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode fast = head;
ListNode slow = head;
while (slow.next != null && fast.next != null && fast.next.next!= null){
slow = slow.next;
fast = fast.next.next;
}
ListNode head1 = head;
ListNode head2 = slow.next;
slow.next = null;
head1 = sortList(head1);
head2 = sortList(head2);
return merge(head1,head2);
}
//总长度为偶数时,head1与head2一样长;总长度为奇数时,head1比head2长1;
private static ListNode merge(ListNode head1,ListNode head2){
ListNode curr1 = head1;
ListNode curr2 = head2;
ListNode fakeHead = new ListNode(0);
ListNode curr = fakeHead;
while (curr1 != null && curr2 != null){
if(curr1.val <= curr2.val){
curr.next = curr1;
curr1 = curr1.next;
}
else{
curr.next = curr2;
curr2 = curr2.next;
}
curr = curr.next;
}
if(curr1 == null){
curr.next = curr2;
}
else {
curr.next = curr1;
}
return fakeHead.next;
}
}
| 1,755 | 0.530756 | 0.503222 | 61 | 26.983606 | 17.073124 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622951 | false | false | 0 |
6deebe37c5ffe9ec0df5f3a684d8518b978e4700 | 22,419,729,296,655 | 9a9dff0f7af4e2bf52e3b3ff34110e6ff00d2b0a | /app/src/main/java/com/example/countries/data/remote/Api.java | e74a7d34d58534f58e12ca4b44e3f925705de379 | [] | no_license | AlexandrSushkov/Countries | https://github.com/AlexandrSushkov/Countries | 23767e8e12ccff2469d351e02f94cd684a060785 | 18af5856ccd6b99c1864cb5ba4fd4aec223f02d0 | refs/heads/master | 2020-04-30T10:22:04.396000 | 2019-03-20T16:24:38 | 2019-03-20T16:24:38 | 176,775,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.countries.data.remote;
import com.example.countries.data.model.Country;
import java.util.List;
import io.reactivex.Single;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Api {
@GET("all")
Single<List<Country>> getAllCountries();
@GET("alpha")
Single<List<Country>> getCountriesByCodes(@Query("codes") String countriesCodes);
}
| UTF-8 | Java | 424 | java | Api.java | Java | [] | null | [] | package com.example.countries.data.remote;
import com.example.countries.data.model.Country;
import java.util.List;
import io.reactivex.Single;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface Api {
@GET("all")
Single<List<Country>> getAllCountries();
@GET("alpha")
Single<List<Country>> getCountriesByCodes(@Query("codes") String countriesCodes);
}
| 424 | 0.747642 | 0.740566 | 20 | 20.200001 | 21.759136 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 0 |
f785d7c31a53bf58ab53f9312c313868467dc340 | 12,025,908,442,922 | 7a947d213bb122e39a55261368a1b26a22ac57ba | /src/InterpLamCTests.java | 6b42dc397adaeece1e64c2864e1f83d63b85bd5a | [] | no_license | xeon13/430Assignment6 | https://github.com/xeon13/430Assignment6 | 284e4f59747f61f0cb420bfc7989e1a6964c18b9 | a3d85f4457f779cedb19fc02fc9551d3bfa0f6ab | refs/heads/master | 2021-01-22T11:36:34.514000 | 2014-05-27T19:44:31 | 2014-05-27T19:44:31 | 20,033,932 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
public class InterpLamCTests {
@Test
public void test() {
Driver d = new Driver();
Environment env = new Environment();
List<String> args = new LinkedList<String>();
args.add("x");
try {
assertEquals(d.interp(new lamC(args, new numC(7)), env), new closV(args, new numC(7), env));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 566 | java | InterpLamCTests.java | Java | [] | null | [] | import static org.junit.Assert.*;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
public class InterpLamCTests {
@Test
public void test() {
Driver d = new Driver();
Environment env = new Environment();
List<String> args = new LinkedList<String>();
args.add("x");
try {
assertEquals(d.interp(new lamC(args, new numC(7)), env), new closV(args, new numC(7), env));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 566 | 0.600707 | 0.597173 | 26 | 20.76923 | 22.134741 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false | 0 |
dd6ce2b657558e2e474979dcaebf827c2c99b94d | 19,310,172,981,137 | 95d5afb491e08c04936a03f5506a6113e7633381 | /app/src/main/java/test/example/com/counselor/view/task/showtask/ShowTaskPresenter.java | 59d458b738c380c03232817a8118d6cb852f6196 | [] | no_license | SliD007/Counselor2 | https://github.com/SliD007/Counselor2 | e5ab9bebb501e70596f96a03b68d79db63fa77d8 | 8519fae9644af3c00ccaa2846214c5648d6890a1 | refs/heads/master | 2021-01-24T04:20:07.346000 | 2018-01-24T10:38:57 | 2018-01-24T10:38:57 | 115,119,982 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test.example.com.counselor.view.task.showtask;
import android.content.Context;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import java.io.File;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Response;
import test.example.com.counselor.util.Constants;
import test.example.com.counselor.util.Urls;
/**
* Created by Sli.D on 2017/12/25.
*/
public class ShowTaskPresenter {
private TaskDetialEntity taskDetialEntity;
private IShowTaskView mIShowTaskView;
private IShowTaskModel mIShowTaskModel;
public ShowTaskPresenter(Context context, IShowTaskView iShowTaskView) {
this.mIShowTaskView = iShowTaskView;
mIShowTaskModel = new ShowTaskModel();
}
public void changeTaskState(int id, int fromWhere){
HashMap<String,String> params = new HashMap<>();
params.put("id",id+"");
params.put("fromWhere",fromWhere+"");
Log.e("changeTaskState",params.toString());
OkGo.post(Urls.ChangeTaskStateURL)
.params(params)
.cacheKey(Constants.getAppCacheFolder())
// .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
.cacheTime(-1)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
Log.e("changeTaskState","response:"+response.toString());
Log.e("changeTaskState","onSuccess:"+s);
JSONObject object = JSON.parseObject(s);
if (object.getInteger("code")==0){
mIShowTaskView.changeTaskStateSuccess();
}else {
mIShowTaskView.changeTaskStateFailed();
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
mIShowTaskView.requestTaskConfigurationFailed();
}
@Override
public void onAfter(String s, Exception e) {
super.onAfter(s, e);
}
});
}
public void requestTaskDetial(int id, int fromWhere){
HashMap<String,String> params = new HashMap<>();
params.put("id",id+"");
params.put("fromWhere",fromWhere+"");
Log.e("requestTaskDetial",params.toString());
OkGo.post(Urls.TASKConfigurationURL)
.params(params)
.cacheKey(Constants.getAppCacheFolder())
// .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
.cacheTime(-1)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
// Log.e("requestTaskDetial","response:"+response.toString());
Log.e("requestTaskDetial","onSuccess:"+s);
JSONObject object = JSON.parseObject(s);
if (object.getInteger("code")==0){
saveValue(object);
mIShowTaskView.requestTaskConfigurationSuccess();
}else {
mIShowTaskView.requestTaskConfigurationFailed();
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
mIShowTaskView.requestTaskConfigurationFailed();
}
@Override
public void onAfter(String s, Exception e) {
super.onAfter(s, e);
}
});
}
public void downLoadTaskFile(String url, String fileName){
// Log.e("downLoadContract","fileName:"+Constants.getAppDownloadFolder());
OkGo.<File>get(url)//
.tag(this)//
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new FileCallback(Constants.getAppDownloadFolder(),fileName) {
@Override
public void onSuccess(File file, Call call, Response response) {
Log.e("downLoadContract","onSuccess:"+response.toString());
mIShowTaskView.downloadTaskFileSuccess();
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
Log.e("downLoadContract","/storage/emulated/0/download/:"+response.toString());
mIShowTaskView.downloadTaskFileFialed();
}
});
}
public void saveValue(JSONObject object){
JSONObject value = object.getJSONObject("value");
// Log.e("requestTask",""+value.toString());
taskDetialEntity = JSONObject.parseObject(value.toString(),TaskDetialEntity.class);
mIShowTaskModel.setTaskDetialEntity(taskDetialEntity);
// Log.e("requestTask",""+taskDetialEntity.toString());
}
public TaskDetialEntity getTaskDetialEntity(){
return mIShowTaskModel.getTaskDetialEntity();
}
}
| UTF-8 | Java | 5,695 | java | ShowTaskPresenter.java | Java | [
{
"context": "xample.com.counselor.util.Urls;\n\n/**\n * Created by Sli.D on 2017/12/25.\n */\n\npublic class ShowTaskPresente",
"end": 516,
"score": 0.9980185627937317,
"start": 511,
"tag": "USERNAME",
"value": "Sli.D"
}
] | null | [] | package test.example.com.counselor.view.task.showtask;
import android.content.Context;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import java.io.File;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Response;
import test.example.com.counselor.util.Constants;
import test.example.com.counselor.util.Urls;
/**
* Created by Sli.D on 2017/12/25.
*/
public class ShowTaskPresenter {
private TaskDetialEntity taskDetialEntity;
private IShowTaskView mIShowTaskView;
private IShowTaskModel mIShowTaskModel;
public ShowTaskPresenter(Context context, IShowTaskView iShowTaskView) {
this.mIShowTaskView = iShowTaskView;
mIShowTaskModel = new ShowTaskModel();
}
public void changeTaskState(int id, int fromWhere){
HashMap<String,String> params = new HashMap<>();
params.put("id",id+"");
params.put("fromWhere",fromWhere+"");
Log.e("changeTaskState",params.toString());
OkGo.post(Urls.ChangeTaskStateURL)
.params(params)
.cacheKey(Constants.getAppCacheFolder())
// .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
.cacheTime(-1)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
Log.e("changeTaskState","response:"+response.toString());
Log.e("changeTaskState","onSuccess:"+s);
JSONObject object = JSON.parseObject(s);
if (object.getInteger("code")==0){
mIShowTaskView.changeTaskStateSuccess();
}else {
mIShowTaskView.changeTaskStateFailed();
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
mIShowTaskView.requestTaskConfigurationFailed();
}
@Override
public void onAfter(String s, Exception e) {
super.onAfter(s, e);
}
});
}
public void requestTaskDetial(int id, int fromWhere){
HashMap<String,String> params = new HashMap<>();
params.put("id",id+"");
params.put("fromWhere",fromWhere+"");
Log.e("requestTaskDetial",params.toString());
OkGo.post(Urls.TASKConfigurationURL)
.params(params)
.cacheKey(Constants.getAppCacheFolder())
// .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
.cacheTime(-1)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
// Log.e("requestTaskDetial","response:"+response.toString());
Log.e("requestTaskDetial","onSuccess:"+s);
JSONObject object = JSON.parseObject(s);
if (object.getInteger("code")==0){
saveValue(object);
mIShowTaskView.requestTaskConfigurationSuccess();
}else {
mIShowTaskView.requestTaskConfigurationFailed();
}
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
mIShowTaskView.requestTaskConfigurationFailed();
}
@Override
public void onAfter(String s, Exception e) {
super.onAfter(s, e);
}
});
}
public void downLoadTaskFile(String url, String fileName){
// Log.e("downLoadContract","fileName:"+Constants.getAppDownloadFolder());
OkGo.<File>get(url)//
.tag(this)//
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new FileCallback(Constants.getAppDownloadFolder(),fileName) {
@Override
public void onSuccess(File file, Call call, Response response) {
Log.e("downLoadContract","onSuccess:"+response.toString());
mIShowTaskView.downloadTaskFileSuccess();
}
@Override
public void onError(Call call, Response response, Exception e) {
super.onError(call, response, e);
Log.e("downLoadContract","/storage/emulated/0/download/:"+response.toString());
mIShowTaskView.downloadTaskFileFialed();
}
});
}
public void saveValue(JSONObject object){
JSONObject value = object.getJSONObject("value");
// Log.e("requestTask",""+value.toString());
taskDetialEntity = JSONObject.parseObject(value.toString(),TaskDetialEntity.class);
mIShowTaskModel.setTaskDetialEntity(taskDetialEntity);
// Log.e("requestTask",""+taskDetialEntity.toString());
}
public TaskDetialEntity getTaskDetialEntity(){
return mIShowTaskModel.getTaskDetialEntity();
}
}
| 5,695 | 0.547147 | 0.54381 | 149 | 37.221478 | 26.902969 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.711409 | false | false | 0 |
62e7cbf4e377caeda304bc082d96dcdc0ee0ba48 | 8,418,135,911,441 | 9812eeec4c8907682132a442093ea3934d058f7f | /chapter3/src/main/java/com/smart/pointcuttest/AspectJTest.java | dd50a98fd8f2d096012279a8ed19d81e957a9b0d | [] | no_license | shxiq01/spring3.0 | https://github.com/shxiq01/spring3.0 | 877f389355e5a5bdbea6a1cc9d0aded074fffdc3 | 4012ba86c6011e340cb9ddda6996207a438049d2 | refs/heads/master | 2021-06-05T20:27:27.653000 | 2016-11-13T09:19:58 | 2016-11-13T09:19:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smart.pointcuttest;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* Created by Administrator on 2016/11/13.
*/
@Aspect
public class AspectJTest {
@Before("execution(* *greet(..)) && args(name)")
public void aspectjTest(String name){
System.out.println("hello,Mr"+name);
}
@AfterReturning(value = "execution(* *greet(..))")
public void after(){
System.out.println("**********************");
}
}
| UTF-8 | Java | 547 | java | AspectJTest.java | Java | [] | null | [] | package com.smart.pointcuttest;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* Created by Administrator on 2016/11/13.
*/
@Aspect
public class AspectJTest {
@Before("execution(* *greet(..)) && args(name)")
public void aspectjTest(String name){
System.out.println("hello,Mr"+name);
}
@AfterReturning(value = "execution(* *greet(..))")
public void after(){
System.out.println("**********************");
}
}
| 547 | 0.645338 | 0.630713 | 22 | 23.863636 | 20.933434 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.318182 | false | false | 0 |
50553339adc309a450de9d302aa587f0e1ffacb3 | 8,418,135,911,097 | 64e9f20691c5763bfe1dbfce37aa17e56efc9d84 | /UIDemo/interfacemodle/src/main/java/com/linktrust/student/interfacemodle/FunctionNoParamHasResult.java | 91db2b45d17d2368f12ca6410d2b63a44dc305c2 | [] | no_license | 18098168100/UIDemo | https://github.com/18098168100/UIDemo | 4ce587a13fd51a26d9bb8e8bf743644c8f2dbc1b | 7904adc9b3f14d5dd9a0f889048f2e1a4b7fe6a7 | refs/heads/master | 2023-05-05T08:30:57.095000 | 2021-06-04T03:51:00 | 2021-06-04T03:51:00 | 371,264,577 | 1 | 0 | null | false | 2021-05-27T12:26:32 | 2021-05-27T06:07:05 | 2021-05-27T07:52:47 | 2021-05-27T12:13:44 | 499 | 1 | 0 | 1 | Java | false | false | package com.linktrust.student.interfacemodle;
/**
* 项目名称 :UIDemo
* 包名:com.linktrust.student.interfacemodle
* 类描述:describe
* 创建人:hh
* 创建时间:2019/7/15 9:36
*/
public abstract class FunctionNoParamHasResult<T> extends Function{
public FunctionNoParamHasResult(String functionName) {
super(functionName);
}
public abstract T function();
}
| UTF-8 | Java | 395 | java | FunctionNoParamHasResult.java | Java | [] | null | [] | package com.linktrust.student.interfacemodle;
/**
* 项目名称 :UIDemo
* 包名:com.linktrust.student.interfacemodle
* 类描述:describe
* 创建人:hh
* 创建时间:2019/7/15 9:36
*/
public abstract class FunctionNoParamHasResult<T> extends Function{
public FunctionNoParamHasResult(String functionName) {
super(functionName);
}
public abstract T function();
}
| 395 | 0.721763 | 0.694215 | 17 | 20.352942 | 21.048798 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.176471 | false | false | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.